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

Keras构建回归神经网络报错:输入形状不兼容问题求助

解决Keras回归模型输入形状不匹配的ValueError问题

问题原因

报错ValueError: Input 0 of layer "sequential_3" is incompatible with the layer: expected shape=(None, 60), found shape=(None, 59)的核心原因是模型定义的输入特征维度与实际训练数据的特征数量不匹配:

  • 划分训练数据时,你取了前59列作为输入特征:training <- data[ind==1, 1:59],实际输入特征数为59
  • 但模型定义时指定的输入形状是input_shape = c(60),期望接收60个特征的输入,两者产生冲突

修正步骤

1. 修正模型的输入形状

将模型第一层的input_shape参数改为实际的特征数量59,修改后的模型定义代码如下:

#Creating the model specification
model <- keras_model_sequential() 
model %>%
  layer_dense(units = 41, activation = 'relu', input_shape = c(59)) %>%  # 将60改为59
  layer_dense(units = 1)

2. (可选)修正数据集划分的概率参数

注意到你划分数据集时的概率设置为prob = c(0.7,.03),测试集占比仅3%,不符合常规划分比例,建议改为prob = c(0.7, 0.3),让测试集占30%:

#Partition 
set.seed(1234)
ind <- sample(2, nrow(data), replace = T, prob = c(0.7, 0.3))  # 修正0.03为0.3
training <- data[ind==1, 1:59]
test <- data[ind==2, 1:59]
trainingtarget <- data[ind==1, 60]
testtarget <- data[ind==2, 60]

验证修正效果

修改完成后重新运行代码,模型将能正确接收训练数据的输入,不会再出现形状不匹配的报错。


内容的提问来源于stack exchange,提问作者Pratham Dave

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 17:55:45