【问题标题】:module 'tensorflow.compat.v1' has no attribute 'contrib'模块“tensorflow.compat.v1”没有属性“contrib”
【发布时间】:2021-04-24 15:04:23
【问题描述】:

由于 tensorflow 2 不支持“占位符”功能,我必须按以下方式导入 tensorflow:

import tensorflow.compat.v1 as tf

tf.disable_v2_behavior() 

进一步的代码片段在下面的 co 中使用了 'contrib' 函数

def encoding_layer(rnn_size, sequence_length, num_layers, rnn_inputs, keep_prob):
    '''Create the encoding layer'''
    
    for layer in range(num_layers):
        with tf.variable_scope('encoder_{}'.format(layer)):
            cell_fw = tf.contrib.rnn.LSTMCell(rnn_size,
                                              initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
            cell_fw = tf.contrib.rnn.DropoutWrapper(cell_fw, 
                                                    input_keep_prob = keep_prob)

            cell_bw = tf.contrib.rnn.LSTMCell(rnn_size,
                                              initializer=tf.random_uniform_initializer(-0.1, 0.1, seed=2))
            cell_bw = tf.contrib.rnn.DropoutWrapper(cell_bw, 
                                                    input_keep_prob = keep_prob)

            enc_output, enc_state = tf.nn.bidirectional_dynamic_rnn(cell_fw, 
                                                                    cell_bw, 
                                                                    rnn_inputs,
                                                                    sequence_length,
                                                                    dtype=tf.float32)
    # Join outputs since we are using a bidirectional RNN
    enc_output = tf.concat(enc_output,2)
    
    return enc_output, enc_state

最后的代码块是:

# Build the graph
train_graph = tf.Graph()
# Set the graph to default to ensure that it is ready for training
with train_graph.as_default():
    
    # Load the model inputs    
    input_data, targets, lr, keep_prob, summary_length, max_summary_length, text_length = model_inputs()

    # Create the training and inference logits
    training_logits, inference_logits = seq2seq_model(tf.reverse(input_data, [-1]),
                                                      targets, 
                                                      keep_prob,   
                                                      text_length,
                                                      summary_length,
                                                      max_summary_length,
                                                      len(vocab_to_int)+1,
                                                      rnn_size, 
                                                      num_layers, 
                                                      vocab_to_int,
                                                      batch_size)
    
    # Create tensors for the training logits and inference logits
    training_logits = tf.identity(training_logits.rnn_output, 'logits')
    inference_logits = tf.identity(inference_logits.sample_id, name='predictions')
    
    # Create the weights for sequence_loss
    masks = tf.sequence_mask(summary_length, max_summary_length, dtype=tf.float32, name='masks')

    with tf.name_scope("optimization"):
        # Loss function
        cost = tf.contrib.seq2seq.sequence_loss(
            training_logits,
            targets,
            masks)

        # Optimizer
        optimizer = tf.train.AdamOptimizer(learning_rate)

        # Gradient Clipping
        gradients = optimizer.compute_gradients(cost)
        capped_gradients = [(tf.clip_by_value(grad, -5., 5.), var) for grad, var in gradients if grad is not None]
        train_op = optimizer.apply_gradients(capped_gradients)
print("Graph is built.")

我收到以下错误:

AttributeError: module 'tensorflow.compat.v1' has no attribute 'contrib'

我遇到了一些建议我安装 tensorflow 1.14 的答案,但是,这也给出了以下错误:

❯ pip install tensorflow==1.14
ERROR: Could not find a version that satisfies the requirement tensorflow==1.14 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.2.1, 2.2.2, 2.3.0rc0, 2.3.0rc1, 2.3.0rc2, 2.3.0, 2.3.1, 2.3.2, 2.4.0rc0, 2.4.0rc1, 2.4.0rc2, 2.4.0rc3, 2.4.0rc4, 2.4.0, 2.4.1, 2.5.0rc0, 2.5.0rc1)
ERROR: No matching distribution found for tensorflow==1.14

请帮忙。

TIA。

[更新]

我尝试通过conda安装tensorflow 1.14,出现如下错误:

❯ conda install tensorflow==1.14
Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: -
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
Examining @/win-64::__cuda==11.1=0:  67%|████████████████████████████████                | 2/3 [00:00<00:00, 13.28it/s]/                                                                                                                       -failed

UnsatisfiableError: The following specifications were found
to be incompatible with the existing python installation in your environment:

Specifications:

  - tensorflow==1.14 -> python[version='3.6.*|3.7.*']
  - tensorflow==1.14 -> python[version='>=3.6,<3.7.0a0|>=3.7,<3.8.0a0']

Your python: python=3.8

If python is on the left-most side of the chain, that's the version you've asked for.
When python appears to the right, that indicates that the thing on the left is somehow
not available for the python version you are constrained to. Note that conda will not
change your python version to a different minor version unless you explicitly specify
that.

The following specifications were found to be incompatible with your CUDA driver:

  - feature:/win-64::__cuda==11.1=0
  - feature:|@/win-64::__cuda==11.1=0

Your installed CUDA driver is: 11.1

【问题讨论】:

  • @JiteshMalipeddi 这显然不是 pip 的问题。但是,我按照你说的做了,并没有解决问题。
  • 这很奇怪。我的 pip 版本是 21.0.1pip install tensorflow==1.14 工作正常,没有任何问题
  • @JiteshMalipeddi 我的点数是 21.1
  • 您使用的是 Python 3.8,但tensorflow==1.14 仅支持最高 3.7 的 Python。如果您需要使用tensorflow==1.14migrate the legacy code to 2.0,请安装 3.7。

标签: python tensorflow pip


【解决方案1】:

如果您想使用 tf.contrib 库,请使用 Tensorflow ==1.14.0 或 1.15.0 它还需要 Python ==3.6/3.7。

【讨论】:

    【解决方案2】:

    Tf.contrib 在 Tensorflow >= 2.0 中被移除。 一些tf.contrib函数可以通过使用来使用

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

    为了使用 tf.contrib 库,请使用 Tensorflow ==1.14 或 1.15。

    正如@hoefling 所说,Tensorflow 1.14 需要 Python ==3.6/3.7。

    【讨论】:

    • 明白。但是,您的评论并没有解决问题。无论如何,谢谢你。
    • 评论只是对@PragyadityaDas 在第一步中尝试的重复。
    猜你喜欢
    • 2021-02-17
    • 2019-09-16
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多