TensorFlow 2.0學習筆記(1)：服飾影像分類

`pip install -U tensorflow_datasets #用來下載、讀取dataset`

`import tensorflow as tfimport tensorflow_datasets as tfdstfds.disable_progress_bar()import mathimport numpy as npimport matplotlib.pyplot as plt`

`dataset, metadata = tfds.load('fashion_mnist', as_supervised=True, with_info=True)train_dataset, test_dataset = dataset['train'], dataset['test']#模型用train_dataset訓練；用test_dataset進行測試`

`class_names = ['T-shirt/top','Trouser','Pullover','Dress', 'Coat','Sandal','Shirt','Sneaker','Bag','Ankle boot']#該資料集有10種不同的標籤[0~9]`

`num_train_examples = metadata.splits['train'].num_examplesnum_test_examples = metadata.splits['test'].num_examplesprint("Number of training examples: {}".format(num_train_examples))print("Number of test examples:     {}".format(num_test_examples))# Number of training examples: 60000 # Number of test examples:     10000`

`#正規化將pixel從[0~255]變成[0~1]之間的範圍def normalize(images, labels):    images = tf.cast(images, tf.float32)    images /= 255    return images, labels# map函數將normalize函式映射到train_dataset和test_datasettrain_dataset =  train_dataset.map(normalize)test_dataset  =  test_dataset.map(normalize)# 將圖片快取至記憶體當中，加快後續載入速度train_dataset =  train_dataset.cache()test_dataset  =  test_dataset.cache()`

`# 將圖片移除顏色for image, label in test_dataset.take(1):    break    image = image.numpy().reshape((28,28))# 單一圖片plt.figure()plt.imshow(image, cmap=plt.cm.binary)plt.colorbar()plt.grid(False)plt.show()# 顯示前25張圖片plt.figure(figsize=(10,10))i = 0for (image, label) in test_dataset.take(25):    image = image.numpy().reshape((28,28))    plt.subplot(5,5,i+1)    plt.xticks([])    plt.yticks([])    plt.grid(False)    plt.imshow(image, cmap=plt.cm.binary)    plt.xlabel(class_names[label])    i += 1plt.show()`

`model = tf.keras.Sequential([    tf.keras.layers.Flatten(input_shape=(28, 28, 1)),  #輸入層    tf.keras.layers.Dense(128, activation=tf.nn.relu), #隱藏層    tf.keras.layers.Dense(10)                          #輸出層])#(input_shape=(28, 28, 1))，將圖片尺寸從28x28轉到1維陣列(784 pixels)#(128, activation=tf.nn.relu)，128個神經元、激活函數使用RELU#(10)，代表著輸出有10個類別`

`model.compile(optimizer='adam',loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),metrics=['accuracy'])# optimizer：使用adam來降低損失# loss：測量損失# metrics：使用accuracy來衡量`

`BATCH_SIZE = 32train_dataset = train_dataset.cache().repeat().shuffle(num_train_examples).batch(BATCH_SIZE)test_dataset = test_dataset.cache().batch(BATCH_SIZE)model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))# .repeat()重複執行；# .shuffle()打散資料，讓電腦不跟著順序訓練；# .batch(BATCH_SIZE)每次使用32張圖片進行訓練`

`test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))print('Accuracy on test dataset:', test_accuracy)`

`for test_images, test_labels in test_dataset.take(1):    test_images = test_images.numpy()    test_labels = test_labels.numpy()    predictions = model.predict(test_images)predictions[0]              #預測第一張圖片，顯示10個類別的信心分數np.argmax(predictions[0])   #用numpy找出信心分數最高的類別test_labels[0]              #用test集判斷是否與預測結果一樣`

Written by