我一直在研究多類分類問題,我需要制作一個函式來顯示某類時尚 MNIST 資料集的影像并對其進行預測。例如,繪制T-shirt該類的3 個影像及其預測。我嘗試了不同的東西,但還沒有成功。我缺少一個條件陳述句,我無法弄清楚在我的函式中如何以及在何處實作它。
這是我到目前為止想出的:
# Make function to plot image
def plot_image(indx, predictions, true_labels, target_images):
"""
Picks an image, plots it and labels it with a predicted and truth label.
Args:
indx: index number to find the image and its true label.
predictions: model predictions on test data (each array is a predicted probability of values between 0 to 1).
true_labels: array of ground truth labels for images.
target_images: images from the test data (in tensor form).
Returns:
A plot of an image from `target_images` with a predicted class label
as well as the truth class label from `true_labels`.
"""
# Set target image
target_image = target_images[indx]
# Truth label
true_label = true_labels[indx]
# Predicted label
predicted_label = np.argmax(predictions) # find the index of max value
# Show image
plt.imshow(target_image, cmap=plt.cm.binary)
plt.xticks([])
plt.yticks([])
# Set colors for right or wrong predictions
if predicted_label == true_label:
color = 'green'
else:
color = 'red'
# Labels appear on the x-axis along with accuracy %
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions),
class_names[true_label]),
color=color)
# Function to display image of a class
def display_image(class_indx):
# Set figure size
plt.figure(figsize=(10,10))
# Set class index
class_indx = class_indx
# Display 3 images
for i in range(3):
plt.subplot(1, 3, i 1)
# plot_image function
plot_image(indx=class_indx, predictions=y_probs[class_indx],
true_labels=test_labels, target_images=test_images_norm)
這些是類名'T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'。當我呼叫顯示函式display_image()并將類索引作為引數傳遞時display_image(class_indx=15),我得到了 3 次相同的影像和相同的預測(注意我的錯誤方法,我傳遞的是索引號而不是類名)。我需要一個函式,它采用str(類名)并顯示該類的 3 個不同預測。舉例來說,display_image('Dress')應該回傳的3個影像Dress類及其3點不同的預測,我的模型取得了一起Prediction#1 (65%),Prediction#2 (100%),Prediction#3 (87%)像現在這樣。謝謝!
uj5u.com熱心網友回復:
我認為你真的很接近解決你的問題。您只需要從您感興趣的類別中抽取三個樣本。我猜你已經使用 ale = LabelEncoder()來編碼你的目標向量。如果是的話,那么你將有類是這樣的:labels = list(le.classes_)。然后我會做以下事情:
def display_image(class_of_interest: str, nb_samples: int=3):
plt.figure(figsize=(10,10))
class_indx = class_names.index(class_of_interest)
target_idx = np.where(true_labels==class_indx)[0]
imgs_idx = np.random.choice(target_idx, nb_samples, replace=False)
for i in range(nb_samples):
plt.subplot(1, nb_samples, i 1)
plot_image(indx=imgs_idx[i],
predictions=y_probs[imgs_idx[i]],
true_labels=test_labels,
target_images=test_images_norm)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/311555.html
標籤:Python matplotlib 机器学习 张量流数据集 张量流2.x
