Python TensorFlow 报错'tensorflow.compat.v2.__internal__' has no attribute 'tf2'解决方法

本文主要介绍Python中,使用TensorFlow时,执行import Keras报错:AttributeError: module 'tensorflow.compat.v2.__internal__' has no attribute 'tf2'解决方法。

示例代码:

# 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

报错信息:

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'

解决方法:

!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

推荐阅读
cjavapy编程之路首页