hinge_loss#
- sklearn.metrics.hinge_loss(y_true, pred_decision, *, labels=None, sample_weight=None)[原始碼]#
平均合頁損失 (非正規化)。
在二元分類的情形下,假設 y_true 中的標籤以 +1 和 -1 編碼,當預測錯誤時,
margin = y_true * pred_decision
始終為負值(因為符號不一致),意味著1 - margin
始終大於 1。因此,累積的 hinge 損失是分類器所犯錯誤數量的上限。在多類別分類的情形下,該函數預期 y_true 中包含所有標籤,或者提供一個可選的 labels 參數,其中包含所有標籤。多標籤的 margin 是根據 Crammer-Singer 的方法計算的。與二元分類的情形一樣,累積的 hinge 損失是分類器所犯錯誤數量的上限。
請在使用者指南中閱讀更多資訊。
- 參數:
- y_true形狀為 (n_samples,) 的類陣列
真實目標,由兩個值的整數組成。正標籤必須大於負標籤。
- pred_decision形狀為 (n_samples,) 或 (n_samples, n_classes) 的類陣列
預測的決策,由 decision_function 輸出(浮點數)。
- labels類陣列,預設為 None
包含問題的所有標籤。用於多類別 hinge 損失。
- sample_weight形狀為 (n_samples,) 的類陣列,預設為 None
樣本權重。
- 回傳:
- loss浮點數
平均 hinge 損失。
參考文獻
[2]Koby Crammer, Yoram Singer. On the Algorithmic Implementation of Multiclass Kernel-based Vector Machines. Journal of Machine Learning Research 2, (2001), 265-292.
範例
>>> from sklearn import svm >>> from sklearn.metrics import hinge_loss >>> X = [[0], [1]] >>> y = [-1, 1] >>> est = svm.LinearSVC(random_state=0) >>> est.fit(X, y) LinearSVC(random_state=0) >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) >>> pred_decision array([-2.18..., 2.36..., 0.09...]) >>> hinge_loss([-1, 1, 1], pred_decision) np.float64(0.30...)
在多類別分類的情形下
>>> import numpy as np >>> X = np.array([[0], [1], [2], [3]]) >>> Y = np.array([0, 1, 2, 3]) >>> labels = np.array([0, 1, 2, 3]) >>> est = svm.LinearSVC() >>> est.fit(X, Y) LinearSVC() >>> pred_decision = est.decision_function([[-1], [2], [3]]) >>> y_true = [0, 2, 3] >>> hinge_loss(y_true, pred_decision, labels=labels) np.float64(0.56...)