1 回答

TA貢獻1784條經驗 獲得超7個贊
讓我們從火車代碼開始(內聯文檔)
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
# load data
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
# Text representation of labels
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Normalize the train and test images
train_images = train_images / 255.0
test_images = test_images / 255.0
# Define the model
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# train the model
model.fit(train_images, train_labels, epochs=10)
正如你所看到的,最后一層是Dense輸出大小的層10。那是因為我們有10個班級。為了確定它屬于哪個類別,我們只需從這 10 個類別中取出最大值并將其類別指定為預測即可。但如果我們可以將這些值更改為概率,我們還可以知道模型做出此預測的信心有多大。因此,讓我們附加 softmax 層,將這 10 個輸出歸一化為概率。
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print (f"Input: {test_images.shape}, Output: {predictions.shape}")
輸出:
Input: (10000, 28, 28), Output: (10000, 10)
讓我們打印第 i 個測試圖像的預測標簽和真實標簽
i = 0
print (f"Actual Label: {train_labels[i]}, Predicted Label: {np.argmax(predictions[i])}")
輸出:
Actual Label: 9, Predicted Label: 9
最后讓我們繪制第 i 個圖像并用預測的類別及其概率對其進行標記。(內聯文檔)
def plot_image(i, predictions_array, true_label, img):
"""
i: render ith image
predictions_array: Probabilities of each class predicted by the model for the ith image
true_label: All the the acutal label
img: All the images
"""
# Get the true label of ith image and the ithe image itself
true_label, img = true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
# Render the ith image
plt.imshow(img, cmap=plt.cm.binary)
# Get the class with the higest probability for the ith image
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
最后讓我們調用它
plot_image(i, predictions[i], test_labels, test_images)
你的困惑是因為predictions_array
參數。請注意,這是模型對第 i 個測試數據所做的預測。它有 10 個值,每個值代表它屬于相應類別的概率。
添加回答
舉報