原文代码作者:François Chollet
github:https://github.com/fchollet/deep-learning-with-python-notebooks
中文注释制作:黄海广
github:https://github.com/fengdu78
代码全部测试通过。
配置环境:keras 2.2.1(原文是2.0.8,运行结果一致),tensorflow 1.8,python 3.6,
主机:显卡:一块1080ti;内存:32g(注:绝大部分代码不需要GPU)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M9ewzQwE-1608798675645)(data/gongzhong.jpg)]
import keras
keras.__version__
Using TensorFlow backend.
'2.2.1'
5.1 - Introduction to convnets
卷积神经网络简介
This notebook contains the code sample found in Chapter 5, Section 1 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments.
First, let’s take a practical look at a very simple convnet example. We will use our convnet to classify MNIST digits, a task that you’ve already been
through in Chapter 2, using a densely-connected network (our test accuracy then was 97.8%). Even though our convnet will be very basic, its
accuracy will still blow out of the water that of the densely-connected model from Chapter 2.
The 6 lines of code below show you what a basic convnet looks like. It’s a stack of Conv2D
and MaxPooling2D
layers. We’ll see in a
minute what they do concretely.
Importantly, a convnet takes as input tensors of shape (image_height, image_width, image_channels)
(not including the batch dimension).
In our case, we will configure our convnet to process inputs of size (28, 28, 1)
, which is the format of MNIST images. We do this via
passing the argument input_shape=(28, 28, 1)
to our first layer.
我们将深入讲解卷积神经网络的原理,以及它在计算机视觉任务上为什么如此成功。但在此之前,我们先来看一个简单的卷积神经网络示例,即使用卷积神经网络对 MNIST 数字进行分类,这个任务我们在第 2 章用密集连接网络做过(当时的测试精度为 97.8%)。虽然本例中的卷积神经网络很简单,但其精度肯定会超过第 2 章的密集连接网络。
下列代码将会展示一个简单的卷积神经网络。它是 Conv2D
层和MaxPooling2D
层的堆叠。 很快你就会知道这些层的作用。
重要的是,卷积神经网络接收形状为 (image_height, image_width, image_channels)
的输入张量(不包括批量维度)。本例中设置卷积神经网络处理大小为 (28, 28, 1)
的输入张量,这正是 MNIST 图像的格式。我们向第一层传入参数 input_shape=(28, 28, 1)
来完成此设置。
from keras import layers
from keras import models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=