Tensorflow1和2不兼容,导致的常见问题及解决办法

tf2中删除或者改变了tf1的中很多函数接口,若是在tf2的环境中中用了tf1的代码,则会报很多错。

两个解决办法

一是换回tf1.x版本,eg:

pip install tensorflow==1.4.0

二是讲tf1的代码改为tf2可以运行的

将使用了tf1代码中的

import tensorflow as tf

更改为:

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

这个替换可以减少很多修改和报错,但还是会有一些个别问题,单独解决。

常见的问题及解决办法:

一、AttributeError类

1.AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’

采用通用解决办法,见上

2.AttributeError: module ‘tensorflow_core.compat.v1’ has no attribute ‘contrib’

将源码:

initializer = tf.contrib.layers.xavier_initializer(seed = 1)

替换为

initializer = tf.truncated_normal_initializer(stddev=0.1)
3.AttributeError: ‘module’ object has no attribute ‘rnn_cell’

解决办法:将tf.nn.rnn_cell替换为tf.contrib.rnn

4.AttributeError: ‘module’ object has no attribute ‘pack’

解决办法:将pack替换为stack

5.AttributeError: module ‘tensorflow’ has no attribute ‘Session’

解决办法:在新的Tensorflow 2.0版本中已经移除了Session这一模块,改换运行代码

tf.compat.v1.Session()

6.AttributeError: module ‘tensorflow’ has no attribute ‘random_normal’

解决办法:将random_normal方法已经换为:random.normal

7.AttributeError: module ‘tensorflow’ has no attribute ‘mul’

解决办法:tf.mul已经在新版本中被移除,请使用 tf.multiply 代替

8.AttributeError: module ‘tensorflow’ has no attribute ‘variable_scope’

采用通用解决办法,见上。

类似的还有:

①tf.train.GradientDescentOptimizer()改成tf.compat.v1.train.GradientDescentOptimizer()
②tf.random_uniform改成tf.random.uniform
③tf.global_variables_initializer()变成tf.compat.v1.global_variables_initializer()
④tf.Session()变成tf.compat.v1.Session()
⑤tf.placeholder变成tf.compat.v1.placeholder
⑥当tf.compat.v1.placeholder占位时,出现错误:tf.compat.v1.placeholder() is not compatible with eager execution.要在占位前面加上一行:tf.compat.v1.disable_eager_execution()

二、ValueError类

1. ValueError: Only call softmax_cross_entropy_with_logits with named arguments (labels=…, logits=…, …)

按照提示,需要将括号内的形参写出,即(logits=pre, lables=tru)而非(pre,tru)

2. ValueError: Variable Wemb/Adam/ does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?

需要定义scope,虽然报错可能是在optimizer处提示,但需要在定义模型时增加scope,即

with tf.variable_scope(tf.get_variable_scope()) as scope:
# model construction

参考:

1.https://www.jb51.net/article/141988.htm(浅谈Tensorflow由于版本问题出现的几种错误及解决方法)

2.https://blog.csdn.net/weixin_46824122/article/details/105421112(Tensorflow2版本对于Tensorflow1版本的部分变化)

GitHub 加速计划 / te / tensorflow
184.54 K
74.12 K
下载
一个面向所有人的开源机器学习框架
最近提交(Master分支:23 天前 )
a49e66f2 PiperOrigin-RevId: 663726708 1 个月前
91dac11a This test overrides disabled_backends, dropping the default value in the process. PiperOrigin-RevId: 663711155 1 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐