* 首先将TensorFlow Python文件从版本1.x转换为版本2.x
安装了tensorflow后,在命令提示符cmd中使用 tf_upgrade_v2 将TensorFlow
Python文件从版本1.x转换为版本2.x,按如下操作:
tf_upgrade_v2 --infile file_v1.py --outfile file_v2.py
转换成功后会生成一个report.txt文件,里面记录了做出修改的地方,如下所示:
TensorFlow 2.0 Upgrade Script ----------------------------- Converted 1 files
Detected 0 issues that require attention
--------------------------------------------------------------------------------
================================================================================
Detailed log follows:
================================================================================
--------------------------------------------------------------------------------
Processing file 'D:\\ProgramData\\Workspace\\bp_network.py' outputting to
'D:\\ProgramData\\Workspace\\bp_network_new.py'
--------------------------------------------------------------------------------
14:17: INFO: Renamed 'tf.random_normal' to 'tf.random.normal' 15:17: INFO:
Renamed 'tf.random_normal' to 'tf.random.normal' 16:4: INFO: Renamed
'tf.placeholder' to 'tf.compat.v1.placeholder' 17:4: INFO: Renamed
'tf.placeholder' to 'tf.compat.v1.placeholder' 21:17: INFO: Added keywords to
args of function 'tf.reduce_mean' 21:37: INFO: Renamed 'tf.log' to
'tf.math.log' 22:13: INFO: Renamed 'tf.train.AdamOptimizer' to
'tf.compat.v1.train.AdamOptimizer' 29:5: INFO: Renamed 'tf.Session' to
'tf.compat.v1.Session' 30:14: INFO: Renamed 'tf.initialize_all_variables' to
'tf.compat.v1.initialize_all_variables'
--------------------------------------------------------------------------------
* RuntimeError: tf.placeholder() is not compatible with eager execution.
从上面可以看到已经将 tf.placeholder() 转换为兼容版本的 tf.compat.v1.placeholder() ,但运行时依然出现了错误
“tf.placeholder() is not compatible with eager execution.”,意思是 placeholder 和
eager execution 不兼容,因为 TensorFlow 2.x 是默认开启 eager execution
的,所以需要禁用该功能,在文件的最前面添加下面这句代码就可以运行了
import tensorflow as tf tf.compat.v1.disable_eager_execution() # 禁用tf的eager
execution功能
* AttributeError: module 'tensorflow' has no attribute 'contrib'
版本1.x:tf.contrib.layers.l2_regularizer() 转换为版本2.x:tf.keras.regularizers.l2()