本文我们将学习使用Keras一步一步搭建一个卷积神经网络。具体来说,我们将使用卷积神经网络对手写数字(MNIST数据集)进行识别,并达到99%以上的正确率。 ![]() 我们还将介绍Colaboratory——一个免费的Jupyter notebook环境,关键的是可以免费使用GPU(学生党买不起呀)! ![]() 为什么选择Keras呢? 主要是因为简单方便。更多细节请看:https:/// 什么卷积神经网络? 简单地说,卷积神经网络(CNNs)是一种多层神经网络,它可以有效地减少全连接神经网络参数量太大的问题。如果对其背后的原理感兴趣的话,斗胆推荐一些学习资料: 深度学习入门:基于Python的理论与实现 Neural Networks and Deep Learning CS231n: Convolutional Neural Networks for Visual Recognition 下面就直接进入主题吧! 1. 搭建环境如果想要在个人电脑上搭建的话,我们需要先安装好Python,进入:https://www./ ![]() 下载安装就好。 之后,打开终端输入pip install -i ![]() 输入以下命令可以确认正常安装: python -c 'import keras;print(keras.__version__)' ![]() 当然,如果想直接使用Colaboratory的话,直接打开你的Google云端硬盘 ![]() 为了方便起见,新建一个名为Keras的文件夹,进入Keras文件夹,单击鼠标右键 ![]() 选择Colaboratory就可新建一个Jupyter notebok啦! 如果没有看到Colaboratory这一项的话,就选择关联更多应用 ![]() 搜索Colaboratory,并关联即可。 2. 导入库和模块我们导入Sequential模型(相当于放积木的桌子)
接下来,我们导入各种层(各种形状各异积木) from keras.layers import Conv2D, MaxPool2Dfrom keras.layers import Dense, Flatten 最后,我们导入to_categorical函数,以便之后对数据进行转换
3. 加载数据MNIST是一个非常有名的手写数字数据集,我们可以使用Keras轻松加载它。 from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data() 查看一下训练集的大小
可以看到60000个样本,它们都是28像素x28像素的。 看一下这些手写数字长什么样 import matplotlib.pyplot as plt%matplotlib inlineplt.imshow(x_train[0]) ![]() 4. 预处理数据使用Keras是必须显式声明输入图像深度的尺寸。例如,具有所有3个RGB通道的全色图像的深度为3。 我们的MNIST图像的深度为1,但我们必须明确声明。 也就是说,我们希望将数据集从形状(n,rows,cols)转换为(n,rows,cols,channels)。
除此之外,我们将数据标准化一下: x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255 之后,将标记值(y_train, y_test)转换为One-Hot Encode的形式,至于为什么要这么做?请查看:
5. 定义模型结构我们参照下图定义一个模型结构 ![]() 代码如下: model = Sequential()model.add(Conv2D(32, kernel_size=(5,5), activation='relu', input_shape=(img_x, img_y, 1)))model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))model.add(Conv2D(64, kernel_size=(5,5), activation='relu'))model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))model.add(Flatten())model.add(Dense(1000, activation='relu'))model.add(Dense(10, activation='softmax')) 是不是有点搭积木的既视感? 6. 编译现在,只需要编译模型,就可以开始训练了。当编译模型时,我们声明了损失函数和优化器(SGD,Adam等)。
Keras有很多损失函数和优化器供你选择。 7. 训练接下来,我们传入训练集进行训练 model.fit(x_train, y_train, batch_size=128, epochs=10) 以下是在Colaboratory上训练的过程 ![]() 以下是在个人电脑上训练的过程 ![]() 可以看到,花费的时间差别还是很大的! 8. 评估模型最后,传入测试集对模型模型进行评估
准确率达到了%99以上! 完整代码如下: # 2. 导入库和模块from keras.models import Sequentialfrom keras.layers import Conv2D, MaxPool2Dfrom keras.layers import Dense, Flattenfrom keras.utils import to_categorical# 3. 加载数据from keras.datasets import mnist(x_train, y_train), (x_test, y_test) = mnist.load_data()# 4. 数据预处理img_x, img_y = 28, 28x_train = x_train.reshape(x_train.shape[0], img_x, img_y, 1)x_test = x_test.reshape(x_test.shape[0], img_x, img_y, 1)x_train = x_train.astype('float32')x_test = x_test.astype('float32')x_train /= 255x_test /= 255y_train = to_categorical(y_train, 10)y_test = to_categorical(y_test, 10)# 5. 定义模型结构model = Sequential()model.add(Conv2D(32, kernel_size=(5,5), activation='relu', input_shape=(img_x, img_y, 1)))model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))model.add(Conv2D(64, kernel_size=(5,5), activation='relu'))model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))model.add(Flatten())model.add(Dense(1000, activation='relu'))model.add(Dense(10, activation='softmax'))# 6. 编译model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# 7. 训练model.fit(x_train, y_train, batch_size=128, epochs=10)# 8. 评估模型score = model.evaluate(x_test, y_test)print('acc', score[1]) |
|