无法使用 tf.contrib

hyp*_*ite 1 python machine-learning attributeerror lstm tensorflow

我导入了 tensorflow 模块,但无法使用 tf.contrib。我不知道是什么问题。我尝试在不同版本中运行它,但我一直得到相同的输出。

模块导入:

import tensorflow.compat.v1 as tf1
tf1.disable_v2_behavior() 
import tensorflow as tf2
Run Code Online (Sandbox Code Playgroud)

代码:

tf2.contrib.rnn.LSTMCell(num_units=num_nodes[li],
                            state_is_tuple=True,
                            initializer= tf.contrib.layers.xavier_initializer()
                           )
Run Code Online (Sandbox Code Playgroud)

输出:

AttributeError: module 'tensorflow' has no attribute 'contrib'
Run Code Online (Sandbox Code Playgroud)

Sac*_*H S 5

我认为问题出在版本上,我在 1.15.2 版本中尝试过,并且对我有用。安装上述版本后,请尝试以下代码,它应该可以工作。

import tensorflow.compat.v1 as tf1
tf1.disable_v2_behavior() 
import tensorflow as tf2 #Tensorflow 1.15.2
from tensorflow.contrib.rnn import LSTMCell


LSTMCell(num_units=num_nodes[li],
                            state_is_tuple=True,
                            initializer= tf.contrib.layers.xavier_initializer()
                           )
Run Code Online (Sandbox Code Playgroud)

但是如果您使用的是 TensorFlow 2.x 版本 contrib 已被弃用,您可以使用以下代码。由于xavier_initializer也在使用 contrib,您可以使用与xavier_initializer相同的GlorotUniform初始化程序。按照下面的代码。

import tensorflow.compat.v1 as tf1
tf1.disable_v2_behavior() 
import tensorflow as tf2 #Tensorflow 2.x

tf2.compat.v1.nn.rnn_cell.LSTMCell(num_units=10,
                            state_is_tuple=True,
                            initializer= tf2.initializers.GlorotUniform()
                           ) 
Run Code Online (Sandbox Code Playgroud)