Roberto Buzzini
Roberto Buzzini

Reputation: 19

How to fix: AttributeError: module 'tensorflow' has no attribute 'contrib'

I'm training a LSTM and I'm defining parameters and regression layer. I get the error in the title with this code:

 lstm_cells = [
    tf.contrib.rnn.LSTMCell(num_units=num_nodes[li],
                            state_is_tuple=True,
                            initializer= tf.contrib.layers.xavier_initializer()
                           )
 for li in range(n_layers)]

drop_lstm_cells = [tf.contrib.rnn.DropoutWrapper(
    lstm, input_keep_prob=1.0,output_keep_prob=1.0-dropout, state_keep_prob=1.0-dropout
) for lstm in lstm_cells]
drop_multi_cell = tf.contrib.rnn.MultiRNNCell(drop_lstm_cells)
multi_cell = tf.contrib.rnn.MultiRNNCell(lstm_cells)

w = tf.get_variable('w',shape=[num_nodes[-1], 1], initializer=tf.contrib.layers.xavier_initializer())
b = tf.get_variable('b',initializer=tf.random_uniform([1],-0.1,0.1))

I'm using tensorflow2 and I have already read the https://www.tensorflow.org/guide/migrate guide and I think almost everything on the net. But I'm not able to solve it. How can I do it?

Upvotes: 2

Views: 9300

Answers (3)

Seth Kitchen
Seth Kitchen

Reputation: 1566

tf.contrib.rnn.LSTMCell -> tf.compat.v1.nn.rnn_cell.LSTMCell or tf.keras.layers.LSTMCell

tf.contrib.rnn.DropoutWrapper -> tf.compat.v1.nn.rnn_cell.DropoutWrapper or tf.keras.layers.DropOut

tf.contrib.rnn.MultiRNNCell -> tf.compat.v1.nn.rnn_cell.MultiRNNCell or tf.keras.layers.RNN

Upvotes: 3

hansoko
hansoko

Reputation: 389

This error occurs because the contrib module has been removed from version 2 of tensorflow. There are two solutions to this problem:

  1. You can delete the current package and install one of the Series 1 versions.

  2. You can use this command, which is also compatible with the version two package: Use tf.compat.v1.nn.rnn_cell.LSTMCell instead of tf.contrib.rnn.LSTMCell and use tf.initializers.GlorotUniform () instead of tf.contrib.layers.xavier_initializer () in other command which include rnn you can use tf.compat.v1.nn.rnn_cell.

Upvotes: 4

Saurav Rai
Saurav Rai

Reputation: 2367

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

Upvotes: 0

Related Questions