使用keras下载数据集及搭建神经网络
import keras
from keras.models import load_model
from keras.datasets import mnist
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
(x_train, y_train), (x_test, y_test) = mnist.load_data(path='C:/Users/lenovo/Desktop/pythonexp/22 proj/hand_writing recognition/mnist.npz')
在load_data函数()中加入路径即可将数据集下载到本地,以后运行就不需要重复下载了。
对数据集进行预处理:
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
num_classes=10
# 手写数字0-9,所以num_classes为10
#将类向量用one_hot编码
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
#对像素值进行归一化处理
x_train /= 255
x_test /= 255
进行神经网络搭建:
batch_size = 128
epochs = 10
input_shape = (28, 28, 1)
#开始构造神经网络
model = Sequential()
#添加一个二维卷积层,卷积核数32,每个卷积核大小3*3,relu激活函数表示将负数设置为0,正数保持不变,input_shape表示输入的形状
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
#添加一个二维最大化池,池化窗口大小2*2
model.add(MaxPooling2D(pool_size=(2, 2)))
#以0.25的概率随机的将输入中的一些元素置为0,增强模型的泛化能力,减少模型对特定特征的依赖
model.add(Dropout(0.25))
#将输入数据展平为一维向量,方便后续处理
model.add(Flatten())
#添加全连接层,256代表该层神经元个数,也是输出数据的维度。relu同上
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
#该连接层用softmax激活,将输入数据转化为一个概率分布,输出即为每个类别的概率,以此来分类
model.add(Dense(num_classes, activation='softmax'))
进行神经网络训练并将模型结果保存到本地:
#配置模型训练参数
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])
#进行神经网络训练,并返回训练历史对象
hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
print("The model has successfully trained")
model.save('mnist.h5')
print("Saving the model as mnist.h5")
如下图所示训练结束:
进行模型效果验证:
model = load_model('C:/Users/lenovo/Desktop/pythonexp/22 proj/hand_writing recognition/mnist.h5')
score = model.evaluate(x_test, y_test, verbose=2)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
结果:
epochs=10数目较少,增加遍历次数可以使准确率更高。