模型源自Yann LeCun(1998)的论文《Gradient-Based Learning Applied to Document Recognition》,用于MNIST数据集。模型输入为32X32的灰度图像,第一层为6个5X5卷积核,不扩展边界;第二层为2X2的最大值池化层,步进为2X2;第三层为16个5X5卷积核,不扩展边界;第四层为2X2的最大值池化层,步进为2X2;第五层为展平层,并全连接120个节点;第六层为全连接层,84个节点;第七层为全连接softmax层,输出结果。
原论文中第二层池化层和第三层卷积层之间为是部分连接。本文中并未考虑,而是做成全连接,模型结构如下图所示。
模型采用keras的Sequential实现,源数据分为train和test两个文件夹,每个文件夹下有十个子文件夹,分别方有各数字对应的灰度图。实现代码如下:
import os
import cv2
from numpy import *
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Conv2D, MaxPooling2D, Flatten
from keras.optimizers import SGD
from keras.utils import np_utils
from keras.utils.vis_utils import plot_model
def loadData(path):
data = []
labels = []
for i in range(10):
dir = './'+path+'/'+str(i)
listImg = os.listdir(dir)
for img in listImg:
data.append([cv2.imread(dir+'/'+img, 0)])
labels.append(i)
print path, i, 'is read'
return data, labels
trainData, trainLabels = loadData('train')
testData, testLabels = loadData('test')
trainLabels = np_utils.to_categorical(trainLabels, 10)
testLabels = np_utils.to_categorical(testLabels, 10)
model = Sequential()
model.add(Conv2D(filters=6, kernel_size=(5,5), padding='valid', input_shape=(1,28,28), activation='tanh'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=16, kernel_size=(5,5), padding='valid', activation='tanh'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(120, activation='tanh'))
model.add(Dense(84, activation='tanh'))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.05, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(trainData, trainLabels, batch_size=500, epochs=20, verbose=1, shuffle=True)
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=False)
网络结构图如下: