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

如何解决AttributeError: module 'tensorflow' has no attribute 'placeholder'错误

解决MaskRCNN训练时的AttributeError: module 'tensorflow' has no attribute 'placeholder'错误

问题场景

运行MaskRCNN训练代码时触发如下错误:

AttributeError: module 'tensorflow' has no attribute 'placeholder'

涉及代码片段:

config = CustomConfig()
model = modellib.MaskRCNN (mode= "training", config=config, model_dir=DEFAULT_LOGS_DIR)
weights_path = COCO_WEIGHTS_PATH # Download weights file
if not os.path.exists(weights_path):
  utils.download_trained_weights(weights_path)
model.load_weights(weights_path, by_name=True, exclude=["mrcnn_class_logits", 
                                                        "mrcnn_bbox_fc","mrcnn_bbox", 
                                                        "mrcnn_mask"])

当前环境配置

!pip install keras==2.2.5
%tensorflow_version 2.x

报错原因

  1. TensorFlow 2.x 默认启用即时执行(Eager Execution),移除了tf.placeholder这类TensorFlow 1.x的旧API;
  2. 所用MaskRCNN版本基于TensorFlow 1.x开发,无法直接兼容TF2.x;
  3. Keras 2.2.5是为TensorFlow 1.x适配的版本,和TF2.x搭配会产生API调用冲突。

解决方法

方案一:切换到TensorFlow 1.x环境(最简便)

直接将环境切换为TensorFlow 1.x,搭配适配的Keras版本,完全兼容原MaskRCNN代码:

%tensorflow_version 1.x
!pip install keras==2.2.5 -q

重新运行训练代码即可解决该错误。

方案二:修改代码适配TensorFlow 2.x(适合保留TF2.x的场景)

  1. 在代码开头添加禁用即时执行的代码:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
  1. 将代码中所有tf.placeholder替换为tf.compat.v1.placeholder;
  2. 检查并替换其他TF1.x专属API(如tf.Session、tf.variable_scope)为tf.compat.v1下的对应方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:01:09