导入tflite-model-maker报No module named 'official.nlp.bert'如何解决
TFLite Model Maker导入报错:
official.nlp.bert模块不存在 问题场景
跟随TensorFlow TFLite基础文本分类教程操作时,执行导入语句抛出异常。
报错的导入代码:
from tensorflow_examples.lite.model_maker.core.data_util import image_dataloader
核心错误信息:
ModuleNotFoundError: No module named 'official.nlp.bert'
已执行的安装操作:
- 执行
pip install tensorflow安装TensorFlow - 执行
pip install -q tflite-model-maker安装TFLite Model Maker - 执行
pip install tf-models-official安装TensorFlow官方模型库
完整错误追踪信息:
Traceback (most recent call last): File "...\Downloads\tf_setup.py", line 6, in <module> from tflite_model_maker import model_spec File "...\AppData\Local\Programs\Python\Python310\lib\site-packages\tflite_model_maker\__init__.py", line 16, in <module> from tensorflow_examples.lite.model_maker.core.data_util import image_dataloader File "...\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow_examples\lite\model_maker\__init__.py", line 17, in <module> from tensorflow_examples.lite.model_maker.core.data_util import text_dataloader File "...\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow_examples\lite\model_maker\core\data_util\text_dataloader.py", line 31, in <module> from tensorflow_examples.lite.model_maker.core.task import model_spec as ms File "...\AppData\Local\Programs\Python\Python310\lib\site-packages\tensorflow_examples\lite\model_maker\core\task\model_spec.py", line 37, in <module> from official.nlp.bert import configs as bert_configs ModuleNotFoundError: No module named 'official.nlp.bert'
错误原因
和BERT模型本身是否安装无关,核心问题是依赖版本不匹配:
高版本tf-models-official已经重构了NLP模块的目录结构,原有的official.nlp.bert路径被移除,相关代码被迁移到了其他目录下。而当前稳定版的tflite-model-maker还在使用旧路径做导入,哪怕装了最新版官方模型库,也找不到对应路径下的文件。
修复步骤
按顺序执行以下操作即可解决:
- 先卸载所有存在版本冲突的相关包,避免残留文件影响:
pip uninstall -y tflite-model-maker tf-models-official tensorflow
- 安装经过兼容验证的固定版本依赖组合,不要单独安装最新版包:
pip install tensorflow==2.15.0 tf-models-official==2.15.0 tflite-model-maker==0.4.2
- 安装完成后重新运行代码,导入错误会消失。
注意:不要安装2.15.0以上版本的
tf-models-official,高版本已经彻底删除旧的bert目录,不存在official.nlp.bert.configs这个导入路径,和现有稳定版tflite-model-maker完全不兼容。
如果执行完上述操作仍报错,先检查本地Python环境是否存在多版本冲突,确认执行pip命令的环境和运行脚本的环境是同一个,可以分别执行pip --version和python --version核对路径是否匹配。
内容的提问来源于stack exchange,提问作者Salvatore
相关产品推荐
相关产品推荐

