TensorFlow v1到v2版本兼容问题汇总与解决方案

  •  首先将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()

  • 12
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Elwin Wong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值