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

Ubuntu22.04下用Flair做情感分析遇Torch循环导入AttributeError

问题

在Ubuntu 22.04系统上使用Python Flair运行文件情感分析代码时,触发Torch相关的AttributeError,错误信息如下:
AttributeError: partially initialized module 'torch' has no attribute 'autograd' (most likely due to a circular import)

完整回溯信息:

Traceback (most recent call last):
  File "/home/ayush/myproj/vaahan/scrape/sentimentF.py", line 9, in <module>
    from flair.models import TextClassifier
  File "/home/ayush/.local/lib/python3.10/site-packages/flair/__init__.py", line 2, in <module>
    import torch
  File "/home/ayush/.local/lib/python3.10/site-packages/torch/__init__.py", line 759, in <module>
    from .serialization import save, load
  File "/home/ayush/.local/lib/python3.10/site-packages/torch/serialization.py", line 21, in <module>
    from transformers.models.bert.modeling_bert import BertModel,BertForMaskedLM
  File "/home/ayush/.local/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py", line 26, in <module>
    import torch.utils.checkpoint
  File "/home/ayush/.local/lib/python3.10/site-packages/torch/utils/checkpoint.py", line 55, in <module>
    class CheckpointFunction(torch.autograd.Function):
AttributeError: partially initialized module 'torch' has no attribute 'autograd' (most likely due to a circular import)

使用的代码:

from flair.models import TextClassifier
from flair.data import Sentence
sia = TextClassifier.load('en-sentiment')

def getSentiment3():
    with open("/home/ayush/myproj/vaahan/scrape/scrapeListFile.txt","r") as f:
        content = f.read()  
        flair_analysis = Sentence(content)
        sia.predict(flair_analysis)
        score = flair_analysis.labels[0]

        return score

print(getSentiment3())
解决方法
  • 检查命名冲突:确认你的脚本文件名不是torch.py、transformers.py或flair.py——这类名字会覆盖官方库文件,导致导入时出现循环依赖。如果有,立即重命名脚本。
  • 重装损坏的依赖:卸载现有Torch、Transformers和Flair,重新安装兼容版本:
    pip uninstall -y torch transformers flair
    pip install torch==2.0.1 transformers==4.30.2 flair==0.12.2
    
  • 使用虚拟环境隔离依赖:避免全局环境依赖混乱,创建并激活独立虚拟环境后再安装依赖:
    python3 -m venv flair_env
    source flair_env/bin/activate
    pip install torch transformers flair
    
  • 清理缓存文件:删除项目目录下的__pycache__文件夹,避免缓存的旧代码干扰导入流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:45:34