Keras构建简单CNN详细解析及代码(包括报错处理)

Keras构建CNN

参考

github源码

MNIST 数据集来自美国国家标准与技术研究所, 是NIST(National Institute of Standards and Technology)的缩小版,训练集 (training set) 由来自 250 个不同人手写的数字构成, 其中 50% 是高中学生, 50% 来自人口普查局 (the Census Bureau) 的工作人员,测试集(test set) 也是同样比例的手写数字数据.

该Keras教程将向你展示如何使用MNIST数据集构建CNN并实现> 99%的准确性。它与我之前的卷积神经网络教程中构建的结构完全相同 ,下图显示了网络的架构:

全部代码及解析

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.layers import Dense, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
import matplotlib.pylab as plt

batch_size = 128      # 每个批次的样本数量为128。
num_classes = 10      # 数据集中的类别数量为10(对应于MNIST数据集中的数字0到9)。
epochs = 10           # 训练模型时的迭代次数为10。在每个epoch中,模型将遍历整个训练集一次。

# input image dimensions   MNIST dataset的输入图像的维度是28x28像素。
img_x, img_y = 28, 28

# load the MNIST data set, which already splits into train and test sets for us
# 加载MNIST数据集,该数据集已经按训练集和测试集进行了划分。
(x_train, y_train), (x_test, y_test) =mnist.load_data()

# reshape the data into a 4D tensor - (sample_number, x_img_size, y_img_size, num_channels)
# because the MNIST is greyscale, we only have a single channel - RGB colour images would have 3
# 将数据重塑为 4D 张量-(样本数,x_img_size,y_img_size,num_channels),因为MNIST是灰度图像,所以只有一个通道- RGB彩色图像会有3个通道
x_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)
input_shape = (img_x, img_y, 1) #输入图像大小为 28×28,,通道数为 1(灰度图)

# convert the data to the right type  将数据转换为正确的类型
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 - this is for use in the
# categorical_crossentropy loss below
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=(5,5),strides=(2,2),
                 activation='relu',input_shape=input_shape
          ))   # 参数 padding 的默认值是 "valid" 不填充
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2)))  # 池化区域的大小(2,2),步长(2,2)

model.add(Conv2D(64,(5,5),activation='relu'))
model.add(MaxPooling2D(
    pool_size=(2,2)
))

model.add(Flatten()) # 将输入的多维张量扁平化为一维向量,为接下来的全连接层或者输出层做准备
model.add(Dense(2000,activation='relu')) #添加一个全连接层,包含1000个神经元,使用ReLU激活函数。
model.add(Dense(num_classes,activation='softmax'))  # 添加一个输出层,包含num_classes个神经元,使用softmax激活函数

#指定损失函数 标准交叉熵、优化器Adam  和  评价指标(准确率)
model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy'])

class AccuracyHistory(keras.callbacks.Callback):  # 定义一个回调类用于记录训练过程中的准确率
    def on_train_begin(self, logs={}):
        self.acc = []

    def on_epoch_end(self, batch, logs={}):
        self.acc.append(logs.get('acc'))

history = AccuracyHistory()

#使用fit方法对模型进行训练,指定训练数据、批次大小、迭代次数、验证数据和回调函数。
model.fit(x_train,y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,# :控制训练过程中输出的信息详细程度。设置为1表示输出每个训练轮次的信息。
          validation_data=(x_test,y_test),# 用于验证模型性能的数据集,可以在训练过程中评估模型在验证集上的表现。
          callbacks=[history]  # 指定回调函数的列表
)

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# print(history.acc)
plt.plot(range(1,11), history.acc)
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.show()

AccuracyHistory类解析

class AccuracyHistory(keras.callbacks.Callback): 
    def on_train_begin(self, logs={}):
        self.acc = []

    def on_epoch_end(self, batch, logs={}):
        self.acc.append(logs.get('acc'))

定义了一个回调类 AccuracyHistory,用于记录训练过程中的准确率。

该回调类包含两个方法:

  1. on_train_begin(self, logs={}) 方法在训练开始时调用。这里定义了一个列表 self.acc,用于存储准确率。
  2. on_epoch_end(self, batch, logs={}) 方法在每个训练轮次(epoch)结束时调用。这里使用 logs.get('acc') 来获取当前轮次的准确率,并将其添加到 self.acc 列表中。

通过定义这个回调类并使用 model.fit() 函数的 callbacks 参数将其传递给训练过程,你可以在训练过程中记录每个轮次的准确率。

输出结果

Test loss: 0.040341589599847794
Test accuracy: 0.9890999794006348

Keras构建简单CNN详细解析及代码(包括报错处理)_第1张图片

报错

  • Exception: URL fetch failure on https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz: None – [Errno 2] No such file or directory

解决办法:

手动下载数据集,然后放到指定的位置,一般为如下目录:

C:\Users.keras\datasets

mnist数据集下载

  • history.acc为空,导致准确率曲线图为空

    原因

    def on_epoch_end(self, batch, logs={}):
            self.acc.append(logs.get('acc'))
       # 这里acc和上文accuracy不对应改过来就行了
    model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adam(),metrics=['accuracy'])
    

你可能感兴趣的:(深度学习基础,keras,cnn,python)