一、读取数据
使用Python、Keras
# 头文件
from keras.datasets import mnist
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Convolution2D, Dense, Flatten, Activation, MaxPooling2D
from keras.utils import np_utils
from keras.optimizers import Adam
import numpy as np
from keras.models import load_model
import numpy as np
from PIL import Image
# 读取数据并查看,数据集下载地址https://d.ailemon.me/mnist.npz
# 也可以使用 (x_train, y_train), (x_test, y_test) = mnist.load_data()会自动在线下载
(x_train, y_train), (x_test, y_test) = mnist.load_data("C:/Users/Li Yanbin/Desktop/StudyNN/mnist.npz")
plt.subplot(121)
plt.imshow(x_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(122)
plt.imshow(x_train[1], cmap=plt.get_cmap('gray'))
# show the plot
plt.show()
二、数据预处理
# 数据预处理
x_train = x_train.reshape(60000, 28, 28, 1)
x_test = x_test.reshape(10000, 28, 28, 1)
# 标签onehot编码
y_test = np_utils.to_categorical(y_test, 10)
y_train = np_utils.to_categorical(y_train, 10)
三、建立模型并训练
# design model
model = Sequential()
model.add(Convolution2D(25, (5, 5), input_shape=(28, 28, 1)))
model.add(MaxPooling2D(2, 2))
model.add(Activation('relu'))
model.add(Convolution2D(50, (5, 5)))
model.add(MaxPooling2D(2, 2))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(50))
model.add(Activation('relu'))
model.add(Dense(10))
model.add(Activation('softmax'))
adam = Adam(lr=0.001)
# compile model
model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])
# training model
model.fit(x_train, y_train, batch_size=100, epochs=5)
# test model
print(model.evaluate(x_test, y_test, batch_size=100))
四、保存模型
注意保存模型和读取模型,用读取的模型训练数据
# save model
model.save('./model.h5')
五、查看效果
# 读取图片
def ImageToMatrix(filename):
im = Image.open(filename)
#change to greyimage
im=im.convert("L")
data = im.getdata()
data = np.matrix(data,dtype='int')
return data
# 读取模型
model = load_model('./model.h5')
# 读取数据并处理
data=ImageToMatrix('./5.png')
data = np.array(data)
data = data.reshape(1, 28, 28, 1)
# 预测并查看结果
result=model.predict_classes(data,batch_size=1,verbose=0)
print(result)
测试图片:
测试结果: