fashion資料集訓練

不該相遇在秋天發表於2020-11-16

下載資料集

fashion資料集總共有7萬張28*28畫素點的灰度圖片和標籤,涵蓋十個分類:T恤、褲子、套頭衫、連衣裙、外套、涼鞋、襯衫、運動鞋、包、靴子。

其中6萬張用於訓練,1萬張用於測試。

 

import tensorflow as tf
from tensorflow import keras
from matplotlib import pyplot as plt
import numpy as np
from tensorflow.keras.layers import Conv2D, MaxPool2D, Flatten, Dense,Dropout

fashion = keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)

 

搭建網路結構

model = keras.models.Sequential([
    Conv2D(64, (3, 3), activation='relu'),
    MaxPool2D((2, 2)),
    Conv2D(128, (3, 3), activation='relu'),
    MaxPool2D((2, 2)),
    Conv2D(128, (3, 3), activation='relu'),
    Flatten(),
    Dropout(0.4),
    Dense(128, activation='relu',kernel_regularizer=keras.regularizers.l2()),
    Dropout(0.4),
    Dense(10, activation='softmax')
])

 

模型編譯

model.compile(optimizer=keras.optimizers.Adam(lr=0.0001), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), metrics=['accuracy'])

 

執行訓練

history = model.fit(x_train, y_train, epochs=100, batch_size=32,verbose=1,validation_data=(x_test, y_test),validation_freq=1)

 

模型評估

score = model.evaluate(x_test, y_test, verbose=0, batch_size=32)
print('測試準確率:{}, 測試loss值: {}'.format(score[1], score[0]))

 

視覺化acc/loss曲線

#顯示訓練集和測試集的acc和loss曲線
plt.rcParams['font.sans-serif']=['SimHei']
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

plt.subplot(1, 2, 1)
plt.plot(acc, label='訓練Acc')
plt.plot(val_acc, label='測試Acc')
plt.title('Acc曲線')
plt.legend()

plt.subplot(1, 2, 2)
plt.plot(loss, label='訓練Loss')
plt.plot(val_loss, label='測試Loss')
plt.title('Loss曲線')
plt.legend()
plt.show()

 

相關文章