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

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

时间2025-05-02 06:56:40分类IT科技浏览7430
导读: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
能领腾讯手游游戏礼包的软件(哪些游戏签到送话费-近期六款腾讯游戏试玩升级送Q币、微信红包奖励!) 手机上看新闻领红包是真的吗(看新闻领红包的软件有哪些-【关注】还在“刷新闻赚现金”?当心碰触到法律底线)