Colab fallback runtime下tensorflow estimator_export导入错误求助
问题背景
一两年前基于教程开发的音频分类模型,因TensorFlow和tflite_model_maker版本迭代,现有代码无法正常运行。尝试在Google Colab中使用fallback runtime环境以保留原代码输出,执行!pip install tflite_model_maker安装成功,但执行导入代码:
import tensorflow as tf import tflite_model_maker as mm
时触发如下错误:
ImportError Traceback (most recent call last) <ipython-input-20-09befa6c6d6d> in <cell line: 2>() 1 import tensorflow as tf ----> 2 import tflite_model_maker as mm 3 from tflite_model_maker import audio_classifier 4 import os 5 17 frames /usr/local/lib/python3.9/dist-packages/tensorflow_estimator/python/estimator/canned/dnn.py in <module> 24 from tensorflow.python.feature_column import feature_column_lib 25 from tensorflow.python.framework import ops ---> 26 from tensorflow.python.util.tf_export import estimator_export 27 from tensorflow_estimator.python.estimator import estimator 28 from tensorflow_estimator.python.estimator.canned import head as head_lib ImportError: cannot import name 'estimator_export' from 'tensorflow.python.util.tf_export' (/usr/local/lib/python3.9/dist-packages/tensorflow/python/util/tf_export.py)
原因
fallback runtime默认的TensorFlow版本,与你安装的最新版tflite_model_maker存在依赖冲突:estimator_export模块在新版TensorFlow中已被迁移至tensorflow_estimator内部,但旧版(或当前安装的)tflite_model_maker仍依赖原导入路径,导致导入失败。
可行解决方法
1. 安装指定兼容版本组合(推荐)
直接安装与原开发环境匹配的TensorFlow、tflite_model_maker和tensorflow-estimator版本,彻底解决兼容问题:
# 卸载现有冲突版本 !pip uninstall -y tensorflow tflite_model_maker tensorflow-estimator # 安装兼容版本(示例为经过验证的稳定组合,可根据原教程版本调整) !pip install tensorflow==2.8.0 tflite_model_maker==0.4.1 tensorflow-estimator==2.8.0
若不确定原版本,可尝试
tflite_model_maker0.3.x-0.4.x搭配TensorFlow 2.7.x-2.8.x的组合,这类版本仍保留estimator_export的原导入路径。
2. 临时修改库文件导入路径
若需临时适配新版环境,可手动修改报错文件的导入逻辑:
- 在Colab中打开报错文件:
/usr/local/lib/python3.9/dist-packages/tensorflow_estimator/python/estimator/canned/dnn.py - 将第26行的导入语句替换为:
from tensorflow_estimator.python.util.tf_export import estimator_export
注意:此方法每次重启runtime后都需重新修改,仅适合临时应急。
3. 切换至Colab旧版Runtime镜像
在Colab中点击Runtime > Change runtime type,在Runtime version下拉菜单中选择TensorFlow 2.x的早期稳定版本(如TensorFlow 2.8),再重新安装对应版本的tflite_model_maker。
内容的提问来源于stack exchange,提问作者LCM

