計算logloss函數sklearn.metrics._classification.log_loss
方法簽名:
def log_loss(y_true, y_pred, eps=1e-15, normalize=True, sample_weight=None,
labels=None):
參數 y_true,也就是測試集的標簽列數據,
參數 y_pred, 是模型對測試集的預測分數。
如果模型的預測分數(model.predict_proba) 結果為:
[[0.1, 0.3, 0.6],
[0.1, 0.6, 0.3]]
對應的測試集的標簽為:
['dog', 'cat']
來計算logloss:
from sklearn import metrics
y_score = [[0.1, 0.3, 0.6],
[0.1, 0.6, 0.3]]
y_test = ['dog', 'cat']
metrics.log_loss(y_true=y_test, y_pred=y_score)
執行后報錯:
ValueError: y_true and y_pred contain different number of classes 2, 3. Please provide the true labels explicitly through the labels argument. Classes found in y_true: ['cat' 'dog']
y_score
中的概率傳給logloss函數,它並不知道每個概率對應的label是什么,例如不知道第一組概率 [0.1, 0.3, 0.6] 是對應 標簽 ['dog', 'cat', 'children']還是[ 'cat', 'dog', 'children'],僅知道概率,不知道是哪個概率無法得知模型的預測結果,進而也就無法評估。
其方法中有一個參數labels
可以用來指定概率對應的標簽:
metrics.log_loss(y_true=y_test, y_pred=y_score, labels=['dog', 'cat', 'children'])
如果根據模型中的標簽列的信息(model.classes_),來排列y_test,使之與y_score對應,也可以進行計算:
from sklearn.preprocessing import label_binarize
# label_binarize 先對y_test按照classes的順序轉換成數字, 比如'dog'在classes中的位置是0,轉換為0,然后初始化長度為3的數組,第0個位置置為1,得到[1,0,0], 其概率也是按照classes輸出的,這樣就能對應了
y_test_onehot = label_binarize(y_test, classes=['dog', 'cat', 'children']) # 多分類模型大多都有classes_屬性
metrics.log_loss(y_test_onehot, y_score)
y_test_onehot
輸出:
array([[1, 0, 0],
[0, 1, 0]])