首先拙泽,定義網(wǎng)絡(luò)模型mnist_model
- 給出各種庫函數(shù)的依賴淌山,這里跟主函數(shù)一樣,也需要依賴Conv2D顾瞻,Maxpooling泼疑,Dense,F(xiàn)latten等各種層函數(shù)荷荤,實(shí)際上主函數(shù)部分因?yàn)闆]有網(wǎng)絡(luò)結(jié)構(gòu)的定義退渗,所以不需要這些層函數(shù)的定義
- 最重要的,keras.models類蕴纳,包含了網(wǎng)絡(luò)的序貫?zāi)P停篠equential()
from keras.models import Sequential
- 然后会油,我們參考lenet-5的網(wǎng)絡(luò)結(jié)構(gòu),可以看到第一卷積層有6個(gè)卷積核古毛,卷積核的大小是5*5翻翩,第一池化層縮小一倍,pooling_size = (2,2),第二卷積層有16個(gè)卷積核嫂冻,卷積核的大小是(5,5)胶征,第二池化層與第一池化層相同,然后將第二池化層壓平Flatten桨仿,然后跟上全連接層Dense進(jìn)行非線性組合以及降維到120弧烤,第二次降維到84,第三次降維到n_class=10
- 所以需要用到的核心層有:Conv2D, Maxpooling, Flatten, Dense這幾種網(wǎng)絡(luò)蹬敲,它們都屬于keras.layers類
from keras.layers import Conv2d,MaxPool2d,Flatten,Dense
圖片.png
- 在完成了庫函數(shù)的定義后暇昂,我們開始搭建網(wǎng)絡(luò)結(jié)構(gòu)
def mnist_model():
# 第一卷積層:
mnist_model.add(Conv2D(6,(5,5),activation='relu',input_shape=input_shape))
- 第一卷積層必須指定input_shape,一般input_shape=(row, col, channel)
#第一池化層
mnist_model.add(MaxPool2D(pool_size=(2,2)))
#第二卷積層伴嗡,這層不需要指定input
mnist_model.add(Conv2D(16,(5,5),activation='relu'))
#第二池化層
mnist_model.add(MaxPool2D(pool_size))
Flatten層
mnist.model.add(Flatten())
Dense層
mnist_model.add(Dense(120,activation='relu'))
Dense層
mnist_model.add(Dense(120,activation='relu'))
return mnist_mode
model函數(shù)部分到此為止
在主函數(shù)部分急波,首先也是導(dǎo)入依賴的數(shù)據(jù)庫
import model # 這是自己定義的模型函數(shù)
import numpy # 涉及reshape的操作,需要依賴numpy.reshape
from keras.dataset import mnist #導(dǎo)入keras自帶的mnist數(shù)據(jù)庫
首先瘪校,分出訓(xùn)練集和測試集澄暮,
(x_train,y_train),(x_test,y_test)=mnist.load_data()
然后阱扬,這里的x_train是60000,28,28的數(shù)組tuple泣懊,因?yàn)榈谝粚颖仨氈付╥nput_shape,一般情況下,tensorflow的變量結(jié)構(gòu)為:“數(shù)量麻惶,行馍刮,列,顏色通道”窃蹋。(不好說啊卡啰,,)
if keras.backend.image_data_format() = 'chanel_first'
# 此時(shí)希望數(shù)組的維度從60000,28,28轉(zhuǎn)到60000,1,28,28
x_train = numpy.reshape(x_train,[x_train.shape[0],1,28,28])
x_test = numpy.reshape(x_test,[x_test.reshape[1],1,28,28])
else
x_train = numpy.reshape(x_train,[x_train.shape[0],28,28,1])
x_test = numpy.reshape(x_test,[x_train.shape[0],28,28,1])
# 一般情況下是后一種警没,也是tensorflow變量的標(biāo)準(zhǔn)存儲(chǔ)形式
然后匈辱,是一些基本參數(shù),涉及到batch_size, epoch, input_shape杀迹,n_class
batch_size = 32
epoch = 12
n_class = 10
然后是y_train,y_test轉(zhuǎn)換成one-hot形式
y_train = keras.utils.np_utils.to_categorical(y_train,n_class)
y_test = keras.utils.np_utils.to_categorical(y_test,n_class)
model = model.mnist_model(input_data, n_class)
model.compile(optimizer='Adadelta', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train,y_train,batch_size,epoch,verbose=1)
載入模型亡脸,就是將模型放在這,
然后是編譯模型树酪,最重要的三個(gè)參數(shù)浅碾,一個(gè)是優(yōu)化器,一個(gè)是損失嗅回,一個(gè)是性能評(píng)估
最后是訓(xùn)練模型及穗,需要訓(xùn)練數(shù)據(jù),訓(xùn)練標(biāo)簽绵载,batch_size,epoch,
verbose是是否顯示進(jìn)度條的選項(xiàng)埂陆。
如果需要保存model
keras.models.save_model(temp_model,'mnist.h5')
del temp_model
temp_model = load_model('mnist.h5')
score = temp_model.evaluate(x_test,y_test,verbose=0)
print('test loss:',score[0])
print('test accuracy:',score[1])