TensorFlow——基本分類問題

本文使用的數(shù)據(jù)集名為Fashion MNIST,是一個關(guān)于衣服的分類數(shù)據(jù)集。與MNIST手寫數(shù)據(jù)集類似,都是作為圖片分類入門的新手?jǐn)?shù)據(jù)集,包含了70000張尺寸為28*28的黑白圖片,共有十個類別。

[站外圖片上傳中...(image-1f2f91-1537627931284)]

導(dǎo)入工具

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

下載數(shù)據(jù)

TensorFlow中包含了這個數(shù)據(jù)集的API,但是很尷尬,國內(nèi)的網(wǎng)絡(luò)很難順利地通過把這個數(shù)據(jù)集下載下來,所以這里需要自行下載數(shù)據(jù)。

from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/fashion')

注意檢查下載的數(shù)據(jù)格式,如果通過TensorFlow的API下載,獲得的是28*28的圖片格式數(shù)據(jù),但是自行下載有可能會下載到784長度的一維數(shù)組格式的數(shù)據(jù)

探索數(shù)據(jù)

(train_images,train_labels) = data.train.images,data.train.labels
train_images.shape
(55000,784)

可以看到,雖然我的數(shù)據(jù)是從教程中提供的github地址下載的,但是數(shù)據(jù)集的長度和圖片格式都與教程中有所不同。

查看數(shù)據(jù)

在開始處理數(shù)據(jù)之前,先查看一下數(shù)據(jù)的形式

import matplotlib.pyplot as plt 
%matplotlib inline
plt.imshow(train_images[0].reshape(28,28))
plt.colorbar()
plt.grid(False)
Fashion MNIST圖片
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
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].reshape(28,28),cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
Fashion MNIST圖片

建立序列模型并訓(xùn)練

這里使用了TensorFlow內(nèi)嵌的keras建立了包含兩個全連接層的神經(jīng)網(wǎng)絡(luò),因為是分類問題,所以最后一層使用了softmax作為激活函數(shù),spare_categorical_crossentropy為損失函數(shù)。

選錯了損失函數(shù)或者激活函數(shù)都可能導(dǎo)致模型不收斂

from tensorflow import keras
import tensorflow as tf
model = keras.Sequential([
    keras.layers.Dense(128,activation=tf.nn.relu),
    keras.layers.Dense(10,activation=tf.nn.softmax)
])
model.compile(
    optimizer = keras.optimizers.Adam(lr=0.1),
    loss = 'sparse_categorical_crossentropy',
    metrics = ['accuracy']
)
model.fit(train_images,train_labels,batch_size=100,epochs=5)
Epoch 1/5
55000/55000 [==============================] - 6s 106us/step - loss: 0.5668 - acc: 0.7905
Epoch 2/5
55000/55000 [==============================] - 4s 77us/step - loss: 0.4308 - acc: 0.8414
Epoch 3/5
55000/55000 [==============================] - 4s 77us/step - loss: 0.3967 - acc: 0.8543
Epoch 4/5
55000/55000 [==============================] - 4s 77us/step - loss: 0.3856 - acc: 0.8589
Epoch 5/5
55000/55000 [==============================] - 4s 77us/step - loss: 0.3660 - acc: 0.8640

驗證模型

test_images,test_labels = data.test.images,data.test.labels
test_images = test_images / 255.0
test_loss,test_acc = model.evaluate(test_images,test_labels)
print("Test accuracy:",test_acc)
10000/10000 [==============================] - 1s 77us/step
Test accuracy: 0.8496

預(yù)測數(shù)據(jù)

predictions = model.predict(test_images)

展示預(yù)測結(jié)果

def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], true_label[i], img[i].reshape(28,28)
  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' # 預(yù)測錯誤的以紅色標(biāo)注
  
  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')
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)
預(yù)測結(jié)果

原文地址:https://www.tensorflow.org/tutorials/keras/basic_classification

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容