如何解决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
报错原因
- TensorFlow 2.x 默认启用即时执行(Eager Execution),移除了
tf.placeholder这类TensorFlow 1.x的旧API; - 所用MaskRCNN版本基于TensorFlow 1.x开发,无法直接兼容TF2.x;
- 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的场景)
- 在代码开头添加禁用即时执行的代码:
import tensorflow as tf tf.compat.v1.disable_eager_execution()
- 将代码中所有
tf.placeholder替换为tf.compat.v1.placeholder; - 检查并替换其他TF1.x专属API(如
tf.Session、tf.variable_scope)为tf.compat.v1下的对应方法。
内容的提问来源于stack exchange,提问作者Magic
相关产品推荐
相关产品推荐

