【最简单解决办法】:module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘

目录

出现错误界面

1.问题原因

2.解决办法

(1)在调用之前首先添加如下代码块并执行

(2)查找响应函数对应的函数调用前缀。

注:若出现错误也是LSTM预测,可直接复制如下代码:

最后问题解决,代码最后成功运行


anaconda下:

tensorflow版本:tensorflow2.3.0

python版本:python3.7

出现错误界面

 

1.问题原因

原因是tensorflow 2.0版本之后把contrib这个库取消了

2.解决办法

简单说法:到tensorflow官网查询相对应的函数调用方式即可。

(1)在调用之前首先添加如下代码块并执行

# import tensorflow as tf
# tf.compat.v1.reset_default_graph()

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

tf.compat.v1.disable_eager_execution()

(2)查找响应函数对应的函数调用前缀。

tensorflow官网TensorFlow (google.cn)

在搜索框直接输入对应函数即可。

以我的函数 DropoutWrapper为例:

直接输入红色框住部分的函数调用即可。

亲测 tf.compat.v1. 对绝大多数部分的函数都可以使用

涉及到tf调用函数的部分全部加上tf.compat.v1.  

最终问题解决,代码执行成功。

注:若出现错误也是LSTM预测,可直接复制如下代码:

def lstm_cell(size_layer):
    return tf.compat.v1.nn.rnn_cell.LSTMCell(size_layer, state_is_tuple = False)

    rnn_cells = tf.compat.v1.nn.rnn_cell.MultiRNNCell(
            [lstm_cell(size_layer) for _ in range(num_layers)],
            state_is_tuple = False,
        )
    self.X = tf.compat.v1.placeholder(tf.compat.v1.float32, (None, None, size))
    self.Y = tf.compat.v1.placeholder(tf.compat.v1.float32, (None, output_size))
    drop = tf.compat.v1.nn.rnn_cell.DropoutWrapper(
            rnn_cells, output_keep_prob = forget_bias
        )
    self.hidden_layer = tf.compat.v1.placeholder(
            tf.compat.v1.float32, (None, num_layers * 2 * size_layer)
        )
    self.outputs, self.last_state = tf.compat.v1.nn.dynamic_rnn(
            drop, self.X, initial_state = self.hidden_layer, dtype = tf.compat.v1.float32
        )
    self.logits = tf.compat.v1.layers.dense(self.outputs[-1], output_size)
    self.cost = tf.compat.v1.reduce_mean(tf.square(self.Y - self.logits))
    self.optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(
            self.cost
        )
        
def forecast():#此处为部分代码
    tf.compat.v1.reset_default_graph()
    modelnn = Model(
        learning_rate, num_layers, df_log.shape[1], size_layer, df_log.shape[1], dropout_rate
    )
    sess = tf.compat.v1.InteractiveSession()
    sess.run(tf.compat.v1.global_variables_initializer())
    date_ori = pd.to_datetime(df.iloc[:, 0]).tolist()

最后问题解决,代码最后成功运行

 

 

物联沃分享整理
物联沃-IOTWORD物联网 » 【最简单解决办法】:module ‘tensorflow.compat.v1‘ has no attribute ‘contrib‘

发表评论