模块“tensorflow.compat.v2.__internal__”没有属性“tf2”

uzr*_*rsa 7 python machine-learning deep-learning keras tensorflow

我昨天尝试使用 TensorFlow 作为后端我可以使用它,但是今天当我尝试导入 Keras 时使用它显示一些错误消息,所以这是我的代码:

# Install required libs  
# NOTE: Run this one code, then restart this runtime and run again for next all... (PENTING!!!) 
 
### please update Albumentations to version>=0.3.0 for `Lambda` transform support
!pip install -U segmentation-models

!pip install q tensorflow==2.1
!pip install q keras==2.3.1
!pip install tensorflow-estimator==2.1.

## Imports libs
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'


import cv2
import Keras
import NumPy as np
import matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

它显示此错误:

AttributeError                            Traceback (most recent call last)

<ipython-input-3-9c78a7be919d> in <module>()
      5 
      6 import cv2
----> 7 import keras
      8 import numpy as np
      9 import matplotlib.pyplot as plt

8 frames

/usr/local/lib/python3.7/dist-packages/keras/initializers/__init__.py in populate_deserializable_objects()
     47 
     48   LOCAL.ALL_OBJECTS = {}
---> 49   LOCAL.GENERATED_WITH_V2 = tf.__internal__.tf2.enabled()
     50 
     51   # Compatibility aliases (need to exist in both V1 and V2).

AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'
Run Code Online (Sandbox Code Playgroud)

因此我使用的是 TensorFlow 2.2 版和 Keras 2.3.1 版,昨天我可以运行,但今天似乎不能。我今天的 Keras 和 TensorFlow 版本导入错误了吗?

编辑:当我使用from tensorFlow import keras我想要的输出时using tensorflow backend没有显示,然后当我加载import segmentation_models as sm它时,当我import Keras像上面那样使用时显示相同的错误。

M.I*_*nat 7

这是您问题的解决方案,我已经在 colab 上对其进行了测试。

!pip install -U -q segmentation-models
!pip install -q tensorflow==2.1
!pip install -q keras==2.3.1
!pip install -q tensorflow-estimator==2.1.

## Imports libs
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
os.environ["SM_FRAMEWORK"] = "tf.keras"

from tensorflow import keras
import segmentation_models as sm
Run Code Online (Sandbox Code Playgroud)
|????????????????????????????????| 51kB 3.3MB/s 
|????????????????????????????????| 421.8MB 42kB/s 
|????????????????????????????????| 450kB 35.7MB/s 
|????????????????????????????????| 3.9MB 33.6MB/s 
Building wheel for gast (setup.py) ... done
ERROR: tensorflow-probability 0.12.1 has requirement gast>=0.3.2, 
but you'll have gast 0.2.2 which is incompatible.
|????????????????????????????????| 378kB 2.1MB/s 
Segmentation Models: using `tf.keras` framework.
Run Code Online (Sandbox Code Playgroud)

  • 在“tf 2.x”之后,独立的“keras”不再维护,它成为“tf”的一部分。因此,之前我们使用“import keras”,现在(在“tf .2.x”之后,我们应该使用“from ten.. import keras”。当您使用“tf 2.”时,您应该以这种方式导入。 (2认同)