深度学习之keras学习笔记——MNIST数据集

本篇适合对卷积原理有初步了解,比较熟悉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')

感谢阅读!其它数据集示例详见我写的其它博客

boston_housing module: Boston housing price regression dataset. cifar10 module: CIFAR10 small images classification dataset. cifar100 module: CIFAR100 small images classification dataset. fashion_mnist module: Fashion-MNIST dataset. imdb module: IMDB sentiment classification dataset. mnist module: MNIST handwritten digits dataset. reuters module: Reuters topic classification dataset. import tensorflow as tf from tensorflow import keras fashion_mnist = keras.datasets.fashion_mnist (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() mnist = keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() cifar100 = keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar100.load_data() cifar10 = keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() imdb = keras.datasets.imdb (x_train, y_train), (x_test, y_test) = imdb.load_data() # word_index is a dictionary mapping words to an integer index word_index = imdb.get_word_index() # We reverse it, mapping integer indices to words reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # We decode the review; note that our indices were offset by 3 # because 0, 1 and 2 are reserved indices for "padding", "start of sequence", and "unknown". decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in x_train[0]]) print(decoded_review) boston_housing = keras.datasets.boston_housing (x_train, y_train), (x_test, y_test) = boston_housing.load_data() reuters= keras.datasets.reuters (x_train, y_train), (x_test, y_test) = reuters.load_data() tf.keras.datasets.reuters.get_word_index( path='reuters_word_index.json' )
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值