使用Transformers做情感分析时出现type_spec_registry导入错误求助
问题描述
尝试使用Transformers库的pipeline函数执行情感分析任务时触发运行时错误,根源是无法从tensorflow.python.framework导入type_spec_registry,进而导致transformers.models.distilbert.modeling_tf_distilbert模块导入失败。
复现代码
from transformers import pipeline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, f1_score, confusion_matrix # Basic usage classifier = pipeline('sentiment-analysis')
完整报错堆栈
ImportError Traceback (most recent call last) File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\transformers\utils\import_utils.py:1099, in _LazyModule._get_module(self, module_name) 1098 try: -> 1099 return importlib.import_module("." + module_name, self.__name__) 1100 except Exception as e: File ~\anaconda3\envs\Asiwajuflow\lib\importlib\__init__.py:127, in import_module(name, package) 126 level += 1 -> 127 return _bootstrap._gcd_import(name[level:], package, level) ...(中间堆栈内容省略) File ~\anaconda3\envs\Asiwajuflow\lib\site-packages\keras\src\saving\legacy\saved_model\json_utils.py:38 37 # isort: off -> 38 from tensorflow.python.framework import type_spec_registry 40 _EXTENSION_TYPE_SPEC = "_EXTENSION_TYPE_SPEC" ImportError: cannot import name 'type_spec_registry' from 'tensorflow.python.framework' (C:\Users\hp\anaconda3\envs\Asiwajuflow\lib\site-packages\tensorflow\python\framework\__init__.py) The above exception was the direct cause of the following exception: RuntimeError Traceback (most recent call last) Cell In[9], line 2 1 #Basic usage ----> 2 classifier = pipeline('sentiment-analysis') ...(中间堆栈内容省略) RuntimeError: Failed to import transformers.models.distilbert.modeling_tf_distilbert because of the following error (look up to see its traceback): cannot import name 'type_spec_registry' from 'tensorflow.python.framework' (C:\Users\hp\anaconda3\envs\Asiwajuflow\lib\site-packages\tensorflow\python\framework\__init__.py)
解决方案
升级TensorFlow到兼容版本
type_spec_registry是TensorFlow 2.10+引入的API,旧版本不存在。执行以下命令升级:# 查看当前TensorFlow版本 pip show tensorflow # 升级到稳定兼容版(如2.15.x系列) pip install --upgrade tensorflow同步Transformers库版本
确保Transformers与TensorFlow版本匹配,执行升级:pip install --upgrade transformers强制使用PyTorch后端(无需TensorFlow时)
创建pipeline时指定framework='pt',跳过TensorFlow相关模块加载:classifier = pipeline('sentiment-analysis', framework='pt')修复依赖冲突
如果单独安装了Keras,可能与TensorFlow自带的Keras冲突,执行以下操作:# 卸载独立安装的Keras pip uninstall -y keras # 重新安装TensorFlow确保依赖完整 pip install tensorflow --force-reinstall
内容的提问来源于stack exchange,提问作者Abdusalam Idris
相关产品推荐
相关产品推荐

