keras实现Lenet5(手写字符识别mnist)

  • Lenet流程
    第一层为6个5X5卷积核,步长为11,不扩展边界,输入单通道的灰度图像,输入图像尺寸为32x32;
    第二层为2X2的最大值池化层,步长为2X2;
    第三层为16个5X5卷积核,步长为1
    1,不扩展边界;
    第四层为2X2的最大值池化层,步长为2X2;
    第五层为展平层,把前面输出的二维数据矩阵打开展开成一维数据,和全连接层对接
    第六层为全连接层,120个节点;
    第七层为全连接层,84个节点;
    第八层为输出层,激活函数为softmax。

代码:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPool2D
from keras.layers import Dense, Flatten,Dropout
import keras
from keras.datasets import mnist
from keras.utils import np_utils
from keras.layers import BatchNormalization
import cv2
import numpy as np
print(cv2.version)
#加载数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()
img_x, img_y = X_train.shape[1], X_train.shape[2]

#数据预处理

X_train=[cv2.cvtColor(cv2.resize(i,(32,32)),cv2.COLOR_GRAY2RGB) for i in X_train]
X_test=[cv2.cvtColor(cv2.resize(i,(32,32)),cv2.COLOR_GRAY2RGB) for i in X_test]
X_train = np.array(X_train,dtype=np.float32)/ 255.0
X_test = np.array(X_test,dtype=np.float32)/ 255.0
#X_train = X_train.astype('float32')
#X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

#to_categorical()将类别向量转换为二进制(只有0和1)的矩阵类型表示
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)
input_shape=(32,32,1)

model = Sequential()
model.add(Conv2D(6,kernel_size=(5,5),padding='valid',strides=(1,1),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Conv2D(16,kernel_size=(5,5),padding='valid',strides=(1,1),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
model.add(Flatten())
model.add(Dense(120,activation='relu'))
model.add(BatchNormalization())
model.add(Dense(84,activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(10,activation='softmax'))

#模型编译
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

#训练
model.fit(X_train, y_train, batch_size=128, epochs=10)

#评估模型
score = model.evaluate(X_test, y_test)
print('acc', score[1])

你可能感兴趣的:(keras,深度学习,python)