Keras FAQ: Frequently Asked Keras Questions

How should I cite Keras?

Please cite Keras in your publications if it helps your research. Here is an example BibTeX entry:

  1. @misc{chollet2015keras,
  2. title={Keras},
  3. author={Chollet, Fran\c{c}ois and others},
  4. year={2015},
  5. howpublished={\url{https://keras.io}},
  6. }

How can I run Keras on GPU?

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

If you are running on the Theano backend, you can use one of the following methods:

Method 1: use Theano flags.

  1. THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py

The name 'gpu' might have to be changed depending on your device's identifier (e.g. gpu0, gpu1, etc).

Method 2: set up your .theanorc: Instructions

Method 3: manually set theano.config.device, theano.config.floatX at the beginning of your code:

  1. import theano
  2. theano.config.device = 'gpu'
  3. theano.config.floatX = 'float32'

How can I run a Keras model on multiple GPUs?

We recommend doing so using the TensorFlow backend. There are two ways to run a single model on multiple GPUs: data parallelism and device parallelism.

In most cases, what you need is most likely data parallelism.

Data parallelism

Data parallelism consists in replicating the target model once on each device, and using each replica to process a different fraction of the input data.Keras has a built-in utility, keras.utils.multi_gpu_model, which can produce a data-parallel version of any model, and achieves quasi-linear speedup on up to 8 GPUs.

For more information, see the documentation for multi_gpu_model. Here is a quick example:

  1. from keras.utils import multi_gpu_model
  2. # Replicates `model` on 8 GPUs.
  3. # This assumes that your machine has 8 available GPUs.
  4. parallel_model = multi_gpu_model(model, gpus=8)
  5. parallel_model.compile(loss='categorical_crossentropy',
  6. optimizer='rmsprop')
  7. # This `fit` call will be distributed on 8 GPUs.
  8. # Since the batch size is 256, each GPU will process 32 samples.
  9. parallel_model.fit(x, y, epochs=20, batch_size=256)

Device parallelism

Device parallelism consists in running different parts of a same model on different devices. It works best for models that have a parallel architecture, e.g. a model with two branches.

This can be achieved by using TensorFlow device scopes. Here is a quick example:

  1. # Model where a shared LSTM is used to encode two different sequences in parallel
  2. input_a = keras.Input(shape=(140, 256))
  3. input_b = keras.Input(shape=(140, 256))
  4. shared_lstm = keras.layers.LSTM(64)
  5. # Process the first sequence on one GPU
  6. with tf.device_scope('/gpu:0'):
  7. encoded_a = shared_lstm(tweet_a)
  8. # Process the next sequence on another GPU
  9. with tf.device_scope('/gpu:1'):
  10. encoded_b = shared_lstm(tweet_b)
  11. # Concatenate results on CPU
  12. with tf.device_scope('/cpu:0'):
  13. merged_vector = keras.layers.concatenate([encoded_a, encoded_b],
  14. axis=-1)

What does "sample", "batch", "epoch" mean?

Below are some common definitions that are necessary to know and understand to correctly utilize Keras:

  • Sample: one element of a dataset.
  • Example: one image is a sample in a convolutional network
  • Example: one audio file is a sample for a speech recognition model
  • Batch: a set of N samples. The samples in a batch are processed independently, in parallel. If training, a batch results in only one update to the model.
  • A batch generally approximates the distribution of the input data better than a single input. The larger the batch, the better the approximation; however, it is also true that the batch will take longer to process and will still result in only one update. For inference (evaluate/predict), it is recommended to pick a batch size that is as large as you can afford without going out of memory (since larger batches will usually result in faster evaluation/prediction).
  • Epoch: an arbitrary cutoff, generally defined as "one pass over the entire dataset", used to separate training into distinct phases, which is useful for logging and periodic evaluation.
  • When using validation_data or validation_split with the fit method of Keras models, evaluation will be run at the end of every epoch.
  • Within Keras, there is the ability to add callbacks specifically designed to be run at the end of an epoch. Examples of these are learning rate changes and model checkpointing (saving).

How can I save a Keras model?

Saving/loading whole models (architecture + weights + optimizer state)

It is not recommended to use pickle or cPickle to save a Keras model.

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model
  • the weights of the model
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

You can then use keras.models.load_model(filepath) to reinstantiate your model.load_model will also take care of compiling the model using the saved training configuration (unless the model was never compiled in the first place).

Example:

  1. from keras.models import load_model
  2. model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
  3. del model # deletes the existing model
  4. # returns a compiled model
  5. # identical to the previous one
  6. model = load_model('my_model.h5')

Please also see How can I install HDF5 or h5py to save my models in Keras? for instructions on how to install h5py.

Saving/loading only a model's architecture

If you only need to save the architecture of a model, and not its weights or its training configuration, you can do:

  1. # save as JSON
  2. json_string = model.to_json()
  3. # save as YAML
  4. yaml_string = model.to_yaml()

The generated JSON / YAML files are human-readable and can be manually edited if needed.

You can then build a fresh model from this data:

  1. # model reconstruction from JSON:
  2. from keras.models import model_from_json
  3. model = model_from_json(json_string)
  4. # model reconstruction from YAML:
  5. from keras.models import model_from_yaml
  6. model = model_from_yaml(yaml_string)

Saving/loading only a model's weights

If you need to save the weights of a model, you can do so in HDF5 with the code below:

  1. model.save_weights('my_model_weights.h5')

Assuming you have code for instantiating your model, you can then load the weights you saved into a model with the same architecture:

  1. model.load_weights('my_model_weights.h5')

If you need to load the weights into a different architecture (with some layers in common), for instance for fine-tuning or transfer-learning, you can load them by layer name:

  1. model.load_weights('my_model_weights.h5', by_name=True)

Example:

  1. """
  2. Assuming the original model looks like this:
  3. model = Sequential()
  4. model.add(Dense(2, input_dim=3, name='dense_1'))
  5. model.add(Dense(3, name='dense_2'))
  6. ...
  7. model.save_weights(fname)
  8. """
  9. # new model
  10. model = Sequential()
  11. model.add(Dense(2, input_dim=3, name='dense_1')) # will be loaded
  12. model.add(Dense(10, name='new_dense')) # will not be loaded
  13. # load weights from first model; will only affect the first layer, dense_1.
  14. model.load_weights(fname, by_name=True)

Please also see How can I install HDF5 or h5py to save my models in Keras? for instructions on how to install h5py.

Handling custom layers (or other custom objects) in saved models

If the model you want to load includes custom layers or other custom classes or functions, you can pass them to the loading mechanism via the custom_objects argument:

  1. from keras.models import load_model
  2. # Assuming your model includes instance of an "AttentionLayer" class
  3. model = load_model('my_model.h5', custom_objects={'AttentionLayer': AttentionLayer})

Alternatively, you can use a custom object scope:

  1. from keras.utils import CustomObjectScope
  2. with CustomObjectScope({'AttentionLayer': AttentionLayer}):
  3. model = load_model('my_model.h5')

Custom objects handling works the same way for load_model, model_from_json, model_from_yaml:

  1. from keras.models import model_from_json
  2. model = model_from_json(json_string, custom_objects={'AttentionLayer': AttentionLayer})

Why is the training loss much higher than the testing loss?

A Keras model has two modes: training and testing. Regularization mechanisms, such as Dropout and L1/L2 weight regularization, are turned off at testing time.

Besides, the training loss is the average of the losses over each batch of training data. Because your model is changing over time, the loss over the first batches of an epoch is generally higher than over the last batches. On the other hand, the testing loss for an epoch is computed using the model as it is at the end of the epoch, resulting in a lower loss.

How can I obtain the output of an intermediate layer?

One simple way is to create a new Model that will output the layers that you are interested in:

  1. from keras.models import Model
  2. model = ... # create the original model
  3. layer_name = 'my_layer'
  4. intermediate_layer_model = Model(inputs=model.input,
  5. outputs=model.get_layer(layer_name).output)
  6. intermediate_output = intermediate_layer_model.predict(data)

Alternatively, you can build a Keras function that will return the output of a certain layer given a certain input, for example:

  1. from keras import backend as K
  2. # with a Sequential model
  3. get_3rd_layer_output = K.function([model.layers[0].input],
  4. [model.layers[3].output])
  5. layer_output = get_3rd_layer_output([x])[0]

Similarly, you could build a Theano and TensorFlow function directly.

Note that if your model has a different behavior in training and testing phase (e.g. if it uses Dropout, BatchNormalization, etc.), you will need to pass the learning phase flag to your function:

  1. get_3rd_layer_output = K.function([model.layers[0].input, K.learning_phase()],
  2. [model.layers[3].output])
  3. # output in test mode = 0
  4. layer_output = get_3rd_layer_output([x, 0])[0]
  5. # output in train mode = 1
  6. layer_output = get_3rd_layer_output([x, 1])[0]

How can I use Keras with datasets that don't fit in memory?

You can do batch training using model.train_on_batch(x, y) and model.test_on_batch(x, y). See the models documentation.

Alternatively, you can write a generator that yields batches of training data and use the method model.fit_generator(data_generator, steps_per_epoch, epochs).

You can see batch training in action in our CIFAR10 example.

How can I interrupt training when the validation loss isn't decreasing anymore?

You can use an EarlyStopping callback:

  1. from keras.callbacks import EarlyStopping
  2. early_stopping = EarlyStopping(monitor='val_loss', patience=2)
  3. model.fit(x, y, validation_split=0.2, callbacks=[early_stopping])

Find out more in the callbacks documentation.

How is the validation split computed?

If you set the validationsplit argument in model.fit to e.g. 0.1, then the validation data used will be the _last 10% of the data. If you set it to 0.25, it will be the last 25% of the data, etc. Note that the data isn't shuffled before extracting the validation split, so the validation is literally just the last x% of samples in the input you passed.

The same validation set is used for all epochs (within a same call to fit).

Is the data shuffled during training?

Yes, if the shuffle argument in model.fit is set to True (which is the default), the training data will be randomly shuffled at each epoch.

Validation data is never shuffled.

How can I record the training / validation loss / accuracy at each epoch?

The model.fit method returns a History callback, which has a history attribute containing the lists of successive losses and other metrics.

  1. hist = model.fit(x, y, validation_split=0.2)
  2. print(hist.history)

How can I "freeze" Keras layers?

To "freeze" a layer means to exclude it from training, i.e. its weights will never be updated. This is useful in the context of fine-tuning a model, or using fixed embeddings for a text input.

You can pass a trainable argument (boolean) to a layer constructor to set a layer to be non-trainable:

  1. frozen_layer = Dense(32, trainable=False)

Additionally, you can set the trainable property of a layer to True or False after instantiation. For this to take effect, you will need to call compile() on your model after modifying the trainable property. Here's an example:

  1. x = Input(shape=(32,))
  2. layer = Dense(32)
  3. layer.trainable = False
  4. y = layer(x)
  5. frozen_model = Model(x, y)
  6. # in the model below, the weights of `layer` will not be updated during training
  7. frozen_model.compile(optimizer='rmsprop', loss='mse')
  8. layer.trainable = True
  9. trainable_model = Model(x, y)
  10. # with this model the weights of the layer will be updated during training
  11. # (which will also affect the above model since it uses the same layer instance)
  12. trainable_model.compile(optimizer='rmsprop', loss='mse')
  13. frozen_model.fit(data, labels) # this does NOT update the weights of `layer`
  14. trainable_model.fit(data, labels) # this updates the weights of `layer`

How can I use stateful RNNs?

Making a RNN stateful means that the states for the samples of each batch will be reused as initial states for the samples in the next batch.

When using stateful RNNs, it is therefore assumed that:

  • all batches have the same number of samples
  • If x1 and x2 are successive batches of samples, then x2[i] is the follow-up sequence to x1[i], for every i.

To use statefulness in RNNs, you need to:

  • explicitly specify the batch size you are using, by passing a batch_size argument to the first layer in your model. E.g. batch_size=32 for a 32-samples batch of sequences of 10 timesteps with 16 features per timestep.
  • set stateful=True in your RNN layer(s).
  • specify shuffle=False when calling fit().

To reset the states accumulated:

  • use model.reset_states() to reset the states of all layers in the model
  • use layer.reset_states() to reset the states of a specific stateful RNN layer

Example:

  1. x # this is our input data, of shape (32, 21, 16)
  2. # we will feed it to our model in sequences of length 10
  3. model = Sequential()
  4. model.add(LSTM(32, input_shape=(10, 16), batch_size=32, stateful=True))
  5. model.add(Dense(16, activation='softmax'))
  6. model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
  7. # we train the network to predict the 11th timestep given the first 10:
  8. model.train_on_batch(x[:, :10, :], np.reshape(x[:, 10, :], (32, 16)))
  9. # the state of the network has changed. We can feed the follow-up sequences:
  10. model.train_on_batch(x[:, 10:20, :], np.reshape(x[:, 20, :], (32, 16)))
  11. # let's reset the states of the LSTM layer:
  12. model.reset_states()
  13. # another way to do it in this case:
  14. model.layers[0].reset_states()

Note that the methods predict, fit, trainon_batch, predict_classes, etc. will _all update the states of the stateful layers in a model. This allows you to do not only stateful training, but also stateful prediction.

How can I remove a layer from a Sequential model?

You can remove the last added layer in a Sequential model by calling .pop():

  1. model = Sequential()
  2. model.add(Dense(32, activation='relu', input_dim=784))
  3. model.add(Dense(32, activation='relu'))
  4. print(len(model.layers)) # "2"
  5. model.pop()
  6. print(len(model.layers)) # "1"

How can I use pre-trained models in Keras?

Code and pre-trained weights are available for the following image classification models:

  • Xception
  • VGG16
  • VGG19
  • ResNet
  • ResNet v2
  • ResNeXt
  • Inception v3
  • Inception-ResNet v2
  • MobileNet v1
  • MobileNet v2
  • DenseNet
  • NASNet

They can be imported from the module keras.applications:

  1. from keras.applications.xception import Xception
  2. from keras.applications.vgg16 import VGG16
  3. from keras.applications.vgg19 import VGG19
  4. from keras.applications.resnet import ResNet50
  5. from keras.applications.resnet import ResNet101
  6. from keras.applications.resnet import ResNet152
  7. from keras.applications.resnet_v2 import ResNet50V2
  8. from keras.applications.resnet_v2 import ResNet101V2
  9. from keras.applications.resnet_v2 import ResNet152V2
  10. from keras.applications.resnext import ResNeXt50
  11. from keras.applications.resnext import ResNeXt101
  12. from keras.applications.inception_v3 import InceptionV3
  13. from keras.applications.inception_resnet_v2 import InceptionResNetV2
  14. from keras.applications.mobilenet import MobileNet
  15. from keras.applications.mobilenet_v2 import MobileNetV2
  16. from keras.applications.densenet import DenseNet121
  17. from keras.applications.densenet import DenseNet169
  18. from keras.applications.densenet import DenseNet201
  19. from keras.applications.nasnet import NASNetLarge
  20. from keras.applications.nasnet import NASNetMobile
  21. model = VGG16(weights='imagenet', include_top=True)

For a few simple usage examples, see the documentation for the Applications module.

For a detailed example of how to use such a pre-trained model for feature extraction or for fine-tuning, see this blog post.

The VGG16 model is also the basis for several Keras example scripts:

How can I use HDF5 inputs with Keras?

You can use the HDF5Matrix class from keras.utils. See the HDF5Matrix documentation for details.

You can also directly use a HDF5 dataset:

  1. import h5py
  2. with h5py.File('input/file.hdf5', 'r') as f:
  3. x_data = f['x_data']
  4. model.predict(x_data)

Please also see How can I install HDF5 or h5py to save my models in Keras? for instructions on how to install h5py.

Where is the Keras configuration file stored?

The default directory where all Keras data is stored is:

  1. $HOME/.keras/

Note that Windows users should replace $HOME with %USERPROFILE%.In case Keras cannot create the above directory (e.g. due to permission issues), /tmp/.keras/ is used as a backup.

The Keras configuration file is a JSON file stored at $HOME/.keras/keras.json. The default configuration file looks like this:

  1. {
  2. "image_data_format": "channels_last",
  3. "epsilon": 1e-07,
  4. "floatx": "float32",
  5. "backend": "tensorflow"
  6. }

It contains the following fields:

  • The image data format to be used as default by image processing layers and utilities (either channels_last or channels_first).
  • The epsilon numerical fuzz factor to be used to prevent division by zero in some operations.
  • The default float data type.
  • The default backend. See the backend documentation.

Likewise, cached dataset files, such as those downloaded with get_file(), are stored by default in $HOME/.keras/datasets/.

How can I obtain reproducible results using Keras during development?

During development of a model, sometimes it is useful to be able to obtain reproducible results from run to run in order to determine if a change in performance is due to an actual model or data modification, or merely a result of a new random sample.

First, you need to set the PYTHONHASHSEED environment variable to 0 before the program starts (not within the program itself). This is necessary in Python 3.2.3 onwards to have reproducible behavior for certain hash-based operations (e.g., the item order in a set or a dict, see Python's documentation or issue #2280 for further details). One way to set the environment variable is when starting python like this:

  1. $ cat test_hash.py
  2. print(hash("keras"))
  3. $ python3 test_hash.py # non-reproducible hash (Python 3.2.3+)
  4. -8127205062320133199
  5. $ python3 test_hash.py # non-reproducible hash (Python 3.2.3+)
  6. 3204480642156461591
  7. $ PYTHONHASHSEED=0 python3 test_hash.py # reproducible hash
  8. 4883664951434749476
  9. $ PYTHONHASHSEED=0 python3 test_hash.py # reproducible hash
  10. 4883664951434749476

Moreover, when using the TensorFlow backend and running on a GPU, some operations have non-deterministic outputs, in particular tf.reduce_sum(). This is due to the fact that GPUs run many operations in parallel, so the order of execution is not always guaranteed. Due to the limited precision of floats, even adding several numbers together may give slightly different results depending on the order in which you add them. You can try to avoid the non-deterministic operations, but some may be created automatically by TensorFlow to compute the gradients, so it is much simpler to just run the code on the CPU. For this, you can set the CUDA_VISIBLE_DEVICES environment variable to an empty string, for example:

  1. $ CUDA_VISIBLE_DEVICES="" PYTHONHASHSEED=0 python your_program.py

The below snippet of code provides an example of how to obtain reproducible results - this is geared towards a TensorFlow backend for a Python 3 environment:

  1. import numpy as np
  2. import tensorflow as tf
  3. import random as rn
  4. # The below is necessary for starting Numpy generated random numbers
  5. # in a well-defined initial state.
  6. np.random.seed(42)
  7. # The below is necessary for starting core Python generated random numbers
  8. # in a well-defined state.
  9. rn.seed(12345)
  10. # Force TensorFlow to use single thread.
  11. # Multiple threads are a potential source of non-reproducible results.
  12. # For further details, see: https://stackoverflow.com/questions/42022950/
  13. session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,
  14. inter_op_parallelism_threads=1)
  15. from keras import backend as K
  16. # The below tf.set_random_seed() will make random number generation
  17. # in the TensorFlow backend have a well-defined initial state.
  18. # For further details, see:
  19. # https://www.tensorflow.org/api_docs/python/tf/set_random_seed
  20. tf.set_random_seed(1234)
  21. sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)
  22. K.set_session(sess)
  23. # Rest of code follows ...

How can I install HDF5 or h5py to save my models in Keras?

In order to save your Keras models as HDF5 files, e.g. viakeras.callbacks.ModelCheckpoint, Keras uses the h5py Python package. It is a dependency of Keras and should be installed by default. On Debian-based distributions, you will have to additionally install libhdf5:

  1. sudo apt-get install libhdf5-serial-dev

If you are unsure if h5py is installed you can open a Python shell and load themodule via

  1. import h5py

If it imports without error it is installed, otherwise you can find detailedinstallation instructions here: http://docs.h5py.org/en/latest/build.html