一:使用tf.keras.model.Sequential搭建分類模型主要包括七個步驟:
- 導入包模塊
- 加載數據集(這里使用的是keras.datasets.fashion_mnist數據包)
- 切分訓練集和驗證集
- 對數據進行歸一化處理
- 搭建分類模型
- 訓練模型
- 將模型應用於測試集
二:導入數據包
這里將一次性導入在機器學習方面經常使用到的庫。
1 import numpy as np 2 import pandas as pd 3 import matplotlib as mpl 4 import matplotlib.pyplot as plt 5 import sklearn 6 import tensorflow as tf 7 import tensorflow.keras as keras
打印一下庫的相關信息
1 for module in np, pd, mpl, sklearn, tf, keras: 2 print (module.__name__, module.__version__)
三:加載數據集
這里使用的是keras自帶的數據集,用於圖像識別的數據
1 fashion_mnist = keras.datasets.fashion_mnist 2 (x_train_all, y_train_all), (x_test, y_test) = fashion_mnist.load_data()
在對數據進行處理之前,我們應該查看一下數據集中的數據樣本,所以我們定義一下兩個函數來查看數據集中的圖片
1 # 定義函數,查看一張圖片 2 def show_single_img(img_arr): 3 plt.imshow(img_arr, cmap='binary') 4 plt.show() 5 show_single_img(x_train_all[0])
顯示結果為:
1 # 定義函數,顯示多行多列圖片。顯示x_data的前n_rows*n_cols個圖片 2 def show_images(n_rows, n_cols, x_data, y_data, class_names): 3 assert len(x_data) == len(y_data)#數據集中的圖片的個數必須和其類別個數相同 4 assert n_rows*n_cols < len(x_data)#要顯示的數據量必須小於數據集中的數據量 5 plt.figure(figsize=(n_rows*1.5, n_cols*1.5)) 6 for row in range(n_rows): 7 for col in range(n_cols): 8 index = n_cols * row + col 9 plt.subplot(n_rows, n_cols, index+1) 10 plt.imshow(x_data[index], cmap='binary', interpolation='nearest') 11 plt.axis('off')# 不顯示坐標軸 12 plt.title(class_names[y_data[index]]) 13 plt.show() 14 class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 15 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle_boot']#fashion_mnist數據集圖片的類別 16 show_images(3, 3, x_test, y_test, class_names)
顯示結果為:
四:切分訓練集和驗證集
首先應該查看x_train_all中有多少張圖片:
1 print (x_train_all.shape) #(60000, 28, 28)
我們將前5000張作為驗證集validation,將后55000張作為訓練集:
1 x_train, x_valid = x_train_all[:5000], x_train_all[5000:] 2 y_train, y_valid = y_train_all[:5000], y_train_all[5000:]
五:對數據進行歸一化處理
歸一化規則:x = (x-u)/std。u:均值,std:方差
我們使用sklearn庫的preprocessing模塊的StandardScaler對象來對數據進行歸一化處理
1 from sklearn.preprocessing import StandardScaler 2 scaler = StandardScaler() 3 x_train_scaled = scaler.fit_transform(x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28,28) 4 x_valid_scaled = scaler.transform(x_valid.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28) 5 x_test_scaled = scaler.transform(x_test.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
這里有一個非常值得注意的點:fit_transform和transform的區別。
- 在進行歸一化處理的時候,我們對驗證集和測試及進行歸一化的時候,需要使用測試集的均值和方差,不能使用自己數據集的均值和方差。
- 這里fit_transform就可以記錄數據集的均值和方差,我們對訓練集進行歸一化的時候,使用這個函數,記錄下訓練集的均值和方差。
- 在對驗證集和測試集進行歸一化的時候使用transform函數,使用的就是訓練集的均值和方差。
六:搭建分類模型(兩種方式)
- 初始化的時候完成層的添加:
1 model = keras.models.Sequential([ 2 keras.layers.Flatten(input_shape = [28,28]), 3 keras.layers.Dense(300, activation = 'sigmoid'), 4 keras.layers.Dense(100, activation='sigmoid'), 5 keras.layers.Dense(10, activation = 'softmax') 6 ]) 7 model.compile(loss = 'sparse_categorical_crossentropy', 8 optimizer = 'sgd', 9 metrics = ['accuracy'])
- 初始化為空的模型,之后再根據需要添加層:
1 model = keras.models.Sequential() 2 model.add(keras.layers.Flatten(input_shape = [28,28])) 3 model.add(keras.layers.Dense(300, activation = 'sigmoid')) 4 model.add(keras.layers.Dense(100, activation = 'sigmoid')) 5 model.add(keras.layers.Dense(10, activation = 'softmax')) 6 7 model.compile(loss = 'sparse_categorical_crossentropy', 8 optimizer = 'sgd', 9 metrics = ['accuracy'])
這里有一個非常值得注意的點:sparse_categorical_crossentropy和categorical_crossentropy的區別。
- 這里我們的y是一個圖片類別的index。我們需要使用one_hot方法將y轉換成相對應的向量,以便於我們來計算損失函數。
- 這里的sparse_categorical_crossentropy就是實現這個功能,自動將y使用one_hot方法轉換成向量。
- 如果我們的y本身就是一個向量,則使用categorical_crossentropy即可。
七:訓練模型
1 history = model.fit(x_train_scaled, y_train, epochs=10, 2 validation_data=(x_valid_scaled, y_valid))
八:將模型應用於測試集上
1 model.evaluate(x_test_scaled,y_test)