人工智能深度學習:使用TensorFlow2.0實現圖像分類


1.獲取Fashion MNIST數據集

本指南使用Fashion MNIST數據集,該數據集包含10個類別中的70,000個灰度圖像。 圖像顯示了低分辨率(28 x 28像素)的單件服裝,如下所示

 

 

 

Fashion MNIST旨在替代經典的MNIST數據集,通常用作計算機視覺機器學習計划的“Hello,World”。

我們將使用60,000張圖像來訓練網絡和10,000張圖像,以評估網絡學習圖像分類的准確程度。

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

圖像是28x28 NumPy數組,像素值介於0到255之間。標簽是一個整數數組,范圍從0到9.這些對應於圖像所代表的服裝類別:

LabelClass0T-shirt/top1Trouser2Pullover3Dress4Coat5Sandal6Shirt7Sneaker8Bag9Ankle boot

每個圖像都映射到一個標簽。 由於類名不包含在數據集中,因此將它們存儲在此處以便在繪制圖像時使用:

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

2.探索數據

讓我們在訓練模型之前探索數據集的格式。 以下顯示訓練集中有60,000個圖像,每個圖像表示為28 x 28像素:

print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(10000,)

3.處理數據

圖片展示

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

 

4.構造網絡

model = keras.Sequential(
[
    layers.Flatten(input_shape=[28, 28]),
    layers.Dense(128, activation='relu'),
    layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
             loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

5.訓練與驗證

model.fit(train_images, train_labels, epochs=5)
Epoch 1/5
60000/60000 [==============================] - 3s 58us/sample - loss: 0.4970 - accuracy: 0.8264
Epoch 2/5
60000/60000 [==============================] - 3s 43us/sample - loss: 0.3766 - accuracy: 0.8651
Epoch 3/5
60000/60000 [==============================] - 3s 42us/sample - loss: 0.3370 - accuracy: 0.8777
Epoch 4/5
60000/60000 [==============================] - 3s 42us/sample - loss: 0.3122 - accuracy: 0.8859
Epoch 5/5
60000/60000 [==============================] - 3s 42us/sample - loss: 0.2949 - accuracy: 0.8921





<tensorflow.python.keras.callbacks.History at 0x7f1f65d2c240>
model.evaluate(test_images, test_labels)
10000/10000 [==============================] - 0s 26us/sample - loss: 0.3623 - accuracy: 0.8737





[0.3623474566936493, 0.8737]

6.預測

predictions = model.predict(test_images)
print(predictions[0])
print(np.argmax(predictions[0]))
print(test_labels[0])
[2.1831402e-05 1.0357383e-06 1.0550731e-06 1.3231372e-06 8.0873624e-06
 2.6805745e-02 1.2466960e-05 1.6174167e-01 1.4259206e-04 8.1126428e-01]
9
9
def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], 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[i], true_label[i]
  plt.grid(False)
  plt.xticks([])
  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, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)
plt.show()

 

# 可視化結果
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, test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions, test_labels)
plt.show()

 

img = test_images[0]

img = (np.expand_dims(img,0))

print(img.shape)
predictions_single = model.predict(img)

print(predictions_single)
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
(1, 28, 28)
[[2.1831380e-05 1.0357381e-06 1.0550700e-06 1.3231397e-06 8.0873460e-06
  2.6805779e-02 1.2466959e-05 1.6174166e-01 1.4259205e-04 8.1126422e-01]]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM