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

TensorFlow2.9.1报错:无法从keras.preprocessing.image导入load_img

问题原因
  • 导入错误由Keras版本冲突、API路径变更两个原因共同导致:
    1. 环境内同时存在独立pip安装的Keras库、TensorFlow 2.9.1内置的Keras模块,代码写from keras.xxx import xxx时,Python会优先加载独立安装的Keras,该独立Keras版本和TensorFlow内置Keras的API不对齐,其preprocessing.image模块下没有load_img、img_to_array等函数,直接触发导入报错。
    2. 从TensorFlow 2.9版本开始,image_dataset_from_directory已经从preprocessing模块迁移到utils模块下,旧的导入路径不再保留,即使不存在版本冲突,从keras.preprocessing导入该函数也会报错。
解决方案

两种方案二选一即可,优先推荐第一种,长期稳定性更高:

  • 方案1:将所有Keras相关导入替换为TensorFlow内置Keras的对应路径,从根源避免版本冲突。
    修正后的可运行完整代码如下:
    # 为新图像执行预测
    from tensorflow.keras.preprocessing.image import load_img, img_to_array
    from tensorflow.keras.models import load_model
    
    # 加载并预处理图像
    def load_image(filename):
        # 加载图像,统一尺寸为224*224
        img = load_img(filename, target_size=(224, 224))
        # 转换为数组格式
        img = img_to_array(img)
        # 调整维度为单样本3通道输入格式
        img = img.reshape(1, 224, 224, 3)
        # 像素值中心化处理
        img = img.astype('float32')
        img = img - [123.68, 116.779, 103.939]
        return img
    
    # 加载图像并执行类别预测
    def run_example():
        img = load_image('test.jpg')
        # 加载预训练模型
        model = load_model('final_model.h5')
        # 执行预测
        result = model.predict(img)
        print(result[0])
    
    # 程序入口
    run_example()
    
    如果需要导入image_dataset_from_directory,使用路径from tensorflow.keras.utils import image_dataset_from_directory即可。
  • 方案2:卸载环境中独立安装的Keras包,消除导入优先级冲突,执行以下命令后原有代码可正常运行:
    pip uninstall -y keras
    
    注意执行命令前确认当前Python解释器和运行代码所用的是同一个环境,避免卸载到其他环境的包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 05:06:30