本次使用的是2.0測試版,正式版估計會很快就上線了 tf2好像更新了蠻多東西 雖然教程不多 還是找了個試試 的確簡單不少,但是還是比較喜歡現在這種寫法
老樣子先導入庫
import tensorflow as tf import tensorflow_datasets as tfds import numpy as np import matplotlib.pyplot as plt import math import tqdm import tqdm.auto tqdm.tqdm = tqdm.auto.tqdm print(tf.__version__) #導入庫
我的版本是2.0.0-dev20190402
現在正在使用google的colab 訓練,因為我本地tensorflow2.0死活裝不上一直報錯了 折騰了一天放棄了 何況google還有免費gpu和tpu能用 速度也不會太慢
導入了庫然后接着導入數據集
dataset,metadata = tfds.load('fashion_mnist',as_supervised=True,with_info=True) train_dataset,test_dataset = dataset['train'],dataset['test'] #導入數據集
創建個標簽 方便以后看
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #映射標簽
查看訓練樣本個數個測試樣本個數
num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.splits['test'].num_examples print("訓練樣本個數: {}".format(num_train_examples)) print("測試樣本個數:{}".format(num_test_examples))
訓練樣本個數: 60000 測試樣本個數:10000
接下來標准化樣本 直接/255
def normalize(images,labels): #定義標准化函數 images = tf.cast(images,tf.float32) images /= 255 return images,labels train_dataset = train_dataset.map(normalize)#標准化 test_dataset = test_dataset.map(normalize) #標准化
圖像數據中每個像素的值是范圍內的整數[0,255],
為了使模型正常工作,需要將這些值標准化為范圍[0,1]
顯示樣本
#顯示前25幅圖像。訓練集並在每個圖像下面顯示類名 plt.figure(figsize=(10,10)) i = 0 for (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 += 1 plt.show()
建立模型
#建立模型 model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28,28,1)), #輸入層 tf.keras.layers.Dense(256,activation=tf.nn.relu),#隱藏層1 tf.keras.layers.Dense(128,activation=tf.nn.relu),#隱藏層2 tf.keras.layers.Dense(10,activation=tf.nn.softmax)#輸出層 ])
一個四層模型這就建立好了。。。。。 一個輸入層兩個隱藏層一個輸出層
-
輸入
tf.keras.layers.Flatten
-這一層將圖像從2d-數組轉換為28。×28個像素,一個784像素的一維數組(28*28)。將這一層想象為將圖像中的逐行像素拆開,並將它們排列起來。該層沒有需要學習的參數,因為它只是重新格式化數據。 -
“隱藏”
tf.keras.layers.Dense
-由128個神經元組成的密集連接層。每個神經元(或節點)從前一層的所有784個節點獲取輸入,根據訓練過程中將學習到的隱藏參數對輸入進行加權,並將單個值輸出到下一層。 -
輸出量
tf.keras.layers.Dense
-A 10節點Softmax層,每個節點表示一組服裝。與前一層一樣,每個節點從其前面層的128個節點獲取輸入。每個節點根據學習到的參數對輸入進行加權,然后在此范圍內輸出一個值。[0, 1]
,表示圖像屬於該類的概率。所有10個節點值之和為1。
接下來定義優化器和損失函數
#定義優化器和損失函數 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
然后再設置一下訓練輪次和樣本
BATCH_SIZE = 32 train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE) test_dataset = test_dataset.batch(BATCH_SIZE)
訓練樣本開沖!
#訓練模型 model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))
然后放上結果
Epoch 1/5 1875/1875 [==============================] - 52s 28ms/step - loss: 0.8060 - accuracy: 0.7083 Epoch 2/5 1875/1875 [==============================] - 35s 18ms/step - loss: 0.5326 - accuracy: 0.8074 Epoch 3/5 1875/1875 [==============================] - 33s 18ms/step - loss: 0.4673 - accuracy: 0.8315 Epoch 4/5 1875/1875 [==============================] - 34s 18ms/step - loss: 0.4341 - accuracy: 0.8439 Epoch 5/5 1875/1875 [==============================] - 34s 18ms/step - loss: 0.4145 - accuracy: 0.8507 <tensorflow.python.keras.callbacks.History at 0x7f8b2bdfca90>
0.85的准確率 還行吧 google的GPU還是蠻快的吧
最后看一下模型在測試集上面的表現如何
test_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32)) print('Accuracy on test dataset:', test_accuracy)
313/313 [==============================] - 6s 18ms/step - loss: 0.4331 - accuracy: 0.8435
Accuracy on test dataset: 0.8435
還行吧 相差無幾,后面還有一些跟之前差不多的用模型預測和顯示結果圖片就不放上來了 放在下面的完整代碼
下一張嘗試一下使用CNN卷積神經網絡,反正使用tf.keras建立起來也是蠻簡單的
最后放上代碼

import tensorflow as tf import tensorflow_datasets as tfds import numpy as np import matplotlib.pyplot as plt import math import tqdm import tqdm.auto tqdm.tqdm = tqdm.auto.tqdm print(tf.__version__) #導入庫 dataset,metadata = tfds.load('fashion_mnist',as_supervised=True,with_info=True) train_dataset,test_dataset = dataset['train'],dataset['test'] #導入數據集 class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #映射標簽 num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.splits['test'].num_examples print("訓練樣本個數: {}".format(num_train_examples)) print("測試樣本個數:{}".format(num_test_examples)) def normalize(images,labels): #定義標准化函數 images = tf.cast(images,tf.float32) images /= 255 return images,labels train_dataset = train_dataset.map(normalize)#標准化 test_dataset = test_dataset.map(normalize) #標准化 #繪制一個圖像 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 = 0 for (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 += 1 plt.show() #建立模型 model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28,28,1)), #輸入層 tf.keras.layers.Dense(256,activation=tf.nn.relu),#隱藏層1 tf.keras.layers.Dense(128,activation=tf.nn.relu),#隱藏層2 tf.keras.layers.Dense(10,activation=tf.nn.softmax)#輸出層 ]) #定義優化器和損失函數 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) #設置訓練參數 BATCH_SIZE = 32 train_dataset = train_dataset.repeat().shuffle(num_train_examples).batch(BATCH_SIZE) test_dataset = test_dataset.batch(BATCH_SIZE) #訓練模型 model.fit(train_dataset, epochs=5, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE)) 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.shape predictions[0] np.argmax(predictions[0]) test_labels[0] def plot_image(i, predictions_array, true_labels, images): predictions_array, true_label, img = predictions_array[i], true_labels[i], images[i] plt.grid(False) plt.xticks([]) plt.yticks([]) plt.imshow(img[...,0], cmap=plt.cm.binary) predicted_label = np.argmax(predictions_array) if predicted_label == true_label: color = 'blue' else: color = 'red' 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') i = 0 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) i = 12 plt.figure(figsize=(6,3)) plt.subplot(1,2,1) plot_image(i, predictions, test_labels, test_images) plt.subplot(1,2,2) plot_value_array(i, predictions, test_labels) 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) img = test_images[0] print(img.shape) img = np.array([img]) print(img.shape) predictions_single = model.predict(img) print(predictions_single) plot_value_array(0, predictions_single, test_labels) _ = plt.xticks(range(10), class_names, rotation=45) np.argmax(predictions_single[0])