You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:15:03