对于 scikit-learn 中的大多数模型,我们可以通过predict_proba 获得类的概率估计。请记住,这是逻辑函数的实际输出,通过选择概率最高的输出获得结果分类,即在输出上应用argmax。如果我们看到实现here,你可以看到它本质上是在做:
def predict(self, X):
# decision func on input array
scores = self.decision_function(X)
# column indices of max values per row
indices = scores.argmax(axis=1)
# index class array using indices
return self.classes_[indices]
如果调用predict_proba 而不是predict,则返回scores。这是一个训练LogisticRegression的示例用例:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y)
lr= LogisticRegression()
lr.fit(X_train, y_train)
y_pred_prob = lr.predict_proba(X_test)
y_pred_prob
array([[1.06906558e-02, 9.02308167e-01, 8.70011771e-02],
[2.57953117e-06, 7.88832490e-03, 9.92109096e-01],
[2.66690975e-05, 6.73454730e-02, 9.32627858e-01],
[9.88612145e-01, 1.13878133e-02, 4.12714660e-08],
...
如上所述,我们可以通过采用argmax 来获得概率,并将类数组索引为:
classes = load_iris().target_names
classes[indices]
array(['virginica', 'virginica', 'versicolor', 'virginica', 'setosa',
'versicolor', 'versicolor', 'setosa', 'virginica', 'setosa',...
因此,对于单个预测,通过预测的概率,我们可以轻松地执行以下操作:
y_pred_prob = lr.predict_proba(X_test[0,None])
ix = y_pred_prob.argmax(1).item()
print(f'predicted class = {classes[ix]} and confidence = {y_pred_prob[0,ix]:.2%}')
# predicted class = virginica and confidence = 90.75%