Path: blob/master/guides/ipynb/training_with_built_in_methods.ipynb
3283 views
Training & evaluation with the built-in methods
Author: fchollet
Date created: 2019/03/01
Last modified: 2023/06/25
Description: Complete guide to training & evaluation with fit()
and evaluate()
.
Setup
Introduction
This guide covers training, evaluation, and prediction (inference) models when using built-in APIs for training & validation (such as Model.fit()
, Model.evaluate()
and Model.predict()
).
If you are interested in leveraging fit()
while specifying your own training step function, see the guides on customizing what happens in fit()
:
If you are interested in writing your own training & evaluation loops from scratch, see the guides on writing training loops:
In general, whether you are using built-in loops or writing your own, model training & evaluation works strictly in the same way across every kind of Keras model -- Sequential models, models built with the Functional API, and models written from scratch via model subclassing.
API overview: a first end-to-end example
When passing data to the built-in training loops of a model, you should either use:
NumPy arrays (if your data is small and fits in memory)
Subclasses of
keras.utils.PyDataset
tf.data.Dataset
objectsPyTorch
DataLoader
instances
In the next few paragraphs, we'll use the MNIST dataset as NumPy arrays, in order to demonstrate how to use optimizers, losses, and metrics. Afterwards, we'll take a close look at each of the other options.
Let's consider the following model (here, we build in with the Functional API, but it could be a Sequential model or a subclassed model as well):
Here's what the typical end-to-end workflow looks like, consisting of:
Training
Validation on a holdout set generated from the original training data
Evaluation on the test data
We'll use MNIST data for this example.
We specify the training configuration (optimizer, loss, metrics):
We call fit()
, which will train the model by slicing the data into "batches" of size batch_size
, and repeatedly iterating over the entire dataset for a given number of epochs
.
The returned history
object holds a record of the loss values and metric values during training:
We evaluate the model on the test data via evaluate()
:
Now, let's review each piece of this workflow in detail.
The compile()
method: specifying a loss, metrics, and an optimizer
To train a model with fit()
, you need to specify a loss function, an optimizer, and optionally, some metrics to monitor.
You pass these to the model as arguments to the compile()
method:
The metrics
argument should be a list -- your model can have any number of metrics.
If your model has multiple outputs, you can specify different losses and metrics for each output, and you can modulate the contribution of each output to the total loss of the model. You will find more details about this in the Passing data to multi-input, multi-output models section.
Note that if you're satisfied with the default settings, in many cases the optimizer, loss, and metrics can be specified via string identifiers as a shortcut:
For later reuse, let's put our model definition and compile step in functions; we will call them several times across different examples in this guide.
Many built-in optimizers, losses, and metrics are available
In general, you won't have to create your own losses, metrics, or optimizers from scratch, because what you need is likely to be already part of the Keras API:
Optimizers:
SGD()
(with or without momentum)RMSprop()
Adam()
etc.
Losses:
MeanSquaredError()
KLDivergence()
CosineSimilarity()
etc.
Metrics:
AUC()
Precision()
Recall()
etc.
Custom losses
If you need to create a custom loss, Keras provides three ways to do so.
The first method involves creating a function that accepts inputs y_true
and y_pred
. The following example shows a loss function that computes the mean squared error between the real data and the predictions:
If you need a loss function that takes in parameters beside y_true
and y_pred
, you can subclass the keras.losses.Loss
class and implement the following two methods:
__init__(self)
: accept parameters to pass during the call of your loss functioncall(self, y_true, y_pred)
: use the targets (y_true) and the model predictions (y_pred) to compute the model's loss
Let's say you want to use mean squared error, but with an added term that will de-incentivize prediction values far from 0.5 (we assume that the categorical targets are one-hot encoded and take values between 0 and 1). This creates an incentive for the model not to be too confident, which may help reduce overfitting (we won't know if it works until we try!).
Here's how you would do it:
Custom metrics
If you need a metric that isn't part of the API, you can easily create custom metrics by subclassing the keras.metrics.Metric
class. You will need to implement 4 methods:
__init__(self)
, in which you will create state variables for your metric.update_state(self, y_true, y_pred, sample_weight=None)
, which uses the targets y_true and the model predictions y_pred to update the state variables.result(self)
, which uses the state variables to compute the final results.reset_state(self)
, which reinitializes the state of the metric.
State update and results computation are kept separate (in update_state()
and result()
, respectively) because in some cases, the results computation might be very expensive and would only be done periodically.
Here's a simple example showing how to implement a CategoricalTruePositives
metric that counts how many samples were correctly classified as belonging to a given class:
Handling losses and metrics that don't fit the standard signature
The overwhelming majority of losses and metrics can be computed from y_true
and y_pred
, where y_pred
is an output of your model -- but not all of them. For instance, a regularization loss may only require the activation of a layer (there are no targets in this case), and this activation may not be a model output.
In such cases, you can call self.add_loss(loss_value)
from inside the call method of a custom layer. Losses added in this way get added to the "main" loss during training (the one passed to compile()
). Here's a simple example that adds activity regularization (note that activity regularization is built-in in all Keras layers -- this layer is just for the sake of providing a concrete example):
Note that when you pass losses via add_loss()
, it becomes possible to call compile()
without a loss function, since the model already has a loss to minimize.
Consider the following LogisticEndpoint
layer: it takes as inputs targets & logits, and it tracks a crossentropy loss via add_loss()
.
You can use it in a model with two inputs (input data & targets), compiled without a loss
argument, like this:
For more information about training multi-input models, see the section Passing data to multi-input, multi-output models.
Automatically setting apart a validation holdout set
In the first end-to-end example you saw, we used the validation_data
argument to pass a tuple of NumPy arrays (x_val, y_val)
to the model for evaluating a validation loss and validation metrics at the end of each epoch.
Here's another option: the argument validation_split
allows you to automatically reserve part of your training data for validation. The argument value represents the fraction of the data to be reserved for validation, so it should be set to a number higher than 0 and lower than 1. For instance, validation_split=0.2
means "use 20% of the data for validation", and validation_split=0.6
means "use 60% of the data for validation".
The way the validation is computed is by taking the last x% samples of the arrays received by the fit()
call, before any shuffling.
Note that you can only use validation_split
when training with NumPy data.
Training & evaluation using tf.data
Datasets
In the past few paragraphs, you've seen how to handle losses, metrics, and optimizers, and you've seen how to use the validation_data
and validation_split
arguments in fit()
, when your data is passed as NumPy arrays.
Another option is to use an iterator-like, such as a tf.data.Dataset
, a PyTorch DataLoader
, or a Keras PyDataset
. Let's take look at the former.
The tf.data
API is a set of utilities in TensorFlow 2.0 for loading and preprocessing data in a way that's fast and scalable. For a complete guide about creating Datasets
, see the tf.data documentation.
You can use tf.data
to train your Keras models regardless of the backend you're using -- whether it's JAX, PyTorch, or TensorFlow. You can pass a Dataset
instance directly to the methods fit()
, evaluate()
, and predict()
:
Note that the Dataset is reset at the end of each epoch, so it can be reused of the next epoch.
If you want to run training only on a specific number of batches from this Dataset, you can pass the steps_per_epoch
argument, which specifies how many training steps the model should run using this Dataset before moving on to the next epoch.
You can also pass a Dataset
instance as the validation_data
argument in fit()
:
At the end of each epoch, the model will iterate over the validation dataset and compute the validation loss and validation metrics.
If you want to run validation only on a specific number of batches from this dataset, you can pass the validation_steps
argument, which specifies how many validation steps the model should run with the validation dataset before interrupting validation and moving on to the next epoch:
Note that the validation dataset will be reset after each use (so that you will always be evaluating on the same samples from epoch to epoch).
The argument validation_split
(generating a holdout set from the training data) is not supported when training from Dataset
objects, since this feature requires the ability to index the samples of the datasets, which is not possible in general with the Dataset
API.
Training & evaluation using PyDataset
instances
keras.utils.PyDataset
is a utility that you can subclass to obtain a Python generator with two important properties:
It works well with multiprocessing.
It can be shuffled (e.g. when passing
shuffle=True
infit()
).
A PyDataset
must implement two methods:
__getitem__
__len__
The method __getitem__
should return a complete batch. If you want to modify your dataset between epochs, you may implement on_epoch_end
.
Here's a quick example:
To fit the model, pass the dataset instead as the x
argument (no need for a y
argument since the dataset includes the targets), and pass the validation dataset as the validation_data
argument. And no need for the batch_size
argument, since the dataset is already batched!
Evaluating the model is just as easy:
Importantly, PyDataset
objects support three common constructor arguments that handle the parallel processing configuration:
workers
: Number of workers to use in multithreading or multiprocessing. Typically, you'd set it to the number of cores on your CPU.use_multiprocessing
: Whether to use Python multiprocessing for parallelism. Setting this toTrue
means that your dataset will be replicated in multiple forked processes. This is necessary to gain compute-level (rather than I/O level) benefits from parallelism. However it can only be set toTrue
if your dataset can be safely pickled.max_queue_size
: Maximum number of batches to keep in the queue when iterating over the dataset in a multithreaded or multipricessed setting. You can reduce this value to reduce the CPU memory consumption of your dataset. It defaults to 10.
By default, multiprocessing is disabled (use_multiprocessing=False
) and only one thread is used. You should make sure to only turn on use_multiprocessing
if your code is running inside a Python if __name__ == "__main__":
block in order to avoid issues.
Here's a 4-thread, non-multiprocessed example:
Training & evaluation using PyTorch DataLoader
objects
All built-in training and evaluation APIs are also compatible with torch.utils.data.Dataset
and torch.utils.data.DataLoader
objects -- regardless of whether you're using the PyTorch backend, or the JAX or TensorFlow backends. Let's take a look at a simple example.
Unlike PyDataset
which are batch-centric, PyTorch Dataset
objects are sample-centric: the __len__
method returns the number of samples, and the __getitem__
method returns a specific sample.
To use a PyTorch Dataset, you need to wrap it into a Dataloader
which takes care of batching and shuffling:
Now you can use them in the Keras API just like any other iterator:
Using sample weighting and class weighting
With the default settings the weight of a sample is decided by its frequency in the dataset. There are two methods to weight the data, independent of sample frequency:
Class weights
Sample weights
Class weights
This is set by passing a dictionary to the class_weight
argument to Model.fit()
. This dictionary maps class indices to the weight that should be used for samples belonging to this class.
This can be used to balance classes without resampling, or to train a model that gives more importance to a particular class.
For instance, if class "0" is half as represented as class "1" in your data, you could use Model.fit(..., class_weight={0: 1., 1: 0.5})
.
Here's a NumPy example where we use class weights or sample weights to give more importance to the correct classification of class #5 (which is the digit "5" in the MNIST dataset).
Sample weights
For fine grained control, or if you are not building a classifier, you can use "sample weights".
When training from NumPy data: Pass the
sample_weight
argument toModel.fit()
.When training from
tf.data
or any other sort of iterator: Yield(input_batch, label_batch, sample_weight_batch)
tuples.
A "sample weights" array is an array of numbers that specify how much weight each sample in a batch should have in computing the total loss. It is commonly used in imbalanced classification problems (the idea being to give more weight to rarely-seen classes).
When the weights used are ones and zeros, the array can be used as a mask for the loss function (entirely discarding the contribution of certain samples to the total loss).
Here's a matching Dataset
example:
Passing data to multi-input, multi-output models
In the previous examples, we were considering a model with a single input (a tensor of shape (764,)
) and a single output (a prediction tensor of shape (10,)
). But what about models that have multiple inputs or outputs?
Consider the following model, which has an image input of shape (32, 32, 3)
(that's (height, width, channels)
) and a time series input of shape (None, 10)
(that's (timesteps, features)
). Our model will have two outputs computed from the combination of these inputs: a "score" (of shape (1,)
) and a probability distribution over five classes (of shape (5,)
).
Let's plot this model, so you can clearly see what we're doing here (note that the shapes shown in the plot are batch shapes, rather than per-sample shapes).
At compilation time, we can specify different losses to different outputs, by passing the loss functions as a list:
If we only passed a single loss function to the model, the same loss function would be applied to every output (which is not appropriate here).
Likewise for metrics:
Since we gave names to our output layers, we could also specify per-output losses and metrics via a dict:
We recommend the use of explicit names and dicts if you have more than 2 outputs.
It's possible to give different weights to different output-specific losses (for instance, one might wish to privilege the "score" loss in our example, by giving to 2x the importance of the class loss), using the loss_weights
argument:
You could also choose not to compute a loss for certain outputs, if these outputs are meant for prediction but not for training:
Passing data to a multi-input or multi-output model in fit()
works in a similar way as specifying a loss function in compile: you can pass lists of NumPy arrays (with 1:1 mapping to the outputs that received a loss function) or dicts mapping output names to NumPy arrays.
Here's the Dataset
use case: similarly as what we did for NumPy arrays, the Dataset
should return a tuple of dicts.
Using callbacks
Callbacks in Keras are objects that are called at different points during training (at the start of an epoch, at the end of a batch, at the end of an epoch, etc.). They can be used to implement certain behaviors, such as:
Doing validation at different points during training (beyond the built-in per-epoch validation)
Checkpointing the model at regular intervals or when it exceeds a certain accuracy threshold
Changing the learning rate of the model when training seems to be plateauing
Doing fine-tuning of the top layers when training seems to be plateauing
Sending email or instant message notifications when training ends or where a certain performance threshold is exceeded
Etc.
Callbacks can be passed as a list to your call to fit()
:
Many built-in callbacks are available
There are many built-in callbacks already available in Keras, such as:
ModelCheckpoint
: Periodically save the model.EarlyStopping
: Stop training when training is no longer improving the validation metrics.TensorBoard
: periodically write model logs that can be visualized in TensorBoard (more details in the section "Visualization").CSVLogger
: streams loss and metrics data to a CSV file.etc.
See the callbacks documentation for the complete list.
Writing your own callback
You can create a custom callback by extending the base class keras.callbacks.Callback
. A callback has access to its associated model through the class property self.model
.
Make sure to read the complete guide to writing custom callbacks.
Here's a simple example saving a list of per-batch loss values during training:
Checkpointing models
When you're training model on relatively large datasets, it's crucial to save checkpoints of your model at frequent intervals.
The easiest way to achieve this is with the ModelCheckpoint
callback:
The ModelCheckpoint
callback can be used to implement fault-tolerance: the ability to restart training from the last saved state of the model in case training gets randomly interrupted. Here's a basic example:
You call also write your own callback for saving and restoring models.
For a complete guide on serialization and saving, see the guide to saving and serializing Models.
Using learning rate schedules
A common pattern when training deep learning models is to gradually reduce the learning as training progresses. This is generally known as "learning rate decay".
The learning decay schedule could be static (fixed in advance, as a function of the current epoch or the current batch index), or dynamic (responding to the current behavior of the model, in particular the validation loss).
Passing a schedule to an optimizer
You can easily use a static learning rate decay schedule by passing a schedule object as the learning_rate
argument in your optimizer:
Several built-in schedules are available: ExponentialDecay
, PiecewiseConstantDecay
, PolynomialDecay
, and InverseTimeDecay
.
Using callbacks to implement a dynamic learning rate schedule
A dynamic learning rate schedule (for instance, decreasing the learning rate when the validation loss is no longer improving) cannot be achieved with these schedule objects, since the optimizer does not have access to validation metrics.
However, callbacks do have access to all metrics, including validation metrics! You can thus achieve this pattern by using a callback that modifies the current learning rate on the optimizer. In fact, this is even built-in as the ReduceLROnPlateau
callback.
Visualizing loss and metrics during training with TensorBoard
The best way to keep an eye on your model during training is to use TensorBoard -- a browser-based application that you can run locally that provides you with:
Live plots of the loss and metrics for training and evaluation
(optionally) Visualizations of the histograms of your layer activations
(optionally) 3D visualizations of the embedding spaces learned by your
Embedding
layers
If you have installed TensorFlow with pip, you should be able to launch TensorBoard from the command line:
Using the TensorBoard callback
The easiest way to use TensorBoard with a Keras model and the fit()
method is the TensorBoard
callback.
In the simplest case, just specify where you want the callback to write logs, and you're good to go:
For more information, see the documentation for the TensorBoard
callback.