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

Google Cloud ML中Keras训练InceptionResNetV2报错:'Tensor'无assign属性

解决Google Cloud ML中Keras训练InceptionResNetV2时的AttributeError: 'Tensor' object has no attribute 'assign'错误

这个错误几乎可以肯定是云环境中Keras与TensorFlow的版本不匹配导致的——你本地用的是Keras 2.1.4,但Google Cloud ML默认的TensorFlow/Keras版本可能和你的本地环境存在差异,触发了旧版Keras与新版TensorFlow之间的兼容性问题。

下面是具体的解决步骤:

  • 强制指定与本地一致的依赖版本
    在你的训练代码目录下创建一个requirements.txt文件,明确指定和本地完全相同的Keras、TensorFlow版本:

    keras==2.1.4
    tensorflow==1.8.0  # 这个版本和Keras2.1.4兼容性良好,你可以根据本地实际使用的TF版本调整
    

    Google Cloud ML会在启动训练实例时自动安装这些指定版本的依赖,确保环境和本地一致。

  • 检查并禁用Eager Execution
    如果云环境默认启用了TensorFlow的Eager Execution模式,旧版Keras(比如2.1.4)会出现这类张量操作错误。你可以在训练代码的最开头添加以下代码强制关闭Eager模式:

    import tensorflow as tf
    tf.disable_eager_execution()
    
  • 优化数据加载逻辑适配云环境
    虽然你的错误不是数据读取导致的,但云环境中文件系统权限可能和本地不同,建议替换你当前用os.system复制数据的方式,改用更Pythonic的方法(比如shutil),同时确保临时目录有写入权限:

    import shutil
    import os
    
    # 创建临时目录
    temp_dir = "pauls_tmp"
    os.makedirs(temp_dir, exist_ok=True)
    
    # 复制训练和验证数据
    shutil.copytree(args.train_dir, os.path.join(temp_dir, "train"))
    shutil.copytree(args.val_dir, os.path.join(temp_dir, "validation"))
    

    这样能避免os.system调用可能带来的权限或路径问题。

  • 验证云ML的Python与TensorFlow运行时版本
    确保你提交训练任务时指定的Python版本和本地一致(你本地用的是Python2.7),同时指定匹配的TensorFlow运行时版本,在提交命令中可以通过--runtime-version和--python-version参数指定:

    gcloud ml-engine jobs submit training JOB_NAME \
        --runtime-version=1.8 \
        --python-version=2.7 \
        --package-path=trainer \
        --module-name=trainer.cloud_trainer \
        --region=us-central1 \
        --args="--train_dir=gs://your-bucket/train --val_dir=gs://your-bucket/validation"
    

    这里的--runtime-version=1.8对应TensorFlow1.8.0,和我们在requirements.txt里指定的版本匹配。

按照以上步骤调整后,应该能解决这个兼容性错误,让云环境的训练和本地保持一致。

内容的提问来源于stack exchange,提问作者Paul Spöring

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:09:25