R语言Keras训练神经网络报错:输入数据不匹配求助
问题描述
使用R语言结合Keras和TensorFlow训练神经网络时,调用fit方法触发以下报错:
Error in py_call_impl(callable, call_args$unnamed, call_args$named) : ValueError: in user code: <...truncated...>/site-packages/keras/src/engine/training.py", line 1080, in train_step y_pred = self(x, training=True) File "/Users/ronypabraham/.virtualenvs/r-tensorflow/lib/python3.9/site-packages/keras/src/utils/traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "/Users/ronypabraham/.virtualenvs/r-tensorflow/lib/python3.9/site-packages/keras/src/engine/input_spec.py", line 197, in assert_input_compatibility raise ValueError( ValueError: Missing data for input "dense_39_input". You passed a data dictionary with keys ['VehPower', 'VehAge', 'DrivAge', 'BonusMalus', 'VehBrand_embedded', 'VehGas_encoded', 'Region_embedded', 'Area_encoded', 'Density']. Expected the following keys: ['dense_39_input']
触发报错的fit代码:
history <- model %>% fit( x = X_train, y = y_train, batch_size = 8, epochs = 50, verbose = 2, validation_split = 0.2 )
报错原因
- 模型构建错误:添加层时使用管道操作但未将结果赋值回
model对象,导致模型结构未正确初始化。 - 输入数据格式不匹配:
X_train为data.frame类型,Keras会将其解析为以列名为键的输入字典,但Sequential模型期望单一张量输入,输入键为默认的层输入名(如dense_39_input),因此出现键不匹配。
解决方案
1. 正确构建模型
将层添加操作通过链式管道赋值给model,确保层被正确添加到模型中:
# Create a simple feedforward neural network model model <- keras_model_sequential() %>% # Add input layer layer_dense(units = 20, activation = "relu", input_shape = 9) %>% # 9 features # Add output layer for count data layer_dense(units = 1, activation = "linear") # 适用于计数数据
2. 转换输入数据格式
将X_train和X_test从data.frame转换为矩阵,避免Keras将其解析为字典输入:
# Predictor variables X_train <- as.matrix(train_data[, c("VehPower", "VehAge", "DrivAge", "BonusMalus", "VehBrand_embedded", "VehGas_encoded", "Region_embedded", "Area_encoded", "Density")]) X_test <- as.matrix(test_data[, c("VehPower", "VehAge", "DrivAge", "BonusMalus", "VehBrand_embedded", "VehGas_encoded", "Region_embedded", "Area_encoded", "Density")])
3. 优化模型编译(可选)
计数数据回归任务中,accuracy指标不适用,建议替换为回归类指标:
# Compile the model model$compile( loss = "poisson", optimizer = optimizer, metrics = c('mean_absolute_error') )
验证修复
运行summary(model)确认模型结构正确,输入形状应为(None, 9),输出层形状为(None, 1),之后重新执行fit方法即可正常训练。
内容的提问来源于stack exchange,提问作者Alinta Wilson
相关产品推荐
相关产品推荐

