TensorFlow2.x和1.x版本的代码差别问题

import tensorflow as tf

替换为:

import tensorflow.compat.v1 as tf

tf.disable_v2_behavior()

①AttributeError: module 'tensorflow' has no attribute 'placeholder'

解决办法:将tf.placeholder改成tf.compat.v1.placeholder

在Anaconda3\envs\tensorflow\lib\site-packages\keras\backend\tensorflow_backend.py文件下,将import tensorflow as tf替换为

import tensorflow.compat.v1 as tf

tf.disable_v2_behavior()

②AttributeError: module 'tensorflow' has no attribute 'set_random_seed'

解决办法:将tf.set_random_seed(1)改为tf.random.set_seed(1)

③AttributeError: module 'tensorflow' has no attribute 'get_variable'

解决办法:将tf.get_variable改成tf.compat.v1.get_variable

④AttributeError: module 'tensorflow' has no attribute 'global_variables_initializer'

解决办法:将tf.global_variables_initializer()改成tf.compat.v1.global_variables_initializer()

⑤AttributeError: module 'tensorflow' has no attribute 'Session'

解决办法:将with tf.Session() as sess_test改成with tf.compat.v1.Session() as sess_test

⑥AttributeError: module 'tensorflow' has no attribute 'reset_default_graph'

解决办法:将tf.reset_default_graph()改成

#用于清除默认图形堆栈并重置全局默认图形
from tensorflow.python.framework import ops #可不写
ops.reset_default_graph()

⑦RuntimeError: tf.placeholder() is not compatible with eager execution

解决办法:在import tensorflow as tf 后加上tf.compat.v1.disable_eager_execution()

关闭紧急执行,这也可以保证session.run()正常运行。

⑧AttributeError: module 'tensorflow' has no attribute 'contrib'

解决办法:将tf.contrib.layers.xavier_initializer改为tf.initializers.GlorotUniform

你可能感兴趣的:(tensorflow)