卷积神经网络案例:LeNet-5手写数字识别

一、LeNet-5网络结构
1.1 LeNet-5介绍:
由Yann LeCun(杨立昆)于1998年提出的一种经典的卷积网络结构。
第一个成功应用于数字识别问题的卷积神经网络。
1.2 LeNet-5网络结构:共7层
输入层
卷积层
池化层
卷积层
池化层
全连接层
输出层
在这里插入图片描述
二、LeNet-5手写数字识别
2.1 MNIST数据集展示:mnist.load_data()加载数据集

from keras.datasets import mnist
(X0,Y0),(X1,Y1) = mnist.load_data()
print(X0.shape)
from matplotlib import pyplot as plt
plt.figure()
fig,ax = plt.subplots(2,5)
ax=ax.flatten()
for i in range(10):
    Im=X0[Y0==i][0]
    ax[i].imshow(Im)
plt.show();

在这里插入图片描述

2.2 数据预处理

from keras.utils import np_utils
N0=X0.shape[0];N1=X1.shape[0]
print([N0,N1])
X0 = X0.reshape(N0,28,28,1)/255
X1 = X1.reshape(N1,28,28,1)/255
YY0 = np_utils.to_categorical(Y0)
YY1 = np_utils.to_categorical(Y1)
print(YY1)

2.3 LeNet-5代码实现

#从Keras的layers中加载大量的模块用于构建CNN模型
from keras.layers import Conv2D,Dense,Flatten,Input,MaxPooling2D 
from keras import Model
#输入层
input_layer = Input([28,28,1])
x = input_layer
x = Conv2D(6,[5,5],padding = "same", activation = 'relu')(x) 
x = MaxPooling2D(pool_size = [2,2], strides = [2,2])(x)    
x = Conv2D(16,[5,5],padding = "valid", activation = 'relu')(x) 
x = MaxPooling2D(pool_size = [2,2], strides = [2,2])(x)
x = Flatten()(x)   
x = Dense(120,activation = 'relu')(x)
x = Dense(84,activation = 'relu')(x)
x = Dense(10,activation = 'softmax')(x)
output_layer=x
model=Model(input_layer,output_layer)
model.summary()  #给出LeNet-5的模型概要和参数情况

在这里插入图片描述

2.4 LeNet-5编译运行

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X0, YY0, epochs=10, batch_size=200, validation_data=[X1,YY1]) 

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_31391601/article/details/115047351