UndefinedMetricWarning: F-Score Error
使用scikit-learn 的metrics.f1_score 計算用戶可能會遇到警告時,用戶可能會遇到警告時,用戶可能會遇到警告時,用戶可能會遇到警告:
「UndefinedMetricWarning:F 分數定義不明確,在沒有預測樣本的標籤中設定為0.0。」
了解警告
此當真實標籤(y_test) 中的某些標籤未出現在預測標籤(y_pred) 中時,會出現警告。在這種情況下,無法計算這些不可預測標籤的 F 分數,並假定為 0.0。
範例
考慮以下範例,其中標籤「2」預測中不存在:
y_test = [1, 10, 35, 9, 7, 29, 26, 3, 8, 23, 39, 11, 20, 2, 5, 23, 28, 30, 32, 18, 5, 34, 4, 25, 12, 24, 13, 21, 38, 19, 33, 33, 16, 20, 18, 27, 39, 20, 37, 17, 31, 29, 36, 7, 6, 24, 37, 22, 30, 0, 22, 11, 35, 30, 31, 14, 32, 21, 34, 38, 5, 11, 10, 6, 1, 14, 12, 36, 25, 8, 30, 3, 12, 7, 4, 10, 15, 12, 34, 25, 26, 29, 14, 37, 23, 12, 19, 19, 3, 2, 31, 30, 11, 2, 24, 19, 27, 22, 13, 6, 18, 20, 6, 34, 33, 2, 37, 17, 30, 24, 2, 36, 9, 36, 19, 33, 35, 0, 4, 1] y_pred = [1, 10, 35, 7, 7, 29, 26, 3, 8, 23, 39, 11, 20, 4, 5, 23, 28, 30, 32, 18, 5, 39, 4, 25, 0, 24, 13, 21, 38, 19, 33, 33, 16, 20, 18, 27, 39, 20, 37, 17, 31, 29, 36, 7, 6, 24, 37, 22, 30, 0, 22, 11, 35, 30, 31, 14, 32, 21, 34, 38, 5, 11, 10, 6, 1, 14, 30, 36, 25, 8, 30, 3, 12, 7, 4, 10, 15, 12, 4, 22, 26, 29, 14, 37, 23, 12, 19, 19, 3, 25, 31, 30, 11, 25, 24, 19, 27, 22, 13, 6, 18, 20, 6, 39, 33, 9, 37, 17, 30, 24, 9, 36, 39, 36, 19, 33, 35, 0, 4, 1] print(metrics.f1_score(y_test, y_pred, average='weighted'))
此程式碼將產生警告。
為什麼只有有時?
警告僅在第一個出現計算 F 分數的時間是因為大多數 Python 環境僅顯示一次特定警告。但是,可以使用 warnings.filterwarnings('always') 來變更此行為。
如何避免警告
要避免看到警告,您可以設定warnings.filterwarnings('ignore') 在匯入scikit-learn 之前或在計算F-score時明確指定您感興趣的標籤,如下:
# Ignore warnings warnings.filterwarnings('ignore') metrics.f1_score(y_test, y_pred, average='weighted') # Explicitly specify labels unique_labels = np.unique(y_pred) metrics.f1_score(y_test, y_pred, average='weighted', labels=unique_labels)
以上是為什麼 Scikit-learn 的 F1-Score 會產生「UndefinedMetricWarning」?的詳細內容。更多資訊請關注PHP中文網其他相關文章!