本文使用的數(shù)據(jù)集名為Fashion MNIST绝葡,是一個(gè)關(guān)于衣服的分類數(shù)據(jù)集。與MNIST手寫(xiě)數(shù)據(jù)集類似,都是作為圖片分類入門(mén)的新手?jǐn)?shù)據(jù)集榜旦,包含了70000張尺寸為28*28的黑白圖片,共有十個(gè)類別。
[站外圖片上傳中...(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中包含了這個(gè)數(shù)據(jù)集的API,但是很尷尬踏兜,國(guó)內(nèi)的網(wǎng)絡(luò)很難順利地通過(guò)把這個(gè)數(shù)據(jù)集下載下來(lái)昔驱,所以這里需要自行下載數(shù)據(jù)。
from tensorflow.examples.tutorials.mnist import input_data
data = input_data.read_data_sets('data/fashion')
注意檢查下載的數(shù)據(jù)格式,如果通過(guò)TensorFlow的API下載面睛,獲得的是28*28的圖片格式數(shù)據(jù),但是自行下載有可能會(huì)下載到784長(zhǎng)度的一維數(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ù)集的長(zhǎng)度和圖片格式都與教程中有所不同。
查看數(shù)據(jù)
在開(kāi)始處理數(shù)據(jù)之前,先查看一下數(shù)據(jù)的形式
import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(train_images[0].reshape(28,28))
plt.colorbar()
plt.grid(False)
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]])
建立序列模型并訓(xùn)練
這里使用了TensorFlow內(nèi)嵌的keras建立了包含兩個(gè)全連接層的神經(jīng)網(wǎng)絡(luò)镣丑,因?yàn)槭欠诸悊?wèn)題,所以最后一層使用了softmax作為激活函數(shù),spare_categorical_crossentropy為損失函數(shù)跟匆。
選錯(cuò)了損失函數(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
驗(yàn)證模型
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ù)測(cè)數(shù)據(jù)
predictions = model.predict(test_images)
展示預(yù)測(cè)結(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ù)測(cè)錯(cuò)誤的以紅色標(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)
原文地址:https://www.tensorflow.org/tutorials/keras/basic_classification