Google Colab导入segmentation_models报AttributeError问题求助
Colab导入segmentation_models报错:AttributeError: module 'keras.utils.generic_utils' has no attribute 'get_custom_objects'
问题描述
在Google Colab中使用segmentation_models库,最初一周使用正常,但近期执行import segmentation_models as sm时触发以下错误:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-3-6f48ce46383f> in <module> 1 import tensorflow as tf ----> 2 import segmentation_models as sm 3 frames /usr/local/lib/python3.8/dist-packages/efficientnet/__init__.py in init_keras_custom_objects() 69 } 70 ---> 71 keras.utils.generic_utils.get_custom_objects().update(custom_objects) 72 73 AttributeError: module 'keras.utils.generic_utils' has no attribute 'get_custom_objects'
当前Colab使用TensorFlow 2.11.0版本,未找到该特定错误的相关解决方案。
解决方案
1. 根本原因
TensorFlow 2.11.0对Keras的API结构进行了调整,get_custom_objects()方法从keras.utils.generic_utils迁移到了tf.keras.utils,而segmentation_models依赖的旧版efficientnet库仍在调用旧路径,导致兼容性报错。
2. 具体修复步骤
升级/重装兼容的efficientnet版本
执行以下命令安装适配TF2.11的efficientnet版本:!pip install --upgrade efficientnet若升级后仍有问题,可指定安装特定兼容版本:
!pip install efficientnet==1.1.1调整导入顺序
先显式导入TensorFlow的Keras模块,再导入segmentation_models,让Python优先使用TF内置的Keras路径:import tensorflow as tf from tensorflow import keras import segmentation_models as sm降级TensorFlow到兼容版本
若上述方法无效,可将TensorFlow降级到2.10.0及以下版本(该版本仍保留旧版Keras API路径):!pip install tensorflow==2.10.0
内容的提问来源于stack exchange,提问作者Droidux
相关产品推荐
相关产品推荐

