Error: No module named ‘tensorflow.contrib‘

在跑下游任务时候偶然遇到了这个问题,完整的错误代码如下:

Traceback (most recent call last):
  File "run_mrc.py", line 12, in 
    from tools import official_tokenization as tokenization, utils
  File "/data/XXX/pycharm/CLUE/baselines/models_pytorch/mrc_pytorch/tools/utils.py", line 7, in 
    import tensorflow.contrib.slim as slim
ModuleNotFoundError: No module named 'tensorflow.contrib'
Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.
Better speed can be achieved with apex installed from https://www.github.com/nvidia/apex.
Traceback (most recent call last):
  File "test_mrc.py", line 14, in 
    from tools import utils
  File "/data/XXX/pycharm/CLUE/baselines/models_pytorch/mrc_pytorch/tools/utils.py", line 7, in 
    import tensorflow.contrib.slim as slim
ModuleNotFoundError: No module named 'tensorflow.contrib'

网上一搜都是降级的,降到1.4... 估计是新的Tensorflow 已经把这个模块删除了。

我不想降级,没多大意思。 找找有没有什么替代方法能够不降级解决这个问题。

第一反应是用这个: 

import tensorflow.compat.v1 as tf

也就是降级成1版本,但是这里不太适用。所以还是直接去官网查查吧。

通过官网查询,找到了如何替换成新版本的解决方案

https://www.tensorflow.org/guide/migrate/migrate_tf2

Remove usage of tf.contrib

The tf.contrib module has been sunsetted and several of its submodules have been integrated into the core TF2 API. The other submodules are now spun-off into other projects like TF IO and TF Addons.

A large amount of older TF1.x code uses the Slim library, which was packaged with TF1.x as tf.contrib.layers. When migrating your Slim code to TF2, switch your Slim API usages to point to the tf-slim pip package. Then, read the model mapping guide to learn how to convert Slim code.

Alternatively, if you use Slim pre-trained models you may consider trying out Keras's pre-traimed models from tf.keras.applications or TF Hub's TF2 SavedModels exported from the original Slim code.

简单点说用pip下一个tf-slim,然后替换掉tensorflow.contrib.slim 就行了。

pip install tf-slim

         Installing collected packages: tf-slim
        Successfully installed tf-slim-1.1.0

然后替换源代码:

# import tensorflow.contrib.slim as slim
import tf_slim as slim

问题解决

你可能感兴趣的:(TensorFlow,tensorflow,机器学习)