16.03.2021 Views

Advanced Deep Learning with Keras

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2

The Functional API is guided by the following two concepts:

• A layer is an instance that accepts a tensor as an argument. The output of

a layer is another tensor. To build a model, the layer instances are objects that

are chained to one another through both input and output tensors. This will

have similar end-result as would stacking multiple layers in the sequential

model have. However, using layer instances makes it easier for models to

have either auxiliary or multiple inputs and outputs since the input/output

of each layer will be readily accessible.

• A model is a function between one or more input tensors and output tensors.

In between the model input and output, tensors are the layer instances that

are chained to one another by layer input and output tensors. A model is,

therefore, a function of one or more input layers and one or more output

layers. The model instance formalizes the computational graph on how

the data flows from input(s) to output(s).

After you've completed building the functional API model, the training and

evaluation are then performed by the same functions used in the sequential

model. To illustrate, in a functional API, a 2D convolutional layer, Conv2D, with

32 filters and with x as the layer input tensor and y as the layer output tensor can

be written as:

y = Conv2D(32)(x)

We're also able to stack multiple layers to build our models. For example, we can

rewrite the CNN on MNIST code, the same code we created in the last chapter,

as shown in following listing:

You'll find Listing 2.1.1, cnn-functional-2.1.1.py, as follows. This shows us

how we can convert the cnn-mnist-1.4.1.py code using the functional API:

import numpy as np

from keras.layers import Dense, Dropout, Input

from keras.layers import Conv2D, MaxPooling2D, Flatten

from keras.models import Model

from keras.datasets import mnist

from keras.utils import to_categorical

# compute the number of labels

num_labels = len(np.unique(y_train))

# convert to one-hot vector

y_train = to_categorical(y_train)

y_test = to_categorical(y_test)

[ 41 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!