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

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’的问题


作者:落花雨96原文地址:https://blog.csdn.net/qq_44368508/article/details/126994477

%s 个评论

要回复文章请先登录注册