Solve AttributeError: module 'tensorflow' has no attribute 'contrib' and other similar problems

1. Project scenario:

When using the tensorflow2.x version, when using the code that calls the tensorflow1.x function, there will often be problems such as module 'tensorflow' has no attribute 'contrib'. This is because tensorflow2.x has abandoned many tensorflow1.x API interfaces. This article aims at several common errors to enable tf2.0 to run the code without downgrading the version.


2. Problem description and solution

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

Change tf.random_normal to tf.random.normal in the number of error lines

代码修改前:

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’

Change the previous import tensorflow to tensorflow.compat.v1 for compatible processing, and then disable 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’

This is more troublesome, because the tensorflow2.x version has no contrib library, but readers can try the following method
First use the placeholder method, first modify import tensorflow as tf to

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

BasicLSTMCell processing method, DropoutWrapper and MultiRNNCell are the same
代码修改前:

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)

Change contrib.rnn to nn.rnn_cell, if you use static_rnn similar, just change contrib.rnn to 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)

Refer to the blog
① tf2.0 can perfectly solve module 'tensorflow' has no attribute 'contrib' and similar problems
without downgrading the version ② tf2.0 can perfectly solve the problem of module 'tensorflow' has no attribute 'contrib' without downgrading the version


Guess you like

Origin blog.csdn.net/qq_44368508/article/details/126994477