Deep Learning With Python - Meap Edition
Deep Learning With Python - Meap Edition
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
Welcome
Thank you for purchasing the MEAP for Deep Learning with Python. If you are looking
for a resource to learn about deep learning from scratch and to quickly become able to use
this knowledge to solve real-world problems, you have found the right book. *Deep
Learning with Python* is meant for engineers and students with a reasonable amount of
Python experience, but no significant knowledge of machine learning and deep learning. It
will take you all the way from basic theory to advanced practical applications. However, if
you already have experience with deep learning, you should still be able to find value in
the latter chapters of this book.
Deep learning is an immensely rich subfield of machine learning, with powerful
applications ranging from machine perception to natural language processing, all the way up
to creative AI. Yet, its core concepts are in fact very simple. Deep learning is often
presented as shrouded in a certain mystique, with references to algorithms that “work like
the brain”, that “think” or “understand”. Reality is however quite far from this science-
fiction dream, and I will do my best in these pages to dispel these illusions. I believe that
there are no difficult ideas in deep learning, and that’s why I started this book, based on
premise that all of the important concepts and applications in this field could be taught to
anyone, with very few prerequisites.
This book is structured around a series of practical code examples, demonstrating on real-
world problems every the notions that gets introduced. I strongly believe in the value of
teaching using concrete examples, anchoring theoretical ideas into actual results and
tangible code patterns. These examples all rely on Keras, the Python deep learning library.
When I released the initial version of Keras almost two years ago, little did I know that it
would quickly skyrocket to become one of the most widely used deep learning frameworks.
A big part of that success is that Keras has always put ease of use and accessibility front and
center. This same reason is what makes Keras a great library to get started with deep
learning, and thus a great fit for this book. By the time you reach the end of this book, you
will have become a Keras expert.
I hope that you will this book valuable —deep learning will definitely open up new
intellectual perspectives for you, and in fact it even has the potential to transform your
career, being the most in-demand scientific specialization these days. I am looking forward
to your reviews and comments. Your feedback is essential in order to write the best possible
book, that will benefit the greatest number of people.
— François Chollet
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
brief contents
PART 1: THE FUNDAMENTALS OF DEEP LEARNING
1 What is Deep Learning?
2 Before we start: the mathematical building blocks of neural networks
3 Getting started with neural networks
4 Fundamentals of machine learning
PART 2: DEEP LEARNING IN PRACTICE
5 Deep learning for computer vision
6 Deep learning for text and sequences
7 Advanced deep learning best practices
8 Generative deep learning
9 Conclusions
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
1
Input data points. For instance, if the task is speech recognition, these data points could
be sound files of people speaking. If the task is image tagging, they could be picture files.
Examples of the expected output. In a speech recognition task, these could be
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
4
human-generated transcripts of our sound files. In an image task, expected outputs could
tags such as "dog", "cat", and so on.
A way to measure if the algorithm is doing a good job, to measure the distance between
its current output and its expected output. This is used as a feedback signal to adjust the
way the algorithm works. This adjustment step is what we call "learning".
A machine learning model transforms its input data into a meaningful output, a
process which is "learned" from exposure to known examples of inputs and outputs.
Therefore, the central problem in machine learning and deep learning is to meaningfully
transform data, or in other words, to learn useful "representations" of the input data at
hand, representations that get us closer to the expected output. Before we go any further:
what’s a representation? At its core, it’s a different way to look at your data—to
"represent", or "encode" your data. For instance, a color image can be encoded in the
RGB format ("red-green-blue") or in the HSV format ("hue-saturation-value"): these are
two different representations of the same data. Some tasks that may be difficult with one
representation can become easy with another. For example, the task "select all red pixels
in the image" is simpler in the RBG format, while "make the image less saturated" is
simpler in the HSV format. Machine learning models are all about finding appropriate
representations for their input data, transformations of the data that make it more
amenable to the task at hand, such as a classification task.
Let’s make this concrete. Let’s consider an x axis, and y axis, and some points
represented by their coordinates in the (x, y) system: our data, as illustrated in figure 3
1.3.
As you can see we have a few white points and a few black points. Let’s say we want
to develop an algorithm that could take the coordinates (x, y) of a point, and output
whether the point considered is likely to be black or to be white. In this case:
What we need here is a new representation of our data that cleanly separates the
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
5
white points from the black points. One transformation we could use, among many other
possibilities, would be a coordinate change, illustrated in figure 1.4.
In this new coordinate system, the coordinates of our points can be said to be a new
"representation" of our data. And it’s a good one! With this representation, the
black/white classification problem can be expressed as a simple rule: black points are
such that x 0 or "white points are such that x < 0". Our new representation basically
solves the classification problem.
In this case, we defined our coordinate change by hand. But if instead we tried
systematically searching for different possible coordinate changes, and used as feedback
the percentage of points being correctly classified, then we would be doing machine
learning. "Learning", in the context of machine learning, describes an automatic search
process for better representations.
All machine learning algorithms consist of automatically finding such
transformations that turn data into more useful representations for a given task. These
operations could sometimes be coordinate changes, as we just saw, or could be linear
projections (which may destroy information), translations, non-linear operations (such as
select all points such that x 0), etc. Machine learning algorithms are not usually very
creative in finding these transformations, they are merely searching through a predefined
set of operations, called an "hypothesis space".
So that’s what machine learning is, technically: searching for useful representations
of some input data, within a pre-defined space of possibilities, using guidance from some
feedback signal. This simple idea allows for solving a remarkably broad range of
intellectual tasks, from speech recognition to autonomous car driving.
Now that you understand what we mean by learning, let’s take a look at what makes
deep learning special.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
6
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
7
What do the representations learned by a deep learning algorithm look like? Let’s
look at how a 3-layer deep network transforms an image of a digit in order to recognize
what digit it is:
As you can see, the network transforms the digit image into representations that are
increasingly different from the original image, and increasingly informative about the
final result. You can think of a deep network as a multi-stage information distillation
operation, where information goes through successive filters and comes out increasingly
"purified" (i.e. useful with regard to some task).
So that is what deep learning is, technically: a multi-stage way to learn data
representations. A simple idea—but as it turns out, very simple mechanisms, sufficiently
scaled, can end up looking like magic.
correct value for all of them may seem like a daunting task, especially since modifying
the value of one parameter will affect the behavior of all others!
To control something, first, you need to be able to observe it. To control the output of
a neural network, you need to be able to measure how far this output is from what you
expected. This is the job of the "loss function" of the network, also called "objective
function". The loss function takes the predictions of the network and the true target (what
you wanted the network to output), and computes a distance score, capturing how well
the network has done on this specific example.
Figure 1.8 A loss function measures the quality of the network’s output
The fundamental trick in deep learning is to use this score as a feedback signal to
adjust the value of the weights by a little bit, in a direction that would lower the loss
score for the current example. This adjustment is the job of the "optimizer", which
implements what is called the "backpropagation" algorithm, the central algorithm in deep
learning. In the next chapter we will explain in more detail how backpropagation works.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
9
Figure 1.9 The loss score is used as a feedback signal to adjust the weights
Initially, the weights of the network are assigned random values, so the network
merely implements a series of random transformations --naturally its output is very far
from what it should ideally be, and the loss score is accordingly very high. But with
every example that the network processes, the weights get adjusted just a little in the right
direction, and the loss score decreases. This is the "training loop", which, repeated a
sufficient number of times (typically tens of iterations overs thousands of examples),
yields weight values that minimize the loss function. A network with a minimal loss is
one for which the outputs are as close as they can be to the targets: a trained network.
Once again: a very simple mechanism, which once scaled ends up looking like magic.
In fact, we are still just exploring the full extent of what deep learning can do. We
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
10
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
11
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
12
Hardware.
Datasets and benchmarks.
Algorithmic advances.
1.2.1 Hardware
Between 1990 and 2010, off-the shelf CPUs have gotten faster by a factor of
approximately 5,000. As a result, nowadays it’s possible to run small deep learning
models on your laptop, whereas this would have been intractable 25 years ago.
However, typical deep learning models used in computer vision or speech recognition
require orders of magnitude more computational power than what your laptop can
deliver. Throughout the 2000s, companies like NVIDIA and AMD have been investing
billions of dollars into developing fast, massively parallel chips (graphical processing
units, GPUs) for powering the graphics of increasingly photorealistic video games.
Cheap, single-purpose supercomputers designed to render complex 3D scenes on your
screen, in real-time. This investment came to benefit the scientific community when, in
2007, NVIDIA launched CUDA, a programming interface for its line of GPUs. A small
number of GPUs started replacing massive clusters of CPUs in a number of various
highly-parallelizable applications, starting with physics modeling. Deep neural networks,
consisting mostly of many small matrix multiplications, are also highly parallelizable,
and around 2011, some researchers started writing CUDA implementations of neural
nets—Dan Ciresan and Alex Krizhevsky were some of the first among them.
So what happened is that the gaming market has subsidized supercomputing for the
next generation of artificial intelligence applications. Sometimes, big things start as
games. Today, the NVIDIA Titan X, a gaming GPU that cost $1000 at the end of 2015,
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
13
can deliver a peak of 6.6 TLOPS in single-precision, i.e. 6.6 trillion of float32
operations per second. That’s about 350 times more than what you can get out of a
modern laptop. On a Titan X, it only takes a couple of days to train an ImageNet model
of the sort that would have won the competition a few years ago. Meanwhile, large
companies train deep learning models on clusters of hundreds of GPUs of a type
developed specifically for the needs of deep learning, such as the NVIDIA K80. The
sheer computational power of such clusters is something that would never have been
possible without modern GPUs.
What’s more, the deep learning industry is even starting to go beyond GPUs, and is
investing into increasingly specialized and efficient chips for deep learning. In 2016, at
its annual I/O convention, Google revealed its "TPU" project (tensor processing unit), a
new chip design developed from the ground-up to run deep neural networks, reportedly
10x faster and far more energy-efficient than top-of-line GPUs.
1.2.2 Data
Artificial Intelligence is sometimes heralded as the new industrial revolution. If deep
learning is the steam engine of this revolution, then data is its coal. The raw material that
powers our intelligent machines, without which nothing would be possible. When it
comes to data, besides the exponential progress in storage hardware over the past twenty
years, following Moore’s law, the game-changer has been the rise of the Internet, making
it feasible to collect and distribute very large datasets for machine learning. Today, large
companies work with image datasets, video datasets, and natural language datasets that
could not have been collected without the Internet. User-generated image tags on Flickr,
for instance, have been a treasure trove of data for computer vision. So were YouTube
videos. And Wikipedia is a key dataset for natural language processing.
If there is one dataset that has been a catalyst for the rise of deep learning, it is the
ImageNet dataset, consisting in 1.4 million images hand-annotated with 1000 images
categories (one category per image). But what makes ImageNet special is not just its
large size, but also the yearly competition associated with it. As [Link] as been
demonstrating since 2010, public competitions are an excellent way to motivate
researchers and engineers to push the envelope. Having common benchmarks that
researchers compete to beat has greatly helped the recent rise of deep learning.
1.2.3 Algorithms
Besides hardware and data, up until the late 2000s, we were still missing a reliable way to
train very deep neural networks. As a result, neural networks were still fairly shallow,
leveraging only one or two layers of representations, and so they were not able to shine
against more refined shallow methods such as SVMs or Random Forests. The key issue
was that of "gradient propagation" through deep stacks of layers. The feedback signal
used to train neural networks would fade away as the number of layers increased.
This changed around 2009-2010 with the development of several simple but
important algorithmic improvements that allowed for better gradient propagation:
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
14
It is only when these improvements started allowing for training models with ten or
more layers that deep learning really started to shine.
Finally, in 2014, 2015 and 2016, even more advanced ways to help gradient
propagation were discovered, such as batch normalization, residual connections, and
depthwise separable convolutions. Today we can train from scratch models that are
thousands of layers deep.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
15
Simplicity. Deep learning removes the need for feature engineering, replacing complex,
brittle and engineering-heavy pipelines with simple end-to-end trainable models typically
built using only 5 or 6 different tensor operations.
Scalability. Deep learning is highly amenable to parallelization on GPUs or TPUs,
making it capable of taking full advantage of Moore’s law. Besides, deep learning models
are trained by iterating over small batches of data, allowing them to be trained on datasets
of arbitrary size (the only bottleneck being the amount of parallel computational power
available, which thanks to Moore’s law is a fast-moving barrier).
Versatility and reusability. Contrarily to many prior machine learning approaches, deep
learning models can be trained on additional data without restarting from scratch, making
them viable for continuous online learning, an important property for very large
production models. Furthermore, trained deep learning models are repurposable and thus
reusable: for instance it is possible to take a deep learning model trained for image
classification and drop it into a video processing pipeline. This allows us to reinvest
previous work into increasingly complex and powerful models. This also makes deep
learning applicable to fairly small datasets.
Deep learning has only been in the spotlight for a few years, and we haven’t yet
established the full scope of what it can do. Every passing month we still come up with
new use cases, or with engineering improvements lifting previously known limitations.
Following a scientific revolution, progress generally follows a sigmoid curve: it starts
with a period of fast progress than gradually stabilizes, as researchers start hitting against
hard limitations and further improvements become more incremental. With deep learning
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]
16
in 2017, it seems that we are still in the first half of that sigmoid, and there is a lot more
progress yet to come in the next few years.
©Manning Publications Co. We welcome reader comments about anything in the manuscript - other than typos and
other simple mistakes. These will be cleaned up during production of the book by copyeditors and proofreaders.
[Link]