项目场景:
tensorflow 版本 不兼容产生的报错
问题描述:
1.AttributeError: module ‘tensorflow’ has no attribute ‘random_uniform’
解决办法:tf2.0中用tf.random.uniform代替了random_uniform
2.RuntimeError: loss
passed to Optimizer.compute_gradients should be a funct
报错行:
train = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
解决办法:函数改为 train = tf.compat.v1.train.GradientDescentOptimizer(0.01).minimize(cost)
官方文档:
tensorflow文档
3.AttributeError: module ‘tensorflow’ has no attribute ‘Session’
报错行
with tf.Session() as sess:
解决办法:在新的Tensorflow 版本中已经移除了Session这一模块,改换运行代码
tf.compat.v1.Session()
4.RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
该流图为空,但是在tensorflow2.0之后已经不再需要用到tf.Session了
在tf2.0中,所有运算仅以张量形式进行,但可以在运算结束时将其变为数组形式,所以将张量改为numpy形式
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 去警告
def tensorflowdemo():
a = tf.constant(12)
b = tf.constant(78)
c = a + b
print("c = ", c)
print("cval= ", c.numpy())
5.ValueError: Dimension 0 in both shapes must be equal, but are 10 and 3. Shapes are [10,?] and [3,10].
解决办法:值错误:两种形状的维度必须相等,不可以顺便改形状
6.AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’
报错行:
c = tf.placeholder(dtype=tf.float32, shape=[3, 2])
解决办法:tensorflow版本不兼容问题,所以更改导入模块方式,就可以在tensorflow2下使用tensorflow1的方法
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()