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

二分类情感分类器阈值问题:仅预测正类无负类请求排查

问题分析与解决

核心问题:阈值判断逻辑完全错误

你当前代码里用min(example_probs) < neg_threshold判定负类的逻辑完全搞反了。predict_proba返回的是每个类别的概率值(比如二分类下是[负类概率, 正类概率]),min(example_probs)取的是两个概率里更小的那个,这个值小于0.4时,实际代表模型更倾向于另一个类(正类),这时候你判成负类,会把真正的负类样本都误判成中性过滤掉,最后剩下的样本全是正类,自然预测结果只有正类。

修正步骤

  1. 先明确模型的类别对应关系
    先打印模型的类别顺序,确认概率列对应的情感:

    print(linear.classes_)
    

    比如输出array([0, 1]),说明第一列是0类(负)的概率,第二列是1类(正)的概率。

  2. 替换错误的阈值判断逻辑
    把循环部分改成直接对应类别的概率判断,不要用max/min,同时降低过高的正类阈值:

    sentiments = []
    # 假设classes_顺序是[0=负, 1=正]
    pos_threshold = 0.6
    neg_threshold = 0.6
    for example_probs in L_probs:
        neg_prob, pos_prob = example_probs
        if pos_prob >= pos_threshold:
            sentiment = "positive"
        elif neg_prob >= neg_threshold:
            sentiment = "negative"
        else:
            sentiment = "neutral"
        sentiments.append(sentiment)
    
  3. 验证过滤后的样本分布
    在过滤后打印样本的真实情感分布,确认是否包含负类:

    print("过滤后真实情感分布:", np.bincount(filtered_sentiments))
    

    如果输出里负类数量为0,说明阈值还是不合理,继续调整neg_threshold(比如降到0.5),直到保留足够的负类样本。

  4. 检查模型本身的性能
    如果调整阈值后过滤的样本里有负类,但预测结果还是全正,那说明你的linear模型本身对负类的识别能力极差,需要重新训练模型(比如调整特征、补充负类样本、优化模型参数)。

修正后的完整代码片段

L_probs = linear.predict_proba(tweet_vectors_t1)

# 确认类别顺序
print("模型类别顺序:", linear.classes_)

# 调整阈值并修正判断逻辑
pos_threshold = 0.6
neg_threshold = 0.6

sentiments = []
for example_probs in L_probs:
    neg_prob, pos_prob = example_probs
    if pos_prob >= pos_threshold:
        sentiment = "positive"
    elif neg_prob >= neg_threshold:
        sentiment = "negative"
    else:
        sentiment = "neutral"
    sentiments.append(sentiment)

filtered_tweet_vectors_t1 = [tweet_vectors_t1[i]
                             for i, sentiment in enumerate(sentiments)
                             if sentiment != "neutral"]
filtered_sentiments = [tweet_sentiment_t1[i]
                       for i, sentiment in enumerate(sentiments)
                       if sentiment != "neutral"]
filtered_sentiments = np.array(filtered_sentiments).astype(int)

# 验证过滤后的样本分布
print("过滤后真实情感分布:", np.bincount(filtered_sentiments))

filtered = linear.predict(filtered_tweet_vectors_t1)

accuracy = accuracy_score(filtered_sentiments, filtered)
precision = precision_score(filtered_sentiments, filtered)
recall = recall_score(filtered_sentiments, filtered)
f1 = f1_score(filtered_sentiments, filtered, average='macro')

print('Accuracy:', accuracy)
print('Precision:', precision)
print('Recall:', recall)
print('F1-score:', f1)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(filtered_sentiments, filtered)
print(cm)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:43:11