多分类结果映射0/1及CIFAR数据集预测标签类别判定
Hey there! Let's break down your questions step by step since you're working on CIFAR image classification with those 10-class probability outputs. I'll cover both identifying the predicted class and converting the probabilities to a 0-1 one-hot mapping.
Your output is an array where each element represents the model's predicted probability for one of the 10 CIFAR classes (indexed 0 to 9). To find which class the model is most confident in, you just need to find the index of the maximum value in the array.
Example with NumPy
Since you're working with NumPy arrays (as shown in your example), here's how to do it:
import numpy as np # Your sample prediction probability array pred_probs = np.array([3.3655483e-04, 9.4402254e-01, 1.1646092e-03, 2.8560971e-04, 1.4086446e-04, 7.1564602e-05, 2.4985364e-03, 6.5030693e-04, 3.4783698e-05, 5.0794542e-02], dtype=np.float32) # Get the index of the highest probability (this is your predicted class) pred_class_idx = np.argmax(pred_probs) print(f"Predicted class index: {pred_class_idx}") # Optional: Map the index to CIFAR-10's human-readable class names cifar10_classes = ["airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"] print(f"Predicted class name: {cifar10_classes[pred_class_idx]}")
This will output Predicted class index: 1 and Predicted class name: automobile for your sample array, since the 2nd element (index 1) has the highest probability (~94.4%).
The method you mentioned is exactly right: set the position of the maximum probability to 1, and all others to 0. Here's how to implement this cleanly:
Using NumPy
# Initialize a zero array with the same shape as your prediction probabilities one_hot = np.zeros_like(pred_probs) # Set the index of the highest probability to 1 one_hot[pred_class_idx] = 1 print("0-1 mapping result:") print(one_hot)
For your sample input, this will output:
array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)
Bonus: Using PyTorch (if you're using a PyTorch model)
If you're working with PyTorch tensors instead of NumPy arrays, the process is similar:
import torch # Convert your NumPy array to a PyTorch tensor pred_probs_tensor = torch.tensor(pred_probs) # Get the predicted class index pred_class_idx_tensor = torch.argmax(pred_probs_tensor) # Create the one-hot tensor one_hot_tensor = torch.zeros(10) one_hot_tensor[pred_class_idx_tensor] = 1 # Convert back to NumPy if needed print(one_hot_tensor.numpy())
内容的提问来源于stack exchange,提问作者amaresh hiremani

