Fashion-MNIST
本數據集是每張圖片大小28*28的灰度圖像,共有70000張,其中包含60,000個示例的訓練集和10,000個示例的測試集,10種標籤
比手寫體數據集更具挑戰性,適合初學者(我)學習
代碼實現
import tensorflow as tf
from tensorflow import keras
import numpy as np
import time
import sys
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
def get_fashion_mnist_labels(labels):
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels]
def show_fashion_mnist(images, labels):
_, figs = plt.subplots(1, len(images), figsize=(12, 12))
for f, img, lbl in zip(figs, images, labels):
f.imshow(img.reshape((28, 28)))
f.set_title(lbl)
f.axes.get_xaxis().set_visible(False)
f.axes.get_yaxis().set_visible(False)
plt.show()
X, y = [], []
for i in range(10):
X.append(x_train[i])
y.append(y_train[i])
show_fashion_mnist(X, get_fashion_mnist_labels(y))
batch_size = 256
if sys.platform.startswith('win'):
num_workers = 0 # 0表示不用額外的進程來加速讀取數據
else:
num_workers = 4
train_iter = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size) # 加載數據集,batch_size 小批量加載,batch_size是一個超參數
# 查看讀取一遍訓練數據需要的時間
start = time.time()
for X, y in train_iter:
continue
print('%.2f sec' % (time.time() - start))
輸出
0.12 sec
相關注解
函數作用:不顯示x、y軸座標
f.axes.get_xaxis().set_visible(False)
f.axes.get_yaxis().set_visible(False)
tf.data.Dataset.from_tensor_slices 進行加載數據集
train_iter = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size)