使用keras3复现《Deep Learning with R》示例遇Reshape错误求助
错误原因与修复方案
错误根源
你遇到的INVALID_ARGUMENT: Only one input size may be -1, not both 0 and 1错误,核心问题在于归一化参数的结构错误:
使用keras3::zip_lists生成的normalization_values没有保留列名索引,导致后续归一化时无法正确获取每个特征的均值和标准差,最终输入数据被处理成全NaN的无效值。TensorFlow在处理这类无效数据时,内部reshape操作触发了维度错误。
另外需要确保你的数据集是完整的(jena_climate_2009_2016.csv总行数应为420551),否则训练/验证/测试集行数可能小于delay值,导致生成空序列数据集,也会触发类似错误。
修复步骤
1. 修正归一化参数的生成方式
用purrr::transpose替代zip_lists,确保normalization_values可以通过列名正确索引均值和标准差:
library(purrr) # 需要先加载purrr包 normalization_values <- transpose(list(mean = lapply(train_df[input_data_colnames], mean), sd = lapply(train_df[input_data_colnames], sd)))
2. 验证数据集完整性
在代码开头添加一行检查,确认数据集行数符合预期:
full_df <- readr::read_csv("jena_climate_2009_2016.csv") cat("数据集总行数:", nrow(full_df), "\n") # 应输出420551
如果行数不符,重新下载完整数据集。
3. 可选:添加序列有效性检查
在df_to_inputs_and_targets函数中添加检查,避免生成空序列:
df_to_inputs_and_targets <- function(df) { inputs <- df[input_data_colnames] %>% normalize_input_data() %>% as.matrix() targets <- as.array(df$`T (degC)`) # 检查数据集行数是否足够生成序列 if(nrow(inputs) <= delay) { stop(sprintf("数据集仅%d行,小于所需的延迟值%d,无法生成有效序列", nrow(inputs), delay)) } list(head(inputs, -delay), tail(targets, -delay)) }
修改后的完整关键代码片段
library(keras3) library(dplyr) library(purrr) # 新增加载purrr包 # Preparing the Data full_df <- readr::read_csv("jena_climate_2009_2016.csv") cat("数据集总行数:", nrow(full_df), "\n") # 验证数据集完整性 full_df$`Date Time` %<>% as.POSIXct(tz = "Etc/GMT+1", format = "%d.%m.%Y %H:%M:%S") num_train_samples <- round(nrow(full_df) * 0.5) num_val_samples <- round(nrow(full_df) * 0.25) num_test_samples <- nrow(full_df) - num_train_samples - num_val_samples train_df <- full_df[seq(num_train_samples), ] val_df <- full_df[seq(from = nrow(train_df) + 1, length.out = num_val_samples), ] test_df <- full_df[seq(to = nrow(full_df), length.out = num_test_samples), ] ## Normalize the data input_data_colnames <- names(full_df) %>% setdiff(c("Date Time")) # 修正归一化参数生成方式 normalization_values <- transpose(list(mean = lapply(train_df[input_data_colnames], mean), sd = lapply(train_df[input_data_colnames], sd))) str(normalization_values) normalize_input_data <- function(df) { normalize <- function(x, center, scale) (x - center) / scale for(col_nm in input_data_colnames) { col_nv <- normalization_values[[col_nm]] df[[col_nm]] %<>% normalize(., col_nv$mean, col_nv$sd) } df } ## 后续代码保持不变...
内容的提问来源于stack exchange,提问作者Yang Yang
相关产品推荐
相关产品推荐

