本篇适合对卷积原理有初步了解,比较熟悉python基础语法的朋友
MNIST数据集:
链接:https://pan.baidu.com/s/1mbYV7iLAq1hF_gfxdwC2sw
提取码:dcgc
需要导入的包:
import keras.utils as np_utils
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.layers import Activation, Dropout
定义超参数:
# 总共有多少个类别(例如MNIST数据集有10个类别,详见MNIST官方文档)
num_classes = 10
# 训练迭代次数
epochs = 1
# 训练批次(一般是设为2的次方,刚开始学可以不断试试,常见的是32)
batch_size = 32
读取数据:
x_train是形状(shape)为(60000, 28, 28)的三维数组
即60000张图片,每张图片宽28,长28
y_train是形状(shape)为(60000, )的一维数组
即60000张图片,每张图片宽28, 长28
# 读取MNIST数据集,第一次读取需要下载
(x_train, y_train), (x_test, y_test) = mnist.load_data()
数据预处理:
数据归一化
对应代码中的 / 255.(完整的是255.0, 省略了0)
将原本数据范围(0-255)缩小至(0-1)的范围,同时也将原本的int型转为了float型
注:
-1代表该维度不变,这里原本是60000,reshape后还是60000
宽为28,长为28,先宽再长,最后的1代表通道数,1为灰度图,3为彩图。2和4都不常见, 尤其是2; 4通道即为rgba,a代表透明度
# 对数据进行归一化和转换形状
# 将x_train的形状(shape)转换成(-1, 28, 28, 1)
x_train = x_train.reshape(-1, 28, 28, 1) / 255.
x_test = x_test.reshape(-1, 28, 28, 1) / 255.
# 转换成独热编码
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
定义模型:
一般来说,一个卷积层(Conv2D)固定搭配一个激活函数(Activation)
当前模型搭配如下:
卷积部分
1层卷积(32个卷积核,核边长为5)+1个激活函数(‘relu’)+1层池化(2x2)+1层Dropout(0.25)
1层卷积(256个卷积核,核边长为5)+1个激活函数(‘relu’)+1层池化(2x2)+1层Dropout(0.25)
全连接层
1024个神经元+1个激活函数(‘relu’)+1层Dropout(0.5)
10个神经元+1个激活函数(‘softmax’)
(其余搭配见我下一篇帖子cifar10数据集)
为什么是32,256个卷积核?为什么是1024个神经元?
答:
算是潜规则吧,一般是2的次方。
常见的模型中卷积核都是从32或64开始往上递增
第一层全连接神经元数量(1024)一般是最后一个卷积层中卷积核(256)的3~4倍
随着不断的深入学习,大家会对建模越来越有经验,刚开始的话死记一些套路,把模型中的细节部分弄懂,更深入了解下卷积原理就好了,当然也可以自己试着搭配模型
# 定义一个顺序模型对象
model = Sequential()
# 添加卷积层
model.add(Conv2D(
# 输入形状,第一层卷积必须要,后面可以不加。None代表不确定输入个数。
batch_input_shape=(None, 28, 28, 1),
# 卷积核(滤波器,过滤器,权重)的个数
filters=32,
# 卷积核的大小(长和宽),也可以传一个元组(5, 5),是一样的
kernel_size=5,
# 补0
padding='same',
))
# 添加激活函数relu,刚开始图像识别部分的建模全都用relu
model.add(Activation('relu'))
# 添加池化层(这是最大池化,还有个AvgPool2D平均池化)
model.add(MaxPooling2D(
# 池化核大小为2,一般也是设置成2
pool_size=2,
))
# 添加Dropout层,随机丢掉25%的数据,抑制过拟合
model.add(Dropout(0.25))
model.add(Conv2D(
filters=256,
kernel_size=5,
padding='same'
))
model.add(Activation('relu'))
model.add(MaxPooling2D(
pool_size=2,
))
model.add(Dropout(0.25))
# 将多维度的数据铺平成一维的
model.add(Flatten())
# 全连接层
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
# 最后输出10层,因为有10个分类
model.add(Dense(num_classes))
# 多分类,单标签的情况,输出层的激活函数都是softmax
model.add(Activation('softmax'))
编译模型:
优化器(optimizer)选adam
损失函数(loss)选categorical_crossentropy
评估标准(accuracy)选accuracy(要传一个列表)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
训练模型:
# 将训练集和对应的标签(label)传进来
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)
评估模型:
# 将测试集和对应的标签(label)传进来
# 返回测试集的损失函数和准确率
loss, accuracy = model.evaluate(x_test, y_test)
print('loss: ', loss)
print('accuracy: ', accuracy)
测试集结果:
loss: 0.034860136426170356
accuracy: 0.9898999929428101
模型保存
默认是保存的H5文件
model.save('model.h5')
完整代码:
import keras.utils as np_utils
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Activation, Dense, Dropout, Flatten
# 定义超参数
# 总共有多少个类别
num_classes = 10
# 训练迭代次数
epochs = 1
# 训练批次
batch_size = 32
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 数据预处理
x_train = x_train.reshape(-1, 28, 28, 1) / 255.
x_test = x_test.reshape(-1, 28, 28, 1) / 255.
# 转换成独热编码
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
# 定义模型
model = Sequential()
# 卷积层+池化层+Dropout层
model.add(Conv2D(
# 输入维度,第一层卷积必须要,后面可以不加。None代表不确定输入个数。
batch_input_shape=(None, 28, 28, 1),
# 卷积核(滤波器,过滤器,权重)的个数
filters=32,
# 卷积核的大小(长宽)
kernel_size=5,
# 补齐0
padding='same',
# 激活函数,前期的建模全都用relu
))
model.add(Activation('relu'))
# 添加池化层
model.add(MaxPooling2D(
# 池化核大小为2
pool_size=2,
))
# 添加Dropout层,抑制过拟合
model.add(Dropout(0.25))
model.add(Conv2D(
filters=256,
kernel_size=5,
padding='same',
))
model.add(Activation('relu'))
model.add(MaxPooling2D(
pool_size=2,
))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs)
loss, accuracy = model.evaluate(x_test, y_test)
print('loss: ', loss)
print('accuracy: ', accuracy)
model.save('model.h5')
感谢阅读!其它数据集示例详见我写的其它博客