06_基本的圖像分類案例、導入圖片數據、探索數據的格式、數據預處理、構建模型(設置層、編譯模型)、訓練模型(Fit模型、評估精確度)、得出預測結果(驗證預測結果)、使用訓練過的模型

1.3.1.基本圖像分類

翻譯自:https://tensorflow.google.cn/tutorials/keras/classification

該指南訓練一個神經網絡模型來對服裝圖像進行分類,像腳底運動鞋和襯衫。如果你不理解所有的細節也沒有關係。這個是一個完成的TesorFlow程序的快速的概述。
指南中使用 tf.keras,這是一個高階API,用於在TensorFlow中構建和訓練模型。

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

輸出結果:

2.2.0

1.3.1.1.導入Fashion MNIST數據集

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

載入數據集返回4個NumPy數組
train_images和train_labels數組是訓練集。這個數據是這個模型學習用的。
模型測試基於測試集,即test_images和test_labels數組。

這些圖片是28x28的NumPy數組,像素值從0到255。labels數據集是一個整型的數組,從0到9。這些對應於圖像所代表的服裝類別:

Label Class
0 T-shirt/top
1 Trouser
2 Pullover
3 Dress
4 Coat
5 Sandal
6 Shirt
7 Sneaker
8 Bag
9 Ankle boot

每個圖像被映射到單個標籤。因爲這個類名不包含在數據集中,將它們存儲在這裏,以便稍後繪製圖像時使用。

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

1.3.1.2.探索數據

在訓練模型之前,讓我們研究一下數據集的格式。下面顯示訓練集中有60000張圖像,每張圖像用28 x 28像素表示。

train_images.shape

輸出結果:

(60000, 28, 28)

同樣,訓練接中有60000個標記值(目標值):

print(len(train_labels))
60000

每個標記值是0和9之間的整型值

print(train_labels)

輸出結果是:

[9 0 0 ... 3 0 5]

在測試集中有10000張圖片。同樣,每幅圖像用28 x 28像素表示:

print(test_images.shape)

輸出結果:

(10000, 28, 28)

這個測試集包含10000個圖片目標值:

print(len(test_labels))

輸出結果:

10000

1.3.1.3.數據預處理

在訓練網絡之前,必須對數據進行預處理。 如果你檢查訓練集中的第一個圖像,您將看到像素值在0到255的範圍內:

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

在這裏插入圖片描述
在將這些值輸入到神經網絡模型之前,將它們縮放到0到1的範圍內,要做到這一點,需要將這些值除以255。重要的是,訓練集和測試集的預處理方式相同:

train_images = train_images / 255.0
test_images = test_images / 255.0

以驗證數據的格式是否正確,並且您已經準備好構建和訓練網絡,讓我們從訓練集中展示開始的25張圖片和在它下面展示每個分類的名稱。

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

顯示結果:
在這裏插入圖片描述

1.3.1.4.構建模型

構建神經網絡需要配置模型的層,然後編譯模型。

1.3.1.4.1.設置層

神經網絡的基本組成部分是層。層從輸入給它們的數據中提取特徵。這些特徵對於手頭上的問題是很有意義的。
大多數深度學習都是由一些層連接在一起的。大多數層,例如tf.keras.layers.Dense,擁有在學習訓練中的參數。

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28,28)),
    keras.layers.Dense(128,activation='relu'),
    keras.layers.Dense(10)
])

在這個網絡中第一層中, tf.keras.layers.Flatten,將圖像格式從二維數組(28×28像素)轉換爲一維數組(28 * 28 = 784像素)。可以將這一層看作是將圖像中的像素行展開並排列起來。這一層沒有深度學習所需的參數。它只是重新格式化數據。

在像素值被flattened之後,這個網絡由兩個tf.keras.layers.Dense層的序列組成。它們是緊密相連或完全相連的神經層。這個第一個Dense層有128個節點(或者說神經元),第二個(也是最後一個)層返回長度爲10的logits數組。每個節點包含一個分數,這個值表示當前圖片屬於這個10個分類中的一個的分值。

1.3.1.4.2.編譯模型

在模型準備好訓練之前,它需要一些更多的設置。在模型訓練過程中這些參數被添加進去:
損失函數(Loss function)—這可以衡量模型在訓練期間的準確性,您想最小化這個函數,以便將模型“引導”到正確的方向
優化器(Optimizer)— 這就是模型如何根據它看到的數據和它的損失函數進行更新.
Metrics—用於監控訓練和測試步驟。下面的例子使用accuracy,即圖片被正確分類的分數。

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

1.3.1.5.訓練模型

訓練神經網絡模型需要以下步驟:
1、將訓練數據輸入模型。在這個例子中,訓練數據在train_images和train_labels數組中。
2、模型學習去關聯圖像和標籤labels(目標值)
3、您要求模型對測試集進行預測。—在這個例子中,這裏測試集即test_images數組。
4、驗證預測是否與test_labels數組中的標籤匹配。

1.3.1.5.1.Fit模型

調用model.fit方法開始訓練模型。之所以這麼說,是因爲它使模型與訓練數據“吻合”。

model.fit(train_images,train_labels,epochs=10)

輸出結果:

Epoch 1/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.4957 - accuracy: 0.8262
Epoch 2/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3758 - accuracy: 0.8652
Epoch 3/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3373 - accuracy: 0.8766
Epoch 4/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.3112 - accuracy: 0.8859
Epoch 5/10
1875/1875 [==============================] - 3s 1ms/step - loss: 0.2968 - accuracy: 0.8896
Epoch 6/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2820 - accuracy: 0.8956
Epoch 7/10
1875/1875 [==============================] - 3s 1ms/step - loss: 0.2700 - accuracy: 0.9002
Epoch 8/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2577 - accuracy: 0.9030
Epoch 9/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2497 - accuracy: 0.9060
Epoch 10/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.2385 - accuracy: 0.9106

作爲模型訓練,損失值和精確值被顯示出來了。該模型對訓練數據的準確率約爲0.91 (91%)。

1.3.1.5.2.評估精確度

接下來,比較模型在測試數據集上的表現:

test_loss,test_acc = model.evaluate(test_images,test_labels,verbose=2)
print('\nTest accuracy:',test_acc)

輸出結果:

313/313 - 0s - loss: 0.3528 - accuracy: 0.8791
Test accuracy: 0.8791000247001648

結果是測試數據集上的準確性比訓練數據集上的準確性稍低,訓練準確度和測試準確度之間的差距代表過擬合。當機器學習模型在新的、以前沒有看到的輸入上的表現不如在訓練數據上的表現時,就會發生過擬合。過度擬合的模型“記憶”了訓練數據集中的噪音和細節,從而對模型在新數據上的性能產生負面影響。欲瞭解更多信息,請參閱以下內容:
Demonstrate overfitting

Strategies to prevent overfitting

1.3.1.6.得出預測結果

通過訓練模型,您可以使用它來對一些圖像進行預測。模型的線性輸出,logits。附加一個softmax層轉換logits爲概率,這個是一個更容易理解的數據。

probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)

這裏,模型已經對測試集中的每一張圖像的標籤進行了預測,讓我們看一下第一個預測:

print(predictions[0])

輸出結果爲:

[1.9066751e-10 2.8168485e-12 2.6482936e-13 1.2655502e-12 3.0858400e-09
 1.4370863e-04 8.8831733e-09 6.9896835e-03 6.6860224e-09 9.9286664e-01]

預測是一個包含10個數字的數組,它們代表了模型的“confidence”,即圖像對應着10種不同的服裝(即是10種分類中每個分類的概率)。你可以看到哪個標籤的置信度最高。

np.argmax(predictions[0])   #即最大可能的分類(目標值)

輸出結果爲:

9

所以,模特最自信的認爲這是一雙腳踝靴(Ankle boot)

繪製圖表,看看10個類預測的全部集合。

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array, 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):
  predictions_array, true_label = predictions_array, 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('blue')
1.3.1.6.1.驗證預測結果

通過訓練模型,您可以使用它來對一些圖像進行預測。

讓我們看看第0個圖像、預測和預測數組, 正確的預測標籤爲藍色,錯誤的預測標籤爲紅色。該數字給出了預測標籤的百分比(滿分100)

i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

在這裏插入圖片描述
再如,預測錯了的案例:

i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

在這裏插入圖片描述
讓我們用他們的預測畫幾個圖像。注意,即使非常自信,模型也可能出錯。

# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

在這裏插入圖片描述

1.3.1.7.使用訓練過的模型

最後,利用訓練好的模型對單幅圖像進行預測。

# Grab an image from the test dataset.
img = test_images[1]

print(img.shape)

輸出結果爲:

(28, 28)

tf.keras模型經過優化,可以立即對一批或一批示例進行預測,因此,即使你使用一個單一的圖像,你需要添加到一個列表:

# Add the image to a batch where it's the only member
img = (np.expand_dims(img,0))
print(img.shape)

輸出結果:

(1, 28, 28)

接着預測這個圖片的正確結果:

predictions_single = probability_model.predict(img)
print(predictions_single)

輸出結果:

[[1.1291439e-04 1.2360411e-12 9.9952698e-01 1.9153010e-09 2.9750227e-04
  2.1691890e-14 6.2605846e-05 1.1370566e-18 8.4102066e-11 1.2200014e-16]]
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)

keras.Model.predict 返回列表的列表,這個列表是每個圖像在批數據中的一個列表。抓取批處理中我們的(唯一的)圖像的預測:

np.argmax(predictions_single[0])

輸出結果是:

2

所有代碼如下:

# -*- coding: UTF-8 -*-

# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

print(train_images.shape)
print(train_labels)
print(len(train_labels))

print(test_images.shape)
print(len(test_labels))

print(train_images[0])

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

train_images = train_images / 255.0
test_images = test_images / 255.0

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

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'])

model.fit(train_images,train_labels,epochs=10)

test_loss,test_acc = model.evaluate(test_images,test_labels,verbose=2)
print('\nTest accuracy:',test_acc)

probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print(predictions[0])

print(np.argmax(predictions[0]))

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array, 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):
  predictions_array, true_label = predictions_array, 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('blue')

i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()



# Plot the first X test images, their predicted labels, and the true labels.
# Color correct predictions in blue and incorrect predictions in red.
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()


# Grab an image from the test dataset.
img = test_images[1]

print(img.shape)


# Add the image to a batch where it's the only member
img = (np.expand_dims(img,0))
print(img.shape)

predictions_single = probability_model.predict(img)
print(predictions_single)

plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)


print(np.argmax(predictions_single[0]))

官網還沒出來中文版,自己翻譯和整理,打個賞唄,您的支持是我堅持寫好博文的動力
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章