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

R语言Keras CNN代码报错:unused argument (grayscale = FALSE)

R Keras image_load 报错 unused argument (grayscale = FALSE) 但未显式使用该参数

问题描述

此前代码可正常运行,测试集准确率达94%-98%,但近期出现以下错误:

Error in (function (path, color_mode = "rgb", target_size = NULL, interpolation = "nearest", : unused argument (grayscale = FALSE)
Called from: do.call(keras$preprocessing$image$load_img, args)
Browse[1]> test_data <- prepare_data(test_dir)
Error during wrapup: unused argument (grayscale = FALSE)
Error: no more error handlers available (recursive errors?); invoking 'abort' restart

代码中调用image_load时仅指定了target_size参数,未使用已被废弃的grayscale参数,仍触发该错误。

解决方案

1. 显式指定color_mode参数

修改preprocess_image函数中的image_load调用,显式声明颜色模式替代隐式默认值:

preprocess_image <- function(image_path) {
  # 显式指定color_mode为rgb,匹配3通道设置
  image <- image_load(image_path, target_size = c(img_width, img_height), color_mode = "rgb")
  image <- image_to_array(image) / 255
  image <- array_reshape(image, c(1, img_width, img_height, channels))
  return(image)
}

新版本Keras已移除grayscale参数,统一使用color_mode:"rgb"对应3通道,"grayscale"对应单通道,显式指定可避免底层参数传递冲突。

2. 检查并更新Keras包版本

运行以下命令查看当前版本:

packageVersion("keras")

若版本较旧,执行更新:

install.packages("keras")
keras::install_keras()

更新后重启R会话,确保加载最新的函数定义。

3. 清理缓存并重新加载包

若更新后仍有问题,先卸载再重新加载Keras:

detach("package:keras", unload=TRUE)
library(keras)

原因说明

Keras R包更新后,彻底移除了grayscale参数,改用color_mode。即使你未显式使用grayscale,旧版本image_load的底层默认逻辑可能仍在传递该废弃参数给TensorFlow Keras的底层函数,而新版本函数已不再接受该参数,从而触发错误。显式指定color_mode可覆盖旧默认行为,解决参数不兼容问题。

内容的提问来源于stack exchange,提问作者Lennart Hampel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 18:40:18