卷积神经网络对比多层感知机:多了卷积层、池化层
卷积层用于提取特征,使用多个filter一张图能产生多个特征图,图像经过卷积后大小不变
池化层用于减小图像大小(一次池化减半):
- 减少需要处理的数据点
- 让图像位置差异变小
- 参数的数量和计算量下降
一个简单的卷积神经网络模型:图像→卷积层1→池化层1→卷积层2→池化层2→平坦层(用于将图像转成一维)→隐藏层→输出层
from keras.datasets import mnist
from keras.utils import np_utils
import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Dropout,Flatten,Conv2D,MaxPooling2D
np.random.seed(10)
#读入数据
(x_train, y_train),(x_test, y_test) = mnist.load_data()
#将数据转化为4维
x_train4D = x_train.reshape(x_train.shape[0],28,28,1).astype('float32')
x_test4D = x_test.reshape(x_test.shape[0],28,28,1).astype('float32')
#数据标准化
x_train4D_normalize = x_train4D / 255
x_test4D_normalize = x_test4D / 255
#label值One-Hot coding
y_trainOneHot = np_utils.to_categorical(y_train)
y_testOneHot = np_utils.to_categorical(y_test)
#建立模型
model = Sequential()
#卷积层1
model.add(Conv2D(filters=16,
kernel_size=(5,5),
padding='same',
input_shape=(28,28,1),
activation='relu'))
#池化层1
model.add(MaxPooling2D(pool_size=(2,2)))
#卷积层2
model.add(Conv2D(filters=36,
kernel_size=(5,5),
padding='same',
activation='relu'))
#池化层2
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
#平坦层
model.add(Flatten())
#隐藏层
model.add(Dense(128,activation='relu'))
model.add(Dropout(0.5))
#输出层
model.add(Dense(10,activation='softmax'))
print(model.summary())
#设置loss、优化器、输出精度
model.compile(loss='categorical_crossentropy',
optimizer='adam',metrics=['accuracy'])
#开始训练
train_history = model.fit(x=x_train4D_normalize,
y=y_trainOneHot, validation_split=0.2,
epochs=10,batch_size=300,verbose=2)
#评估模型准确率
score=model.evaluate(x_test4D_normalize,y_testOneHot)
score[1]