使用R语言neuralnet包训练神经网络时遇维度错误求助
神经网络训练维度错误修正方案
报错信息
Error in x[0, , drop = FALSE] : número incorreto de dimensiones
原问题代码
set.seed(123) library(neuralnet) library(caret) # data1: training data sex <- factor(sample(c("male", "female"), size = 1000, replace = TRUE)) height <- rnorm(1000, mean = c(1.8, 1.6)[sex]) weight <- rnorm(1000, mean = c(80, 60)[sex]) data1 <- data.frame(sex, height, weight) # data2: population data sex <- factor(sample(c("male", "female"), size = 10000, replace = TRUE)) height <- rnorm(1000, mean = c(1.81, 1.61)[sex]) weight <- rnorm(1000, mean = c(81, 61)[sex]) data2 <- data.frame(sex, height, weight) # training net <- neuralnet(sex ~ height + weight, data = data1, hidden = c(10, 10), linear.output = FALSE, threshold = 0.1, stepmax = 10000) trained_net <- train(net, data, error.fun = "ce", stepmax = 1e+07) # Prediction and results predictions <- compute(trained_net, data2[, c("height", "weight")]) predictions_df <- data.frame(predictions$net.result) colnames(predictions_df) <- c("probfemale") result <- cbind(datos2, predictions_df) result$prediccion_sex <- ifelse(resul$probfemale >= 0.5, "female", "male")
问题分析与修正点
- 数据维度不匹配:data2中
height和weight生成时用了rnorm(1000,...),但sex是10000行,导致列维度不一致,这是核心错误来源。 - train()函数误用:caret的
train()不能直接传入neuralnet训练好的对象,且代码中data变量未定义,无需用caret二次训练。 - 变量名拼写错误:预测部分的
datos2应为data2,resul应为result,拼写错误会导致变量找不到。 - 因变量格式问题:neuralnet对因子类型的因变量支持不佳,建议转为二元数值(如female=1,male=0),更适合分类概率预测。
修正后完整代码
set.seed(123) library(neuralnet) # 生成训练数据:将sex转为二元数值 sex <- sample(c(0, 1), size = 1000, replace = TRUE) # 0=male, 1=female height <- rnorm(1000, mean = c(1.8, 1.6)[sex + 1]) # R索引从1开始,+1匹配mean的两个值 weight <- rnorm(1000, mean = c(80, 60)[sex + 1]) data1 <- data.frame(sex, height, weight) # 生成测试数据:修正行数匹配问题 sex <- sample(c(0, 1), size = 10000, replace = TRUE) height <- rnorm(10000, mean = c(1.81, 1.61)[sex + 1]) weight <- rnorm(10000, mean = c(81, 61)[sex + 1]) data2 <- data.frame(sex, height, weight) # 训练神经网络:直接用neuralnet,无需caret的train net <- neuralnet(sex ~ height + weight, data = data1, hidden = c(10, 10), linear.output = FALSE, # 分类问题设为FALSE,输出概率 threshold = 0.1, stepmax = 1e5) # 增大stepmax避免训练提前终止 # 预测并整理结果 predictions <- compute(net, data2[, c("height", "weight")]) predictions_df <- data.frame(probfemale = predictions$net.result) result <- cbind(data2, predictions_df) # 将原始sex转回因子方便对比,生成预测性别 result$sex <- factor(result$sex, levels = c(0,1), labels = c("male", "female")) result$prediccion_sex <- ifelse(result$probfemale >= 0.5, "female", "male") # 查看前几行结果 head(result)
关键说明
- 把因变量转为二元数值后,neuralnet能更稳定处理分类任务,
linear.output=FALSE确保输出是sigmoid激活后的概率值。 - 修正了data2的行数问题,保证所有列维度一致。
- 移除了不必要的caret包调用,简化训练流程,避免函数误用。
- 修正了变量拼写错误,确保代码可运行。
内容的提问来源于stack exchange,提问作者Fran
相关产品推荐
相关产品推荐

