如何构建混淆矩阵?KNN交叉验证代码混淆矩阵报错求解
Let's break down your issues and fix them step by step:
1. Why You're Getting the "Too Many Values to Unpack" Error
The root problem here is a misunderstanding of what confusion_matrix.ravel() returns. Since you have 9 target classes, your confusion matrix is a 9x9 grid (81 total elements). When you call .ravel(), it flattens this grid into a 1D array of 81 values—but you're trying to unpack all 81 into just 9 variables. That's why you see ValueError: too many values to unpack (expected 9).
2. Correct Way to Build and Use the Confusion Matrix
First, let's ensure you compute the confusion matrix correctly, with explicit class labels to avoid ordering issues. Then, we'll handle the results properly:
Step 1: Compute the Confusion Matrix
Define your class labels explicitly to guarantee the matrix uses the order you expect:
from sklearn.metrics import confusion_matrix import numpy as np # List your 9 classes in the order you want them displayed class_labels = [11, 12, 13, 21, 22, 23, 31, 32, 33] # Compute the confusion matrix with specified labels cm = confusion_matrix(y_test, preds, labels=class_labels)
Step 2: Extract Useful Metrics (Instead of Unpacking)
If you want to get metrics like true positives for each class, use the diagonal of the matrix:
# True positives for each class (diagonal elements) true_positives = np.diag(cm) print("True Positives per Class:") for cls, tp in zip(class_labels, true_positives): print(f"Class {cls}: {tp}")
If you need the full flattened matrix, assign it to a single variable:
flattened_cm = cm.ravel() # Access individual elements via index, e.g., flattened_cm[0] for the first element
Step 3: Print a Readable Confusion Matrix
For better readability, print the matrix with class labels:
print("\nConfusion Matrix:") print("Row = True Class, Column = Predicted Class") print(f"Labels: {class_labels}") print(cm)
3. Bonus: Visualize the Confusion Matrix
For a clearer view of your model's performance across all 9 classes, use a heatmap:
import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(10, 8)) sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_labels, yticklabels=class_labels) plt.xlabel('Predicted Class') plt.ylabel('True Class') plt.title('Confusion Matrix for 9-Class KNN Model') plt.show()
4. Full Fixed Code Snippet
Here's how the relevant part of your code should look after fixes:
# ... (your existing code up to preds = clf.best_estimator_.predict(X_test)) from sklearn.metrics import confusion_matrix import numpy as np class_labels = [11, 12, 13, 21, 22, 23, 31, 32, 33] cm = confusion_matrix(y_test, preds, labels=class_labels) # Get true positives per class true_positives = np.diag(cm) print("True Positives:", dict(zip(class_labels, true_positives))) # Print full confusion matrix print("\nConfusion Matrix:") print(cm)
Content of the question来源于stack exchange,提问作者Codrin Mironiuc

