电商开放平台,湖南企业竞价优化,南宁百度快速优化,义乌网站建设多少钱大白话讲解卷积神经网络工作原理#xff0c;推荐一个bilibili的讲卷积神经网络的视频#xff0c;up主从youtube搬运过来#xff0c;用中文讲了一遍。
这篇文章是 TensorFlow 2.0 Tutorial 入门教程的第五篇文章#xff0c;介绍如何使用卷积神经网络#xff08;Convolutio… 大白话讲解卷积神经网络工作原理推荐一个bilibili的讲卷积神经网络的视频up主从youtube搬运过来用中文讲了一遍。
这篇文章是 TensorFlow 2.0 Tutorial 入门教程的第五篇文章介绍如何使用卷积神经网络Convolutional Neural Network, CNN来提高mnist手写数字识别的准确性。之前使用了最简单的784x10的神经网络达到了 0.91 的正确性而这篇文章在使用了卷积神经网络后正确性达到了0.99
卷积神经网络Convolutional Neural Network, CNN是一种前馈神经网络它的人工神经元可以响应一部分覆盖范围内的周围单元对于大型图像处理有出色表现。
卷积神经网络由一个或多个卷积层和顶端的全连通层对应经典的神经网络组成同时也包括关联权重和池化层pooling layer。这一结构使得卷积神经网络能够利用输入数据的二维结构。与其他深度学习结构相比卷积神经网络在图像和语音识别方面能够给出更好的结果。这一模型也可以使用反向传播算法进行训练。相比较其他深度、前馈神经网络卷积神经网络需要考量的参数更少使之成为一种颇具吸引力的深度学习结构。
——维基百科
1. 安装TensorFlow 2.0
Google与2019年3月发布了TensorFlow 2.0TensorFlow 2.0 清理了废弃的API通过减少重复来简化API并且通过Keras能够轻松地构建模型从这篇文章开始教程示例采用TensorFlow 2.0版本。 1 pip install tensorflow2.0.0-beta0
或者在这里下载whl包安装Links for tensorflow
2. 代码目录结构 12345678910111213 data_set_tf2/ # TensorFlow 2.0的mnist数据集 |--mnist.npz test_images/ # 预测所用的图片 |--0.png |--1.png |--4.pngv4_cnn/ |--ckpt/ # 模型保存的位置 |--checkpoint |--cp-0005.ckpt.data-00000-of-00001 |--cp-0005.ckpt.index |--predict.py # 预测代码 |--train.py # 训练代码
3. CNN模型代码train.py
模型定义的前半部分主要使用Keras.layers提供的Conv2D卷积与MaxPooling2D池化函数。
CNN的输入是维度为 (image_height, image_width, color_channels)的张量mnist数据集是黑白的因此只有一个color_channel颜色通道一般的彩色图片有3个R,G,B,熟悉Web前端的同学可能知道有些图片有4个通道(R,G,B,A)A代表透明度。对于mnist数据集输入的张量维度就是(28,28,1)通过参数input_shape传给网络的第一层。 123456789101112131415161718192021222324 import osimport tensorflow as tffrom tensorflow.keras import datasets, layers, modelsclass CNN(object): def __init__(self): model models.Sequential() # 第1层卷积卷积核大小为3*332个28*28为待训练图片的大小 model.add(layers.Conv2D(32, (3, 3), activationrelu, input_shape(28, 28, 1))) model.add(layers.MaxPooling2D((2, 2))) # 第2层卷积卷积核大小为3*364个 model.add(layers.Conv2D(64, (3, 3), activationrelu)) model.add(layers.MaxPooling2D((2, 2))) # 第3层卷积卷积核大小为3*364个 model.add(layers.Conv2D(64, (3, 3), activationrelu)) model.add(layers.Flatten()) model.add(layers.Dense(64, activationrelu)) model.add(layers.Dense(10, activationsoftmax)) model.summary() self.model model
model.summary()用来打印我们定义的模型的结构。 123456789101112131415161718192021222324 Model: sequential_________________________________________________________________Layer (type) Output Shape Param # conv2d (Conv2D) (None, 26, 26, 32) 320 _________________________________________________________________max_pooling2d (MaxPooling2D) (None, 13, 13, 32) 0 _________________________________________________________________conv2d_1 (Conv2D) (None, 11, 11, 64) 18496 _________________________________________________________________max_pooling2d_1 (MaxPooling2 (None, 5, 5, 64) 0 _________________________________________________________________conv2d_2 (Conv2D) (None, 3, 3, 64) 36928 _________________________________________________________________flatten (Flatten) (None, 576) 0 _________________________________________________________________dense (Dense) (None, 64) 36928 _________________________________________________________________dense_1 (Dense) (None, 10) 650 Total params: 93,322Trainable params: 93,322Non-trainable params: 0_________________________________________________________________
我们可以看到每一个Conv2D和MaxPooling2D层的输出都是一个三维的张量(height, width, channels)。height和width会逐渐地变小。输出的channel的个数是由第一个参数(例如32或64)控制的随着height和width的变小channel可以变大从算力的角度。
模型的后半部分是定义输出张量的。layers.Flatten会将三维的张量转为一维的向量。展开前张量的维度是(3, 3, 64) 转为一维(576)的向量后紧接着使用layers.Dense层构造了2层全连接层逐步地将一维向量的位数从576变为64再变为10。
后半部分相当于是构建了一个隐藏层为64输入层为576输出层为10的普通的神经网络。最后一层的激活函数是softmax10位恰好可以表达0-9十个数字。
最大值的下标即可代表对应的数字使用numpy很容易计算出来 123456 import numpy as npy1 [0, 0.8, 0.1, 0.1, 0, 0, 0, 0, 0, 0]y2 [0, 0.1, 0.1, 0.1, 0.5, 0, 0.2, 0, 0, 0]np.argmax(y1) # 1np.argmax(y2) # 4
4. mnist数据集预处理train.py 12345678910111213 class DataSource(object): def __init__(self): # mnist数据集存储的位置如何不存在将自动下载 data_path os.path.abspath(os.path.dirname(__file__)) /../data_set_tf2/mnist.npz (train_images, train_labels), (test_images, test_labels) datasets.mnist.load_data(pathdata_path) # 6万张训练图片1万张测试图片 train_images train_images.reshape((60000, 28, 28, 1)) test_images test_images.reshape((10000, 28, 28, 1)) # 像素值映射到 0 - 1 之间 train_images, test_images train_images / 255.0, test_images / 255.0 self.train_images, self.train_labels train_images, train_labels self.test_images, self.test_labels test_images, test_labels
5. 开始训练并保存训练结果train.py 12345678910111213141516171819202122 class Train: def __init__(self): self.cnn CNN() self.data DataSource() def train(self): check_path ./ckpt/cp-{epoch:04d}.ckpt # period 每隔5epoch保存一次 save_model_cb tf.keras.callbacks.ModelCheckpoint(check_path, save_weights_onlyTrue, verbose1, period5) self.cnn.model.compile(optimizeradam, losssparse_categorical_crossentropy, metrics[accuracy]) self.cnn.model.fit(self.data.train_images, self.data.train_labels, epochs5, callbacks[save_model_cb]) test_loss, test_acc self.cnn.model.evaluate(self.data.test_images, self.data.test_labels) print(准确率: %.4f共测试了%d张图片 % (test_acc, len(self.data.test_labels)))if __name__ __main__: app Train() app.train()
在执行python train.py后会得到以下的结果 123456789101112131415 Train on 60000 samplesEpoch 1/560000/60000 [] - 45s 749us/sample - loss: 0.1477 - accuracy: 0.9536Epoch 2/560000/60000 [] - 45s 746us/sample - loss: 0.0461 - accuracy: 0.9860Epoch 3/560000/60000 [] - 50s 828us/sample - loss: 0.0336 - accuracy: 0.9893Epoch 4/560000/60000 [] - 50s 828us/sample - loss: 0.0257 - accuracy: 0.9919Epoch 5/559968/60000 [.] - ETA: 0s - loss: 0.0210 - accuracy: 0.9930Epoch 00005: saving model to ./ckpt/cp-0005.ckpt60000/60000 [] - 51s 848us/sample - loss: 0.0210 - accuracy: 0.993010000/10000 [] - 3s 290us/sample - loss: 0.0331 - accuracy: 0.9901准确率: 0.9901共测试了10000张图片
可以看到在第一轮训练后识别准确率达到了0.95365轮之后使用测试集验证准确率达到了0.9901
在第五轮时模型参数成功保存在了./ckpt/cp-0005.ckpt。接下来我们就可以加载保存的模型参数恢复整个卷积神经网络进行真实图片的预测了。
6. 图片预测predict.py
为了将模型的训练和加载分开预测的代码写在了predict.py中。 12345678910111213141516171819202122232425262728293031323334353637383940 import tensorflow as tffrom PIL import Imageimport numpy as npfrom train import CNNpython 3.7tensorflow 2.0.0b0pillow(PIL) 4.3.0class Predict(object): def __init__(self): latest tf.train.latest_checkpoint(./ckpt) self.cnn CNN() # 恢复网络权重 self.cnn.model.load_weights(latest) def predict(self, image_path): # 以黑白方式读取图片 img Image.open(image_path).convert(L) img np.reshape(img, (28, 28, 1)) / 255. x np.array([1 - img]) # API refer: https://keras.io/models/model/ y self.cnn.model.predict(x) # 因为x只传入了一张图片取y[0]即可 # np.argmax()取得最大值的下标即代表的数字 print(image_path) print(y[0]) print( - Predict digit, np.argmax(y[0]))if __name__ __main__: app Predict() app.predict(../test_images/0.png) app.predict(../test_images/1.png) app.predict(../test_images/4.png)
最终执行predict.py可以看到 12345678910 $ python predict.py../test_images/0.png[1. 0. 0. 0. 0. 0. 0. 0. 0. 0.] - Predict digit 0../test_images/1.png[0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] - Predict digit 1../test_images/4.png[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.] - Predict digit 4
任何程序错误以及技术疑问或需要解答的请添加