位置:- 正文

解决 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等类似的问题(解决问题)

编辑:rootadmin
解决 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等类似的问题 1、项目场景:

推荐整理分享解决 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等类似的问题(解决问题),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:解决的英文,解决问题,解决的英文,解决的英文,解决烧心最快方法,解决口苦最快的方法,解决烧心最快方法,解决口苦最快的方法,内容如对您有帮助,希望把文章链接给更多的朋友!

使用tensorflow2.x版本的时候,使用调用tensorflow1.x函数的代码时,常常会出现module ‘tensorflow’ has no attribute ‘contrib’这样的问题,这是由于tensorflow2.x废弃了很多tensorflow1.x API接口,本文针对常见的几种错误来使tf2.0不降版本也能运行代码。

2、问题描述和解决办法

1、报错AttributeError: module ‘tensorflow’ has no attribute ‘random_normal’

在报错的行数将tf.random_normal修改成tf.random.normal即可

代码修改前:

w = tf.Variable(tf.random_normal([num_neurons[-1], 1]))

代码修改后:

w = tf.Variable(tf.random.normal([num_neurons[-1], 1])

2、报错 AttributeError: module ‘tensorflow’ has no attribute ‘placeholder’

解决 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等类似的问题(解决问题)

将前边的import tensorflow改成兼容处理的tensorflow.compat.v1,再禁用eager_execution

代码修改前:

import tensorflow as tf

代码修改后:

import tensorflow.compat.v1 as tftf.compat.v1.disable_eager_execution()

3、报错AttributeError: module ‘tensorflow’ has no attribute ‘contrib’

这个是比较麻烦的,因为tensorflow2.x版本已经没有contrib库,但是读者可以试试下面的方法 首先用placeholder的方法,先修改import tensorflow as tf 改成

import tensorflow.compat.v1 as tftf.compat.v1.disable_eager_execution()

BasicLSTMCell处理方法,DropoutWrapper和MultiRNNCell同理 代码修改前:

cell = tf.contrib.rnn.BasicLSTMCell(num_units=units, forget_bias=0.9)

代码修改后:

cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=units,forget_bias=0.9)

将contrib.rnn 改成 nn.rnn_cell,如果使用了static_rnn类似的,就把contrib.rnn改成nn即可

代码修改前:

outputs, _ = tf.contrib.rnn.static_rnn(stacked_lstm_cells, inputs, dtype=tf.float32)

代码修改后:

outputs, _ = tf.nn.static_rnn(stacked_lstm_cells, inputs, dtype=tf.float32)

参考博客 ①tf2.0不降版本也能完美解决module ‘tensorflow’ has no attribute ‘contrib’ 等类似的问题 ②tf2.0不降版本也能完美解决module ‘tensorflow’ has no attribute ‘contrib’的问题

本文链接地址:https://www.jiuchutong.com/zhishi/285102.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/285103.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络