簡體   English   中英

Tensorflow 圖像處理函數

[英]Tensorflow Image Processing Function

伙計們,我從 Tensorflow.org 制作了基本圖像分類教程。 但我無法理解 def image_process 的代碼。 因為教程里沒有解釋。

這是代碼:

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)

我的問題:

函數如何確定predictions_array 是預測值,真實標簽是正確的標簽。 我們不應該說 true_label = train_label[i] 或 predictions_array = prediction[i]

當我們沒有像我展示的那樣在我們的函數中設置對象時,函數如何確定對象。

讓我們從火車代碼開始(內嵌文檔)

# 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)

如您所見,最后一層是輸出大小為10Dense層。 那是因為我們有 10 個班級。 為了確定它屬於哪個類,我們可以從這 10 個中取出最大值並將其分配為它的預測。 但是,如果我們可以將這些值更改為概率,我們還可以判斷模型在進行此預測時的信心程度。 因此,讓我們附加將這 10 個輸出歸一化為概率的 softmax 層。

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 個值,每個值代表它屬於相應類別的概率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM