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

无法从torchmetrics.functional导入f1的问题求助

解决Cannot import name 'f1' from 'torchmetrics.functional'的问题

问题原因

你遇到的报错主要来自两个点:

  • torchmetrics版本过旧,f1函数未被放在torchmetrics.functional根路径下
  • 函数名使用错误,torchmetrics中通用的F1指标函数名为f1_score,而非f1(f1函数归类在分类任务子模块中)

解决方案

  1. 升级torchmetrics到最新版本
    执行以下命令更新模块:

    pip install --upgrade torchmetrics
    
  2. 使用正确的导入语句
    根据你的使用场景选择:

    • 通用场景(直接计算F1分数):
      from torchmetrics.functional import f1_score
      
    • 分类任务场景(支持多分类、多标签等更灵活的参数设置):
      from torchmetrics.functional.classification import f1
      

使用示例

以分类任务为例,调用f1函数的代码示例:

from torchmetrics.functional.classification import f1
import torch

# 模拟预测结果和真实标签
preds = torch.tensor([0, 1, 2, 0, 1, 2])
target = torch.tensor([0, 2, 1, 0, 0, 1])

# 计算多分类的macro F1
result = f1(preds, target, num_classes=3, average='macro')
print(result)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:40:41