pycharm安装tensorflow是最新版本 2.0开始已经抛弃一些原本函数
报错情况下可以将原本函数tf后加上.compat.v1
一、基本修改
tf.Session() -> tf.compat.v1.Session()
二、定义损失函数 修改前后
报错详情:module 'tensorflow' has no attribute 'log'
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.compat.v1.log(pred), axis=1))
三、使用梯度下降优化器 修改前后
报错详情:module ‘tensorflow._api.v2.train‘ has no attribute ‘GradientDescentOptimize
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
optimizer = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(cost)
四、图片输入占位符 需要新增代码 直接添加即可
报错详情:tf.placeholder() is not compatible with eager execution.
x = tf.placeholder(tf.float32, [None, 784])
# 2.0以上版本增加的compat.v1
tf.compat.v1.disable_eager_execution()
五、没有函数包报错 下载添加
报错详情:from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.examples.tutorials.mnist import input_data
链接:https://pan.baidu.com/s/1uR9ggIjZgmsg7o5lxwAGmg
提取码:61r3
六、 输出.numpy出现报错 需要新增代码 直接添加即可
报错详情:Tensor' object has no attribute 'numpy'
y_true = tf.constant([1, 2])
y_pred = tf.constant([[0.05, 0.95, 0], [0.1, 0.8, 0.1]])
loss = tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred))
scce = tf.keras.losses.SparseCategoricalCrossentropy()
print(loss.numpy())
# 2.0以上版本增加的compat.v1
tf.compat.v1.enable_eager_execution()
七、无法执行sess.run() 需要新增代码 直接添加即可
报错详情:The Session graph is empty. Add operations to the graph before calling run().
with tf.compat.v1.Session() as sess:
for i in range(global_steps):
T_c= sess.run(c,feed_dict={global_: i})
T_C.append(T_c)
F_d = sess.run(d,feed_dict={global_: i})
F_D.append(F_d)
# 2.0以上版本增加的compat.v1
tf.compat.v1.disable_eager_execution()
八、迭代器问题 更改代码方式
报错详情:BatchDataset‘ object has no attribute ‘make_one_shot_iterator‘
data_it = dataset.make_one_shot_iterator()
data_it = tf.compat.v1.data.make_one_shot_iterator(dataset)