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

Python多分类模型合并类别后按概率阈值计算TP和FP的实现方法

多分类场景下按transport概率和计算TP/FP的代码修改方案

核心逻辑调整说明

  • 入参新增:每个样本的car类概率p_car_list、bike类概率p_bike_list,以及待测试的阈值列表thresholds
  • 真实正例判定:若样本的真实标签为1(car)或3(bike),则属于transport类(真实正例),其余为真实负例
  • 预测正例判定:对每个阈值,判断p_car + p_bike > threshold,满足则判定为预测正例
  • 遍历所有阈值,分别统计每个阈值对应的TP、FP值

修改后代码

def calculate_transport_metrics(yTrue, p_car_list, p_bike_list, thresholds):
    # 初始化返回结果,结构为{阈值: (TP, FP)}
    metrics = {}
    for threshold in thresholds:
        TP, FP = 0, 0
        for i in range(len(yTrue)):
            # 判断当前样本是不是真实的transport类
            is_true_transport = yTrue[i] in (1, 3)
            # 计算当前样本的transport总概率
            transport_prob = p_car_list[i] + p_bike_list[i]
            # 判断是不是预测为transport类
            is_pred_transport = transport_prob > threshold
            
            if is_true_transport and is_pred_transport:
                TP += 1
            elif not is_true_transport and is_pred_transport:
                FP += 1
        metrics[threshold] = (TP, FP)
    return metrics

使用示例

比如你要测试90%、80%、70%三个阈值,调用方式如下:

# 示例输入数据
yTrue = [1,2,3,4,5,1,3]
p_car_list = [0.92, 0.01, 0.05, 0.03, 0.02, 0.88, 0.08]
p_bike_list = [0.05, 0.02, 0.9, 0.01, 0.04, 0.07, 0.86]
thresholds = [0.9, 0.8, 0.7]

# 调用函数得到各阈值的TP、FP
result = calculate_transport_metrics(yTrue, p_car_list, p_bike_list, thresholds)
for thres, (tp, fp) in result.items():
    print(f"阈值{thres*100:.0f}%: TP={tp}, FP={fp}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:36:02