解决AttributeError: module ‘tensorflow‘ has no attribute ‘placeholder‘问题

PyCharm运行optimize.py出错
Traceback (most recent call last):
File “D:/PyCharm/RelationPrediction-master/code/optimization/optimize.py”, line 241, in
X = tf.placeholder(tf.float32, shape=(None,2))
AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’

查看tensorflow版本

python
import tensorflow as tf
tf.__version__


当前版本为2.3.1
报错原因:tensorflow 2.0版本去掉了placeholder,而tensorflow 1.*版本才有。

解决:将

import tensorflow as tf

替换成下面代码

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

顺便记录一下tensorflow和keras的对应版本

卸载之前的tensorflow版本

在conda环境中删除文件
安装1.4.0版本

pip install tensorflow==1.4.0


安装keras 2.8版本

ImportError: cannot import name ‘tf2’
导入keras的时候出现报错:ImportError: cannot import name ‘tf2’

这是因为keras是tensorflow的高级API
如果keras的版本和tensorflow的版本不一致,就会报错。

用到的版本为tensorflow 1.4,python3.6,对应的keras版本为2.0.8

卸载重装keras 2.0.8版本,python3.6版本

来源:代码小轩

物联沃分享整理
物联沃-IOTWORD物联网 » 解决AttributeError: module ‘tensorflow‘ has no attribute ‘placeholder‘问题

发表评论