昨天我可以使用TensorFlow作为后端,但今天在尝试导入Keras时显示了一些错误信息,以下是我的代码:
# 安装所需的库 # 注意:运行此代码后,请重新启动运行时,然后再运行下面的所有代码...(非常重要!!!) ### 请将Albumentations更新到版本>=0.3.0,以支持`Lambda`变换!pip install -U segmentation-models!pip install q tensorflow==2.1!pip install q keras==2.3.1!pip install tensorflow-estimator==2.1.## 导入库import osos.environ['CUDA_VISIBLE_DEVICES'] = '0'import cv2import Kerasimport NumPy as npimport matplotlib.pyplot as plt
它显示了以下错误:
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 plt8 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 # 兼容别名(在V1和V2中都需要存在)。AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'
虽然我使用的是TensorFlow 2.2版本和Keras 2.3.1版本,昨天还能运行,但今天似乎不行了。我今天导入的Keras和TensorFlow版本是否有问题?
编辑:当我使用from tensorFlow import keras
时,我想要的输出using tensorflow backend
并没有显示出来,然后当我加载import segmentation_models as sm
时,它显示了与使用import Keras
时相同的错误,如上所述。
回答:
这是解决您问题的方案,我已经在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.## 导入库import osos.environ['CUDA_VISIBLE_DEVICES'] = '0'os.environ["SM_FRAMEWORK"] = "tf.keras"from tensorflow import kerasimport segmentation_models as sm
|████████████████████████████████| 51kB 3.3MB/s |████████████████████████████████| 421.8MB 42kB/s |████████████████████████████████| 450kB 35.7MB/s |████████████████████████████████| 3.9MB 33.6MB/s Building wheel for gast (setup.py) ... doneERROR: 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.
更新
您不需要安装任何特定的tensorflow / keras
版本。任何2.x
以上的版本都可以运行,例如tf 2.4/ 2.5/ 2.6
。然而,在Colab中,您需要重启内核才能看到效果。但如果您在Kaggle内核上运行,则不需要重启内核。请看下面:
在Colab中:
# 单元格: 1import os !pip install -U -q segmentation-models --useros.kill(os.getpid(), 9)
它会自动重启内核。重启后,在新的单元格中运行以下代码。
#单元格: 2import os os.environ["SM_FRAMEWORK"] = "tf.keras"import segmentation_models as sm
在Kaggle内核中:
import os !pip install -U -q segmentation-models --useros.environ["SM_FRAMEWORK"] = "tf.keras"import segmentation_models as sm