Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Thực hiện dự đoán Fashion MNIST với TensorFlow


TensorFlow (Google) framework học máy mã nguồn mở, tối ưu bằng NumPy và tensor.

Cài đặt: pip install tensorflow

Tensor: mảng đa chiều trong đồ thị luồng dữ liệu.

Fashion MNIST: >70.000 ảnh grayscale trang phục 10 loại, 28x28 pixel.

Chạy trên Google Colab (Python trên trình duyệt, GPU miễn phí).

Ví dụ

probability_model = tf.keras.Sequential([
    model,
    tf.keras.layers.Softmax()
])
predictions = probability_model.predict(test_images)
print("Đang dự đoán...")
print(predictions[0])
np.argmax(predictions[0])
print("Nhãn test:")
print(test_labels[0])

def plot_image(i, predictions_array, true_label, img):
    true_label, img = true_label[i], img[i]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])
    plt.imshow(img, cmap=plt.cm.binary)
    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)

def plot_value_array(i, predictions_array, true_label):
    true_label = true_label[i]
    plt.grid(False)
    plt.xticks(range(10))
    plt.yticks([])
    thisplot = plt.bar(range(10), predictions_array, color="#777777")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)
    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('green')

Nguồn mã: TensorFlow Classification Tutorial

Đầu ra

Đang dự đoán...
[1.3008227e-07 9.4930819e-10 2.0181861e-09 5.4944155e-10 3.8257373e-11 1.3896286e-04 1.4776078e-08 3.1724274e-03 9.4210514e-11 9.9668854e-01]
Nhãn test: 9

Giải thích

  • Sau train, cần test mô hình bằng dự đoán ảnh.
  • Gắn lớp Softmax sau mô hình để chuyển logits → xác suất.
  • Softmax giúp diễn giải dự đoán dễ dàng hơn.
  • Định nghĩa plot_image hiển thị ảnh + nhãn dự đoán/thật (xanh/đỏ).
  • Định nghĩa plot_value_array vẽ biểu đồ cột xác suất 10 classes.