百度友情链接,佛山选择免费网站优化,注册岩土工程师,psd转wordpress我们将训练一个卷积神经网络来对 MNIST 数据库中的图像进行分类#xff0c;可以与前面所提到的CNN实现对比CNN对 MNIST 数据库中的图像进行分类-CSDN博客
加载 MNIST 数据库
MNIST 是机器学习领域最著名的数据集之一。
它有 70,000 张手写数字图像 - 下载非常简单 - 图像尺…我们将训练一个卷积神经网络来对 MNIST 数据库中的图像进行分类可以与前面所提到的CNN实现对比CNN对 MNIST 数据库中的图像进行分类-CSDN博客
加载 MNIST 数据库
MNIST 是机器学习领域最著名的数据集之一。
它有 70,000 张手写数字图像 - 下载非常简单 - 图像尺寸为 28x28 - 灰度图像
from keras.datasets import mnist# 使用 Keras 导入预洗牌 MNIST 数据库
(X_train, y_train), (X_test, y_test) mnist.load_data()print(The MNIST database has a training set of %d examples. % len(X_train))
print(The MNIST database has a test set of %d examples. % len(X_test)) 将前六个训练图像可视化
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.cm as cm
import numpy as np# 绘制前六幅训练图像
fig plt.figure(figsize(20,20))
for i in range(6):ax fig.add_subplot(1, 6, i1, xticks[], yticks[])ax.imshow(X_train[i], cmapgray)ax.set_title(str(y_train[i])) 查看图像的更多细节
def visualize_input(img, ax):ax.imshow(img, cmapgray)width, height img.shapethresh img.max()/2.5for x in range(width):for y in range(height):ax.annotate(str(round(img[x][y],2)), xy(y,x),horizontalalignmentcenter,verticalalignmentcenter,colorwhite if img[x][y]thresh else black)fig plt.figure(figsize (12,12))
ax fig.add_subplot(111)
visualize_input(X_train[0], ax) 预处理输入图像通过将每幅图像中的每个像素除以 255 来调整图像比例
# normalize the data to accelerate learning
mean np.mean(X_train)
std np.std(X_train)
X_train (X_train-mean)/(std1e-7)
X_test (X_test-mean)/(std1e-7)print(X_train shape:, X_train.shape)
print(X_train.shape[0], train samples)
print(X_test.shape[0], test samples) 对标签进行预处理使用单热方案对分类整数标签进行编码
from keras.utils import np_utilsnum_classes 10
# print first ten (integer-valued) training labels
print(Integer-valued labels:)
print(y_train[:10])# one-hot encode the labels
# convert class vectors to binary class matrices
y_train np_utils.to_categorical(y_train, num_classes)
y_test np_utils.to_categorical(y_test, num_classes)# print first ten (one-hot) training labels
print(One-hot labels:)
print(y_train[:10]) 重塑数据以适应我们的 CNN和 input_shape
# input image dimensions 28x28 pixel images.
img_rows, img_cols 28, 28X_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)print(image input shape: , input_shape)
print(x_train shape:, X_train.shape)
定义模型架构 论文地址lecun-01a.pdf 要在 Keras 中实现 LeNet-5请阅读原始论文并从第 6、7 和 8 页中提取架构信息。以下是构建 LeNet-5 网络的主要启示
每个卷积层的滤波器数量从图中以及论文中的定义可以看出每个卷积层的深度滤波器数量如下C1 6、C3 16、C5 120 层。每个 CONV 层的内核大小根据论文内核大小 5 x 5每个卷积层之后都会添加一个子采样层POOL。每个单元的感受野是一个 2 x 2 的区域即 pool_size 2。请注意LeNet-5 创建者使用的是平均池化它计算的是输入的平均值而不是我们在早期项目中使用的最大池化层后者传递的是输入的最大值。如果您有兴趣了解两者的区别可以同时尝试。在本实验中我们将采用论文架构。激活函数LeNet-5 的创建者为隐藏层使用了 tanh 激活函数因为对称函数被认为比 sigmoid 函数收敛更快。一般来说我们强烈建议您为网络中的每个卷积层添加 ReLU 激活函数。
需要记住的事项
始终为 CNN 中的 Conv2D 层添加 ReLU 激活函数。除了网络中的最后一层密集层也应具有 ReLU 激活函数。在构建分类网络时网络的最后一层应该是具有软最大激活函数的密集FC层。最终层的节点数应等于数据集中的类别总数。
from keras.models import Sequential
from keras.layers import Conv2D, AveragePooling2D, Flatten, Dense
#Instantiate an empty model
model Sequential()# C1 Convolutional Layer
model.add(Conv2D(6, kernel_size(5, 5), strides(1, 1), activationtanh, input_shapeinput_shape, paddingsame))# S2 Pooling Layer
model.add(AveragePooling2D(pool_size(2, 2), strides2, paddingvalid))# C3 Convolutional Layer
model.add(Conv2D(16, kernel_size(5, 5), strides(1, 1), activationtanh, paddingvalid))# S4 Pooling Layer
model.add(AveragePooling2D(pool_size(2, 2), strides2, paddingvalid))# C5 Fully Connected Convolutional Layer
model.add(Conv2D(120, kernel_size(5, 5), strides(1, 1), activationtanh, paddingvalid))#Flatten the CNN output so that we can connect it with fully connected layers
model.add(Flatten())# FC6 Fully Connected Layer
model.add(Dense(84, activationtanh))# Output Layer with softmax activation
model.add(Dense(10, activationsoftmax))# print the model summary
model.summary() 编译模型
我们将使用亚当优化器
# the loss function is categorical cross entropy since we have multiple classes (10) # compile the model by defining the loss function, optimizer, and performance metric
model.compile(losscategorical_crossentropy, optimizeradam, metrics[accuracy])
训练模型
LeCun 和他的团队采用了计划衰减学习法学习率的值按照以下时间表递减前两个历元为 0.0005接下来的三个历元为 0.0002接下来的四个历元为 0.00005之后为 0.00001。在论文中作者对其网络进行了 20 个历元的训练。
from keras.callbacks import ModelCheckpoint, LearningRateScheduler# set the learning rate schedule as created in the original paper
def lr_schedule(epoch):if epoch 2: lr 5e-4elif epoch 2 and epoch 5:lr 2e-4elif epoch 5 and epoch 9:lr 5e-5else: lr 1e-5return lrlr_scheduler LearningRateScheduler(lr_schedule)# set the checkpointer
checkpointer ModelCheckpoint(filepathmodel.weights.best.hdf5, verbose1, save_best_onlyTrue)# train the model
hist model.fit(X_train, y_train, batch_size32, epochs20,validation_data(X_test, y_test), callbacks[checkpointer, lr_scheduler], verbose2, shuffleTrue) 在验证集上加载分类准确率最高的模型
# load the weights that yielded the best validation accuracy
model.load_weights(model.weights.best.hdf5)
计算测试集的分类准确率
# evaluate test accuracy
score model.evaluate(X_test, y_test, verbose0)
accuracy 100*score[1]# print test accuracy
print(Test accuracy: %.4f%% % accuracy) 评估模型
import matplotlib.pyplot as pltf, ax plt.subplots()
ax.plot([None] hist.history[accuracy], o-)
ax.plot([None] hist.history[val_accuracy], x-)
# 绘制图例并自动使用最佳位置 loc 0。
ax.legend([Train acc, Validation acc], loc 0)
ax.set_title(Training/Validation acc per Epoch)
ax.set_xlabel(Epoch)
ax.set_ylabel(acc)
plt.show() import matplotlib.pyplot as pltf, ax plt.subplots()
ax.plot([None] hist.history[loss], o-)
ax.plot([None] hist.history[val_loss], x-)# Plot legend and use the best location automatically: loc 0.
ax.legend([Train loss, Val loss], loc 0)
ax.set_title(Training/Validation Loss per Epoch)
ax.set_xlabel(Epoch)
ax.set_ylabel(Loss)
plt.show() 文章转载自: http://www.morning.jfjqs.cn.gov.cn.jfjqs.cn http://www.morning.bnygf.cn.gov.cn.bnygf.cn http://www.morning.hbxnb.cn.gov.cn.hbxnb.cn http://www.morning.pdmc.cn.gov.cn.pdmc.cn http://www.morning.fjntg.cn.gov.cn.fjntg.cn http://www.morning.mgwpy.cn.gov.cn.mgwpy.cn http://www.morning.snnb.cn.gov.cn.snnb.cn http://www.morning.qgkcs.cn.gov.cn.qgkcs.cn http://www.morning.ywpcs.cn.gov.cn.ywpcs.cn http://www.morning.mwcqz.cn.gov.cn.mwcqz.cn http://www.morning.haibuli.com.gov.cn.haibuli.com http://www.morning.rnwt.cn.gov.cn.rnwt.cn http://www.morning.qcnk.cn.gov.cn.qcnk.cn http://www.morning.yckrm.cn.gov.cn.yckrm.cn http://www.morning.ldynr.cn.gov.cn.ldynr.cn http://www.morning.thjqk.cn.gov.cn.thjqk.cn http://www.morning.ljwyc.cn.gov.cn.ljwyc.cn http://www.morning.ktmnq.cn.gov.cn.ktmnq.cn http://www.morning.cykqg.cn.gov.cn.cykqg.cn http://www.morning.mghgl.cn.gov.cn.mghgl.cn http://www.morning.wqcz.cn.gov.cn.wqcz.cn http://www.morning.pmrlt.cn.gov.cn.pmrlt.cn http://www.morning.kndyz.cn.gov.cn.kndyz.cn http://www.morning.attorneysportorange.com.gov.cn.attorneysportorange.com http://www.morning.dhtdl.cn.gov.cn.dhtdl.cn http://www.morning.tkrwm.cn.gov.cn.tkrwm.cn http://www.morning.jnoegg.com.gov.cn.jnoegg.com http://www.morning.jqjnx.cn.gov.cn.jqjnx.cn http://www.morning.pbwcq.cn.gov.cn.pbwcq.cn http://www.morning.xscpq.cn.gov.cn.xscpq.cn http://www.morning.gmrxh.cn.gov.cn.gmrxh.cn http://www.morning.fqtzn.cn.gov.cn.fqtzn.cn http://www.morning.bgpb.cn.gov.cn.bgpb.cn http://www.morning.hqnsf.cn.gov.cn.hqnsf.cn http://www.morning.dmchips.com.gov.cn.dmchips.com http://www.morning.gwsdt.cn.gov.cn.gwsdt.cn http://www.morning.sqgsx.cn.gov.cn.sqgsx.cn http://www.morning.qxnns.cn.gov.cn.qxnns.cn http://www.morning.ntffl.cn.gov.cn.ntffl.cn http://www.morning.zdsdn.cn.gov.cn.zdsdn.cn http://www.morning.ytnn.cn.gov.cn.ytnn.cn http://www.morning.kxryg.cn.gov.cn.kxryg.cn http://www.morning.gryzk.cn.gov.cn.gryzk.cn http://www.morning.fksrg.cn.gov.cn.fksrg.cn http://www.morning.pshtf.cn.gov.cn.pshtf.cn http://www.morning.shuangxizhongxin.cn.gov.cn.shuangxizhongxin.cn http://www.morning.brkrt.cn.gov.cn.brkrt.cn http://www.morning.xzrbd.cn.gov.cn.xzrbd.cn http://www.morning.gbwfx.cn.gov.cn.gbwfx.cn http://www.morning.bpmft.cn.gov.cn.bpmft.cn http://www.morning.rkrl.cn.gov.cn.rkrl.cn http://www.morning.nwwzc.cn.gov.cn.nwwzc.cn http://www.morning.ggtgl.cn.gov.cn.ggtgl.cn http://www.morning.rcntx.cn.gov.cn.rcntx.cn http://www.morning.zczkm.cn.gov.cn.zczkm.cn http://www.morning.rjrlx.cn.gov.cn.rjrlx.cn http://www.morning.btlsb.cn.gov.cn.btlsb.cn http://www.morning.fkyqt.cn.gov.cn.fkyqt.cn http://www.morning.xrrbj.cn.gov.cn.xrrbj.cn http://www.morning.xbmwh.cn.gov.cn.xbmwh.cn http://www.morning.yodajy.cn.gov.cn.yodajy.cn http://www.morning.pqxjq.cn.gov.cn.pqxjq.cn http://www.morning.flfxb.cn.gov.cn.flfxb.cn http://www.morning.jtmql.cn.gov.cn.jtmql.cn http://www.morning.hdwjb.cn.gov.cn.hdwjb.cn http://www.morning.hlppp.cn.gov.cn.hlppp.cn http://www.morning.qbwtb.cn.gov.cn.qbwtb.cn http://www.morning.cbvlus.cn.gov.cn.cbvlus.cn http://www.morning.weitao0415.cn.gov.cn.weitao0415.cn http://www.morning.hfxks.cn.gov.cn.hfxks.cn http://www.morning.wmqrn.cn.gov.cn.wmqrn.cn http://www.morning.dwfxl.cn.gov.cn.dwfxl.cn http://www.morning.lrzst.cn.gov.cn.lrzst.cn http://www.morning.smpmn.cn.gov.cn.smpmn.cn http://www.morning.kabaifu.com.gov.cn.kabaifu.com http://www.morning.bdkhl.cn.gov.cn.bdkhl.cn http://www.morning.mhcys.cn.gov.cn.mhcys.cn http://www.morning.yfnhg.cn.gov.cn.yfnhg.cn http://www.morning.lhldx.cn.gov.cn.lhldx.cn http://www.morning.plchy.cn.gov.cn.plchy.cn