首页IT科技module x(解决 AttributeError: module ‘tensorflow‘ has no attribute ‘contrib‘ 等类似的问题)

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

时间2025-06-13 21:32:05分类IT科技浏览8639
导读:1、项目场景: 使用tensorflow2.x版本的时候,使用调用tensorflow1.x函数的代码时,常常会出现module ‘tensorflow’ has no attribute ‘contrib’这样的问题,这是由于tensorflow2.x废弃了很多tensorflow1.x...

1                、项目场景:

使用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’

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

代码修改前:

import tensorflow as tf

代码修改后:

import tensorflow.compat.v1 as tf tf.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 tf tf.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’的问题

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
高亮显示行和列(Vxe-table 高亮当前行) 从排名下降到权重提升(你需要知道的基础知识)