predict和predict_proba概率之间存在很大差异



我正在尝试训练社交网络帖子识别模型,但遇到了一件奇怪的事情。我收到了用户帖子的文本,模型预测了一个类,但最高的概率对应于另一个类。下面我举了一个最简单的例子,但我在其他模型中也发现了同样的情况。可能是我对predict_proba方法有些不理解。

型号:

texts = np.array(get_train_texts()[0])
labels = np.array(get_train_texts()[1])
X_train, X_test, y_train, y_test = train_test_split(texts, labels, 
test_size=0.25, random_state=True)
gbc_model = Pipeline([
('tf_idf', TfidfVectorizer()),
('gbc', GradientBoostingClassifier(n_estimators=128,
max_depth=16,
criterion='friedman_mse'))])
gbc_model.fit(X_train, y_train)  
text_to_recognize = [get_post(id, offset, access_token)]    
label = gbc_model.predict(text_to_recognize)                
grades = gbc_model.predict_proba(text_to_recognize)        
grades = [f'{classes[i]}: {round(grades[0][i] * 100, 4)} %' for i in range(len(classes))]

输出:

...
['science'] 
['science: 3.6298 %', 'cinema: 1.0597 %', 'IT: 1.5812 %', 'art: 2.1504 %', 'games: 91.5788 %']

所以,如果我从成绩中选择了argmax,我会得到不正确的类"游戏";而不是";科学";,对应良好:

grades = gbc_model.predict_proba(text_to_recognize) 
result = classes[np.argmax(grades)]
print(result)

输出:

['science'] 
['science: 3.6298 %', 'cinema: 1.0597 %', 'IT: 1.5812 %', 'art: 2.1504 %', 'games: 91.5788 %']
games

为什么会发生这种情况?

gbc模型使用与您使用的类顺序不同的类顺序。您选择了classes[i],但不能保证GradientBoostingClassifier使用的类的索引是相同的。

事实上,分类器按字母顺序对类进行排序,使science成为最后一个类中的最后一个,也是示例中概率最高的一个。这就是为什么应该使用内部gbc_model.classes_属性或LabelEncoder

换句话说,分类器一切都很好。

相关内容

最新更新