R语言Keras LSTM多变量输入维度配置与基数歧义报错解决
问题原因
- 输入数组维度顺序错误:Keras时序模型要求输入维度为
(样本数, 时间步, 特征数),你构造的arr_x维度是(10,4,100),会被模型识别为仅有10个样本,和100个标签的数量不匹配,触发基数歧义报错。 - 模型结构不匹配输出要求:你开启了LSTM层的
return_sequences = TRUE,会输出每个时间步的计算结果,无法直接和一维标签适配。 - 编译参数配置错误:二分类任务需要指定损失函数为
binary_crossentropy,你误将其放在了评估指标参数中。
修正代码
library("keras") # 构造原始数据 x <- data.frame( x1 = sample(c(0,1), replace=TRUE, size=1000), x2 = sample(c(0,1), replace=TRUE, size=1000), x3 = sample(c(0,1), replace=TRUE, size=1000), x4 = sample(c(0,1), replace=TRUE, size=1000) ) y <- data.frame(y = sample(c(0,1), replace=TRUE, size=100)) # 按时间步切分样本 x_list <- list() for(i in 1:100) { # 若要使用全部1000行数据,可将切片改为 x[(10*(i-1)+1) : (10*i), ] x_list[[i]] <- x[(10*i+1) :((1+i)*10),] } # 调整输入数组维度为 (样本数, 时间步, 特征数) arr_x <- array_reshape( as.numeric(unlist(x_list)), dim = c(length(x_list), dim(x_list[[1]])[1], dim(x_list[[1]])[2]) ) # 标签转换为矩阵格式 y <- as.matrix(y) # 构造适配的LSTM模型 lstm_model <- keras_model_sequential() lstm_model %>% layer_lstm( units = 64, input_shape = c(10,4), return_sequences = FALSE # 仅输出最后一个时间步的结果,适配单值输出需求 ) %>% layer_dense(units = 1, activation = "sigmoid") # 二分类输出层 # 修正编译参数 lstm_model %>% compile( optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = 'accuracy' ) # 模型训练 lstm_model %>% fit( x = arr_x, y = y, batch_size = 1, epochs = 20, verbose = 1, shuffle = FALSE )
内容的提问来源于stack exchange,提问作者patrick
相关产品推荐
相关产品推荐

