Guide to Keras Basics

Keras is a high-level API to build and train deep learning models. It’s used for fast prototyping, advanced research, and production, with three key advantages:

Import keras

To get started, load the keras library:

library(keras)

Build a simple model

Sequential model

In Keras, you assemble layers to build models. A model is (usually) a graph of layers. The most common type of model is a stack of layers: the sequential model.

To build a simple, fully-connected network (i.e., a multi-layer perceptron):

Configure the layers

There are many layers available with some common constructor parameters:

The following instantiates dense layers using constructor arguments:

Train and evaluate

Set up training

After the model is constructed, configure its learning process by calling the compile method:

compile takes three important arguments:

The following shows a few examples of configuring a model for training:

Input data

You can train keras models directly on R matrices and arrays (possibly created from R data.frames). A model is fit to the training data using the fit method:

fit takes three important arguments:

Here’s an example using validation_data:

Evaluate and predict

Same as fit, the evaluate and predict methods can use raw R data as well as a dataset.

To evaluate the inference-mode loss and metrics for the data provided:

And to predict the output of the last layer in inference for the data provided, again as R data as well as a dataset:

Build advanced models

Functional API

The sequential model is a simple stack of layers that cannot represent arbitrary models. Use the Keras functional API to build complex model topologies such as:

Building a model with the functional API works like this:

  1. A layer instance is callable and returns a tensor.
  2. Input tensors and output tensors are used to define a keras_model instance.
  3. This model is trained just like the sequential model.

The following example uses the functional API to build a simple, fully-connected network:

Custom layers

To create a custom Keras layer, you create an R6 class derived from KerasLayer. There are three methods to implement (only one of which, call(), is required for all types of layer):

Here is an example custom layer that performs a matrix multiplication:

In order to use the custom layer within a Keras model you also need to create a wrapper function which instantiates the layer using the create_layer() function. For example:

You can now use the layer in a model as usual:

Custom models

In addition to creating custom layers, you can also create a custom model. This might be necessary if you wanted to use TensorFlow eager execution in combination with an imperatively written forward pass.

In cases where this is not needed, but flexibility in building the architecture is required, it is recommended to just stick with the functional API.

A custom model is defined by calling keras_model_custom() passing a function that specifies the layers to be created and the operations to be executed on forward pass.

Callbacks

A callback is an object passed to a model to customize and extend its behavior during training. You can write your own custom callback, or use the built-in callbacks that include:

To use a callback, pass it to the model’s fit method:

callbacks <- list(
  callback_early_stopping(patience = 2, monitor = 'val_loss'),
  callback_tensorboard(log_dir = './logs')
)

model %>% fit(
  data,
  labels,
  batch_size = 32,
  epochs = 5,
  callbacks = callbacks,
  validation_data = list(val_data, val_labels)
)

Save and restore

Weights only

Save and load the weights of a model using save_model_weights_hdf5 and load_model_weights_hdf5, respectively:

Configuration only

A model’s configuration can be saved - this serializes the model architecture without any weights. A saved configuration can recreate and initialize the same model, even without the code that defined the original model. Keras supports JSON and YAML serialization formats:

Caution: Custom models are not serializable because their architecture is defined by the R code in the function passed to keras_model_custom.

Entire model

The entire model can be saved to a file that contains the weight values, the model’s configuration, and even the optimizer’s configuration. This allows you to checkpoint a model and resume training later —from the exact same state —without access to the original code.