# 笔记：基于keras的不同神经网络模型Minst手写体识别

## 1.CNN版

1.导入数据

``````import keras
from keras.datasets import mnist

from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPool2D,Activation,Dropout
from matplotlib import pyplot as plt
``````

``````def load_data(path='mnist.npz'):
# Returns
Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
"""
path = get_file(path,
origin='https://s3.amazonaws.com/img-datasets/mnist.npz',
file_hash='8a61469f7ea1b51cbae51d4f78837e45')
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
return (x_train, y_train), (x_test, y_test)
``````

``````(x_train, y_train), (x_test, y_test) = mnist.load_data()
``````

``````print(x_train.shape, y_train.shape, x_test.shape, y_test.shape)
plt.imshow(x_train[5]) x代表的都是手写体的图
plt.show()
# print(y_train)
# plt.imshow(x_test[0])
# plt.show()
# print(y_test)
``````

(60000, 28, 28) (60000,) (10000, 28, 28) (10000,)

2.数据处理：转换数据格式和归一化

``````x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
``````

``````x_train = x_train / 255
x_test = x_test / 255
``````

``````y_train = keras.utils.to_categorical(y_train)
y_test = keras.utils.to_categorical(y_test)
``````

``````print(x_train.shape) (60000, 28, 28, 1)
print(y_train.shape) (60000, 10)
print(x_test.shape)  (10000, 28, 28, 1)
print(y_test.shape)  (10000, 10)
``````

3.建模（这里用的lenet5）

``````model = Sequential()

``````

4.配置模型参数再训练

``````model.compile(optimizer='Adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train, y_train, batch_size=64, epochs=50, validation_split=0.2)

``````

5.评估模型

#做出训练集上loss同步变化的情况

``````plt.plot(model.history.history['loss'])
plt.title('loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.show()
``````

#做出训练集上accuracy同步变化的情况

``````plt.plot(model.history.history['accuracy'])
plt.title('loss')
plt.xlabel('epochs')
plt.ylabel('loss')
plt.show()

``````

THE END