一.原理说明
卷积神经网络(Convolutional Neural Networks)是一种深度学习模型或类似于人工神经网络的多层感知器,常用来分析视觉图像。卷积神经网络的创始人是着名的计算机科学家 Yann LeCun,目前在 Facebook 工作,他是第一个通过卷积神经网络在 MNIST 数据集上解决手写数字问题的人。
二.数据说明
MINST数据集是机器学习领域一个经典的数据集,其中包括70000个样本,包括60000个训练样本和10000个测试样本
三.代码实战
第一步:导入头文件
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
第二步:导入数据并进行预处理
seed = 7
numpy.random.seed(seed)
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
第三步:构建模型网络
def baseline_model():
# create model
model = Sequential()
model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
第四步:训练和测试
# build the model
model = baseline_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=10, batch_size=200, verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))
结果:
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
- 16s - loss: 0.2236 - acc: 0.9366 - val_loss: 0.0746 - val_acc: 0.9768
Epoch 2/10
- 19s - loss: 0.0709 - acc: 0.9784 - val_loss: 0.0463 - val_acc: 0.9847
Epoch 3/10
- 19s - loss: 0.0504 - acc: 0.9845 - val_loss: 0.0420 - val_acc: 0.9860
Epoch 4/10
- 19s - loss: 0.0402 - acc: 0.9874 - val_loss: 0.0392 - val_acc: 0.9869
Epoch 5/10
- 19s - loss: 0.0320 - acc: 0.9898 - val_loss: 0.0345 - val_acc: 0.9885
Epoch 6/10
- 19s - loss: 0.0262 - acc: 0.9918 - val_loss: 0.0330 - val_acc: 0.9902
Epoch 7/10
- 19s - loss: 0.0227 - acc: 0.9929 - val_loss: 0.0341 - val_acc: 0.9890
Epoch 8/10
- 19s - loss: 0.0193 - acc: 0.9938 - val_loss: 0.0338 - val_acc: 0.9887
Epoch 9/10
- 19s - loss: 0.0165 - acc: 0.9949 - val_loss: 0.0303 - val_acc: 0.9900
Epoch 10/10
- 19s - loss: 0.0129 - acc: 0.9961 - val_loss: 0.0300 - val_acc: 0.9907
Baseline Error: 0.93%
标签:acc,loss,val,Keras,MINST,test,CNN,model,10
From: https://blog.csdn.net/u013289254/article/details/143607551