Keras学习(二)MNIST 识别---CNN 实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hoho1151191150/article/details/79859301

【本系列博文是学习 Keras 的笔记,Keras 版本为2.1.5,主要的参考资料为:Keras中文文档
上一节,我们从一个简单的 DNN MNIST 的例子学习 Keras 的基本使用,包括如何定义一个简单的模型、如何训练模型,以及模型的保存,本节我们学习 Keras 如何设计一个卷积神经网络,本节程序代码来自于 Keras 的 examples 中的 mnist_cnn.py

本节主要注意的点是 data_format
在如何表示一组彩色图片的问题上,Keras 的后端引擎 Theano 和 TensorFlow 发生了分歧:

  • Theano 表示法,即 ‘channel_first’ 模式,用 ‘th’ 表示,该模式会把 channel 参数放在 image_height 和 image_width前面,比如 100 张 RGB 三通道的 16×32(高为16宽为32)彩色图表示为下面这种形式(100,3,16,32),Caffe采取的也是这种方式。第 0个维度是样本维,代表样本的数目,第1个维度是通道维,代表颜色通道数。后面两个就是高和宽了。
  • 而在 TensorFlow 中,它的表达形式是(100,16,32,3),即把通道维放在了最后,这种数据组织方式称为“channels_last”,用 ‘tf’ 表示。

我们可以用 keras.backend.image_data_format() 查看 data_format,我们也可以用 keras.backend.set_image_dim_ordering(‘th’/’tf’) 设置 data_format

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

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

data_format 的判断: 此处我们也可以用 keras.backend.set_image_dim_ordering() 设置

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(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)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

网络定义、编译和训练:

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
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(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

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])

测试结果为 99.1% 左右

猜你喜欢

转载自blog.csdn.net/hoho1151191150/article/details/79859301