TensorFlow 2.11.0导入segmentation_models库出现AttributeError求助
解决TensorFlow 2.11.0中导入segmentation_models的AttributeError问题
问题场景
在Google Colab环境使用TensorFlow 2.11.0时,执行Python库导入代码,在导入segmentation_models(别名sm)步骤触发AttributeError,提示'module 'keras.utils.generic_utils' has no attribute 'get_custom_objects'。
原代码
import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import numpy as np import pandas as pd import os from PIL import Image import matplotlib from sklearn.model_selection import train_test_split import tensorflow as tf import keras from keras.models import * from keras.layers import * from keras.callbacks import * from tensorflow.keras.optimizers import * from tqdm import tqdm import cv2 import segmentation_models as sm %load_ext tensorboard import datetime from keras.utils.vis_utils import plot_model
报错信息
AttributeError Traceback (most recent call last) <ipython-input-19-fb82ca23d179> in <module> 20 import cv2 21 import tensorflow as tf ---> 22 import segmentation_models as sm 23 model = tf.keras.applications.segmentation_model(model_name='mask_rcnn', weights='imagenet') 24 get_ipython().run_line_magic('load_ext', 'tensorboard') 3 frames /usr/local/lib/python3.8/dist-packages/efficientnet/__init__.py in init_keras_custom_objects() 69 } 70 ---> 71 tensorflow.python.keras.utils.generic_utils.get_custom_objects().update(custom_objects) 72 73 AttributeError: module 'keras.utils.generic_utils' has no attribute 'get_custom_objects'
问题原因
- API混用冲突:代码同时导入了独立的
keras库和tensorflow.keras,TensorFlow 2.x中Keras已整合到tf.keras,两套API共存会导致版本不兼容。 - 依赖库版本不适配:
segmentation_models依赖的efficientnet库调用了旧版Keras API,而TensorFlow 2.11.0中该API路径已变更。
解决方法
1. 统一使用tf.keras API
替换所有独立keras的导入语句,改用tensorflow.keras,避免两套API冲突。
2. 安装兼容版本的依赖库
在Colab中执行以下命令,卸载现有版本后安装适配TensorFlow 2.11.0的库:
!pip uninstall -y segmentation_models efficientnet !pip install segmentation_models==1.0.1 efficientnet==1.1.1
3. 指定segmentation_models的后端为tf.keras
在导入segmentation_models前,强制设置其使用tf.keras作为后端,确保调用正确的API路径。
修改后的完整代码
import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import numpy as np import pandas as pd import os from PIL import Image import matplotlib from sklearn.model_selection import train_test_split import tensorflow as tf # 统一使用tf.keras导入模块 from tensorflow.keras.models import * from tensorflow.keras.layers import * from tensorflow.keras.callbacks import * from tensorflow.keras.optimizers import * from tensorflow.keras.utils.vis_utils import plot_model from tqdm import tqdm import cv2 # 设置segmentation_models后端为tf.keras import segmentation_models as sm sm.set_framework('tf.keras') %load_ext tensorboard import datetime
内容的提问来源于stack exchange,提问作者ANIKET SHINDE
相关产品推荐
相关产品推荐

