使用confusion_matrix函数遇too many values to unpack错误求助
confusion_matrix Hey there! Let's figure out why you're hitting this error and how to fix it. First off, the (71,) shape you're seeing is a 1-dimensional array/list—this is totally normal for confusion_matrix inputs, so the "empty dimension" isn't the issue here. Let's break down the most likely causes and solutions:
1. You're trying to unpack a multi-class confusion matrix into 4 variables
The most common reason for this error is assuming confusion_matrix will always return a 2x2 matrix (which only happens for binary classification) and trying to unpack it into tn, fp, fn, tp. If your labels have more than 2 classes, the result will be an n x n matrix, and trying to split that into 4 values will throw "too many values to unpack".
Fix:
First, check what your confusion matrix actually looks like before unpacking:
from sklearn.metrics import confusion_matrix # Get the full confusion matrix cm = confusion_matrix(y_true, y_predict) print("Confusion matrix shape:", cm.shape) print("Confusion matrix:\n", cm)
If the shape is (n, n) where n > 2, you can't unpack it into 4 variables. Instead, access elements directly (e.g., cm[0][1] for the count of class 0 predicted as class 1) or use cm.ravel() to get a flat array if you need all values in order.
If you're doing binary classification and still getting a larger matrix, explicitly specify your labels to ensure a 2x2 output:
# For binary classification, define your class labels explicitly cm = confusion_matrix(y_true, y_predict, labels=[0, 1]) # Use ravel() to flatten the 2x2 matrix into a 1D array before unpacking tn, fp, fn, tp = cm.ravel()
2. Double-check your input data format
Even though you said y_true and y_predict are lists with shape (71,), make sure they aren't accidentally nested (e.g., [[1, 0, 1, ...]] instead of [1, 0, 1, ...]). A nested list would have a shape like (1, 71), which might cause unexpected behavior.
Verify with this quick check:
import numpy as np print("y_true shape:", np.array(y_true).shape) print("y_predict shape:", np.array(y_predict).shape)
Both should output (71,). If not, flatten them with np.array(y_true).flatten().tolist() to get a 1D list.
3. Ensure label types match
Make sure the elements in y_true and y_predict are the same data type (e.g., both integers or both strings). Mismatched types can sometimes cause odd behavior, though this usually throws a different error—it's worth checking just in case.
内容的提问来源于stack exchange,提问作者Simplicity

