You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

transformers与TensorFlow导入报错:如何解决register_load_context_function缺失问题

解决ProsusAI/finbert情感分析Flask接口的transformers与TensorFlow导入错误

错误信息

RuntimeError: Failed to import transformers.models.bert.modeling_tf_bert because of the following error (look up to see its traceback):
module 'tensorflow._api.v2.compat.v2.__internal__' has no attribute 'register_load_context_function'

问题场景

运行调用ProsusAI/finbert进行情感分析的Flask接口代码时触发上述错误,涉及代码片段:

sentiment_analysis = pipeline("sentiment-analysis", model="ProsusAI/finbert")
@app.route('/news', methods=['POST'])
def analyze_news_sentiment():
    data = request.json
    news_text = data.get('news_text')

    # Perform sentiment analysis
    result = sentiment_analysis(news_text)

    return jsonify(sentiment=result[0]['label'])

解决方案

方案1:指定PyTorch后端(推荐)

finbert同时支持PyTorch和TensorFlow后端,直接在pipeline初始化时指定使用PyTorch,避免加载TensorFlow相关模块,绕开版本冲突:

sentiment_analysis = pipeline("sentiment-analysis", model="ProsusAI/finbert", framework="pt")

方案2:对齐transformers与TensorFlow版本

若必须使用TensorFlow后端,需确保两者版本兼容:

  • 卸载现有冲突版本:
    pip uninstall -y transformers tensorflow
    
  • 安装经过验证的兼容版本组合:
    pip install transformers==4.30.2 tensorflow==2.13.0
    

方案3:使用独立虚拟环境

创建并激活项目专属虚拟环境,避免全局环境中不同版本的Python包互相干扰,再重新安装所需依赖。

内容的提问来源于stack exchange,提问作者Ritesh Kedar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 01:41:06