如何在 Python 中使用 TensorFlow 對 Fashion MNIST 資料集進行預測?


Tensorflow 是 Google 提供的一個機器學習框架。它是一個開源框架,與 Python 結合使用以實現演算法、深度學習應用程式等等。它用於研究和生產目的。它具有最佳化技術,有助於快速執行復雜的數學運算。這是因為它使用了 NumPy 和多維陣列。這些多維陣列也稱為“張量”。

可以使用以下程式碼行在 Windows 上安裝“tensorflow”包:

pip install tensorflow

張量是 TensorFlow 中使用的資料結構。它有助於連線流圖中的邊。此流圖稱為“資料流圖”。張量不過就是多維陣列或列表。

“Fashion MNIST”資料集包含各種服裝的影像。它包含超過 70,000 件屬於 10 個不同類別的服裝的灰度影像。這些影像的解析度較低(28 x 28 畫素)。

我們正在使用 Google Colaboratory 來執行以下程式碼。Google Colab 或 Colaboratory 有助於透過瀏覽器執行 Python 程式碼,並且無需任何配置,並且可以免費訪問 GPU(圖形處理單元)。Colaboratory 是建立在 Jupyter Notebook 之上的。

以下是進行預測的程式碼片段:

示例

probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print("The predictions are being made ")
print(predictions[0])

np.argmax(predictions[0])
print("The test labels are")
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’)

程式碼來源https://www.tensorflow.org/tutorials/keras/classification

輸出

The predictions are being made
[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]
The test labels are
9

解釋

  • 模型訓練完成後,需要對其進行測試。

  • 這可以透過使用構建的模型對影像進行預測來完成。

  • 線性輸出、logits 和 softmax 層附加到它。

  • softmax 層有助於將 logits 轉換為機率。

  • 這樣做是為了更容易解釋所做的預測。

  • 定義了“plot_value_array”方法,該方法顯示實際值和預測值。

更新於: 2021年1月20日

111 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.