下面是一个Mnist手写识别的例子
导入必要的包
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
from matplotlib import pyplot as plt
如果没有相应的包,请自行导入,我在这里使用的是Anaconda(Python3.6)的环境,如果你在自己的环境下导入不成功,请自行下载Anaconda,网址https://www.anaconda.com/download/#windows。
设置参数
batch_size = 128
num_classes = 10
epochs = 3
img_rows, img_cols = 28, 28
导入数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data2()
得到输入图像的shape
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
print(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
image_data_format(),返回默认的图像的维度顺序(‘channels_last’或‘channels_first’),在表示一组彩色图片的问题上,Theano和Caffe使用(样本数,通道数,行或称为高,列或称为宽)通道在前的方式,称为channels_first;而TensorFlow使用(样本数,行或称为高,列或称为宽,通道数)通道在后的方式,称为channels_last。
归一化
x_train /= 255
x_test /= 255
把y向量转化为01矩阵
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
比如将[2 1]转化为[[0 0 1 0 0 0 0 0 0 0],[0 1 0 0 0 0 0 0 0 0]]
卷积核心代码
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
#为了防止过拟合,我们加上一个最大池化层,再加上一个Dropout层
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
#数据转换
model.add(Flatten())
model.add(Dense(128, activation='relu'))
#怕过拟合,就用dropout
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
#编译模型
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=['accuracy'])
#训练模型
history=model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
#评估模型
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
模型训练过程可视化
accuracy的历史
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train','validation'],loc='upper left')
plt.show()
loss的历史
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train','validation'],loc='upper left')
plt.show()
结果如下:
测试集损失率: 0.025634088496793994
测试集准确率: 0.9918