R使用ggplot2绘制神经网络迭代误差仅显示测试集线条问题
问题根因
你的绘图逻辑不存在问题,核心原因是error_df的type字段所有行被错误赋值为test,ggplot2仅会按照唯一的分组值绘制单条曲线,和你选择的绘图数据区间无关。
排查步骤
- 回溯
error_df的构造代码,重点检查训练集、测试集误差合并为数据框的逻辑,常见错误场景包括:type字段赋值被后续代码覆盖,例如先给训练集部分赋值train,又执行了全局赋值error_df$type = "test"覆盖所有行- 合并训练、测试误差时,仅给测试集设置了
type字段,训练集的对应字段缺失,合并后被统一填充为test - 训练过程中实时记录误差时,训练、验证环节的记录逻辑都硬编码写入了
test标签
- 运行
table(error_df$type)打印全量分组统计结果,确认是否存在train分类的记录,若仅返回test的计数即可确认是数据赋值问题
修复示例
错误的error_df构造逻辑示例:
# 错误写法:全局赋值覆盖了所有行的type train_error <- c(0.78, 0.56, 0.41, 0.32, 0.26) test_error <- c(0.79, 0.58, 0.43, 0.36, 0.31) error_df <- data.frame(epoch = rep(1:5, 2), error = c(train_error, test_error)) error_df$type <- "train" error_df$type <- "test"
修正后构造逻辑:
# 正确写法:分组赋值type train_error <- c(0.78, 0.56, 0.41, 0.32, 0.26) test_error <- c(0.79, 0.58, 0.43, 0.36, 0.31) error_df <- rbind( data.frame(epoch = 1:5, error = train_error, type = "train"), data.frame(epoch = 1:5, error = test_error, type = "test") )
修复后正常绘图代码即可输出双曲线:
library(ggplot2) ggplot(error_df, aes(x = epoch, y = error, color = type)) + geom_line(linewidth = 1) + labs(x = "迭代轮次", y = "误差值", color = "数据集类型") + theme_bw()
内容的提问来源于stack exchange,提问作者user16951674
相关产品推荐
相关产品推荐

