sklearn中log_loss报错:不支持多输出目标数据的标签二值化
log_loss Hey there! Let's break down why this error is popping up and how to fix it.
The Core Issue
Sklearn's log_loss function has a default behavior that's tripping you up here: when your y_true is a 2D array, it automatically assumes you're working on a multi-output task (like predicting multiple independent labels for each sample) instead of a single multi-class classification task where each row represents the true probability distribution over classes.
Even though mathematically log_loss should handle true probability distributions, the default multi_class='auto' parameter checks the shape of y_true and misinterprets your input as multi-output data— which doesn't support the label binarization step the function tries to run in that case.
How to Fix It
You just need to explicitly tell the function that you're dealing with a multinomial (multi-class) classification task where each row in y_true is a probability distribution over classes. Here's how:
Option 1: Specify multi_class='multinomial' (Recommended)
This approach preserves the true probability distribution information in your y_true data, which aligns perfectly with what you're trying to do:
from sklearn import metrics import numpy as np y_true = np.array([[0.2,0.8,0],[0.9,0.05,0.05]]) y_predict = np.array([[0.5,0.5,0.0],[0.5,0.4,0.1]]) # Explicitly define the task type to use multinomial log loss metrics.log_loss(y_true, y_predict, multi_class='multinomial')
Option 2: Convert y_true to class indices (Not Ideal for Your Use Case)
If you didn't need to retain the true probability distributions, you could convert y_true to 1D indices of the most probable class. But this loses the nuance of your original true distribution, so it's not recommended here:
y_true_indices = np.argmax(y_true, axis=1) metrics.log_loss(y_true_indices, y_predict)
Why This Works
When you set multi_class='multinomial', the log_loss function switches to using the multinomial log loss formula, which is specifically designed to handle true class probability distributions as input— exactly what you're providing.
内容的提问来源于stack exchange,提问作者user1700890

