Compute a K×K confusion matrix where rows are true labels and columns are predictions. Support multiple normalization modes for different analysis perspectives.
A confusion matrix is a fundamental tool for evaluating classification performance. It provides detailed insights into which classes are being confused with each other, enabling targeted model improvements.
Confusion Matrix Definition:
Cij=n=1∑N1[ytrue(n)=i and ypred(n)=j]Normalization Modes:
'none': Raw counts
'true': Row-wise → ∑jCij=1
'pred': Column-wise → ∑iCij=1
'all': Total → ∑ijCij=1
y_true: array-like, shape (N,) - True class labels, integers in [0, K-1]y_pred: array-like, shape (N,) - Predicted class labels, integers in [0, K-1]num_classes: optional int - Number of classes K; if None, infer from max(labels)+1normalize: str - Normalization mode: 'none', 'true', 'pred', or 'all'Input: y_true=[0,1,1], y_pred=[0,1,0], normalize='none'
Output: [[1,0],[1,1]]
Input: y_true=[0,1,1], y_pred=[0,1,0], normalize='true'
Output: [[1.0,0.0],[0.5,0.5]]
Use np.bincount() with indices computed as y_true * K + y_pred.
For normalization, use keepdims=True in np.sum() to maintain dimensions.
Handle division by zero by setting zero denominators to 1 before division.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: any
Accepts: string
Compute a K×K confusion matrix where rows are true labels and columns are predictions. Support multiple normalization modes for different analysis perspectives.
A confusion matrix is a fundamental tool for evaluating classification performance. It provides detailed insights into which classes are being confused with each other, enabling targeted model improvements.
Confusion Matrix Definition:
Cij=n=1∑N1[ytrue(n)=i and ypred(n)=j]Normalization Modes:
'none': Raw counts
'true': Row-wise → ∑jCij=1
'pred': Column-wise → ∑iCij=1
'all': Total → ∑ijCij=1
y_true: array-like, shape (N,) - True class labels, integers in [0, K-1]y_pred: array-like, shape (N,) - Predicted class labels, integers in [0, K-1]num_classes: optional int - Number of classes K; if None, infer from max(labels)+1normalize: str - Normalization mode: 'none', 'true', 'pred', or 'all'Input: y_true=[0,1,1], y_pred=[0,1,0], normalize='none'
Output: [[1,0],[1,1]]
Input: y_true=[0,1,1], y_pred=[0,1,0], normalize='true'
Output: [[1.0,0.0],[0.5,0.5]]
Use np.bincount() with indices computed as y_true * K + y_pred.
For normalization, use keepdims=True in np.sum() to maintain dimensions.
Handle division by zero by setting zero denominators to 1 before division.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: any
Accepts: string