Provides a scope that changes to cannot escape.

Code within a with statement will be able to access custom objectsby name. Changes to global custom objects persistwithin the enclosing with statement. At end of the with statement,global custom objects are reverted to stateat beginning of the with statement.

Example

Consider a custom object MyObject (e.g. a class):

  1. with CustomObjectScope({'MyObject':MyObject}):
  2. layer = Dense(..., kernel_regularizer='MyObject')
  3. # save, load, etc. will recognize custom object by name

HDF5Matrix

  1. keras.utils.HDF5Matrix(datapath, dataset, start=0, end=None, normalizer=None)

Representation of HDF5 dataset to be used instead of a Numpy array.

Example

  1. x_data = HDF5Matrix('input/file.hdf5', 'data')
  2. model.predict(x_data)

Providing start and end allows use of a slice of the dataset.

Optionally, a normalizer function (or lambda) can be given. This willbe called on every slice of data retrieved.

Arguments

  • datapath: string, path to a HDF5 file
  • dataset: string, name of the HDF5 dataset in the file specified in datapath
  • start: int, start of desired slice of the specified dataset
  • end: int, end of desired slice of the specified dataset
  • normalizer: function to be called on data when retrieved

Returns

An array-like HDF5 dataset.

[source]

Sequence

  1. keras.utils.Sequence()

Base object for fitting to a sequence of data, such as a dataset.

Every Sequence must implement the getitem and the len methods.If you want to modify your dataset between epochs you may implementonepochend. The method __getitem should return a complete batch.

Notes

Sequence are a safer way to do multiprocessing. This structure guaranteesthat the network will only train once on each sample per epoch which is notthe case with generators.

  1. keras.utils.to_categorical(y, num_classes=None, dtype='float32')

Converts a class vector (integers) to binary class matrix.

E.g. for use with categorical_crossentropy.

Arguments

  • y: class vector to be converted into a matrix (integers from 0 to num_classes).
  • num_classes: total number of classes.
  • dtype: The data type expected by the input, as a string (float32, float64, int32…)

Returns

A binary matrix representation of the input. The classes axisis placed last.

Example

  1. # Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
  2. > labels
  3. array([0, 2, 1, 2, 0])
  4. # `to_categorical` converts this into a matrix with as many
  5. # columns as there are classes. The number of rows
  6. # stays the same.
  7. > to_categorical(labels)
  8. array([[ 1., 0., 0.],
  9. [ 0., 0., 1.],
  10. [ 0., 1., 0.],
  11. [ 0., 0., 1.],

normalize

  1. keras.utils.normalize(x, axis=-1, order=2)

Normalizes a Numpy array.

Arguments

  • x: Numpy array to normalize.
  • axis: axis along which to normalize.

Returns

A normalized copy of the array.

get_file

  1. keras.utils.get_file(fname, origin, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None)

Downloads a file from a URL if it not already in the cache.

By default the file at the url origin is downloaded to thecache_dir ~/.keras, placed in the cache_subdir datasets,and given the filename fname. The final location of a fileexample.txt would therefore be ~/.keras/datasets/example.txt.

Files in tar, tar.gz, tar.bz, and zip formats can also be extracted.Passing a hash will verify the file after download. The command lineprograms shasum and sha256sum can compute the hash.

Arguments

  • fname: Name of the file. If an absolute path /path/to/file.txt is specified the file will be saved at that location.
  • origin: Original URL of the file.
  • untar: Deprecated in favor of 'extract'. boolean, whether the file should be decompressed
  • md5_hash: Deprecated in favor of 'file_hash'. md5 hash of the file for verification
  • file_hash: The expected hash string of the file after download. The sha256 and md5 hash algorithms are both supported.
  • cache_subdir: Subdirectory under the Keras cache dir where the file is saved. If an absolute path /path/to/folder is specified the file will be saved at that location.
  • hash_algorithm: Select the hash algorithm to verify the file. options are 'md5', 'sha256', and 'auto'. The default 'auto' detects the hash algorithm in use.
  • extract: True tries extracting the file as an Archive, like tar or zip.
  • archive_format: Archive format to try for extracting the file. Options are 'auto', 'tar', 'zip', and None. 'tar' includes tar, tar.gz, and tar.bz files. The default 'auto' is ['tar', 'zip']. None or an empty list will return no matches found.
  • cache_dir: Location to store cached files, when None it defaults to the .

Returns

Path to the downloaded file

Prints a summary of a model.

  • model: Keras model instance.
  • line_length: Total length of printed lines (e.g. set this to adapt the display to different terminal window sizes).
  • positions: Relative or absolute positions of log elements in each line. If not provided, defaults to [.33, .55, .67, 1.].
  • print_fn: Print function to use. It will be called on each line of the summary. You can set it to a custom function in order to capture the string summary. It defaults to print (prints to stdout).

plot_model

  1. keras.utils.plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)

Converts a Keras model to dot format and save to a file.

Arguments

  • model: A Keras model instance
  • to_file: File name of the plot image.
  • show_shapes: whether to display shape information.
  • show_layer_names: whether to display layer names.
  • rankdir: rankdir argument passed to PyDot, a string specifying the format of the plot: 'TB' creates a vertical plot; 'LR' creates a horizontal plot.
  • expand_nested: whether to expand nested models into clusters.
  • dpi: dot DPI.

Returns

A Jupyter notebook Image object if Jupyter is installed.This enables in-line display of the model plots in notebooks.

multi_gpu_model

  1. keras.utils.multi_gpu_model(model, gpus=None, cpu_merge=True, cpu_relocation=False)

Replicates a model on different GPUs.

Specifically, this function implements single-machinemulti-GPU data parallelism. It works in the following way:

  • Divide the model's input(s) into multiple sub-batches.
  • Apply a model copy on each sub-batch. Every model copyis executed on a dedicated GPU.
  • Concatenate the results (on CPU) into one big batch.

E.g. if your batch_size is 64 and you use gpus=2,then we will divide the input into 2 sub-batches of 32 samples,process each sub-batch on one GPU, then return the fullbatch of 64 processed samples.

This induces quasi-linear speedup on up to 8 GPUs.

This function is only available with the TensorFlow backendfor the time being.

Arguments

  • model: A Keras model instance. To avoid OOM errors, this model could have been built on CPU, for instance (see usage example below).
  • gpus: Integer >= 2 or list of integers, number of GPUs or list of GPU IDs on which to create model replicas.
  • cpu_merge: A boolean value to identify whether to force merging model weights under the scope of the CPU or not.
  • cpu_relocation: A boolean value to identify whether to create the model's weights under the scope of the CPU. If the model is not defined under any preceding device scope, you can still rescue it by activating this option.

Returns

A Keras Model instance which can be used just like the initialmodel argument, but which distributes its workload on multiple GPUs.

Examples

Example 1 - Training models with weights merge on CPU

  1. import tensorflow as tf
  2. from keras.applications import Xception
  3. from keras.utils import multi_gpu_model
  4. import numpy as np
  5. num_samples = 1000
  6. height = 224
  7. width = 224
  8. # Instantiate the base model (or "template" model).
  9. # We recommend doing this with under a CPU device scope,
  10. # so that the model's weights are hosted on CPU memory.
  11. # Otherwise they may end up hosted on a GPU, which would
  12. with tf.device('/cpu:0'):
  13. model = Xception(weights=None,
  14. input_shape=(height, width, 3),
  15. classes=num_classes)
  16. # Replicates the model on 8 GPUs.
  17. # This assumes that your machine has 8 available GPUs.
  18. parallel_model = multi_gpu_model(model, gpus=8)
  19. parallel_model.compile(loss='categorical_crossentropy',
  20. optimizer='rmsprop')
  21. # Generate dummy data.
  22. x = np.random.random((num_samples, height, width, 3))
  23. y = np.random.random((num_samples, num_classes))
  24. # This `fit` call will be distributed on 8 GPUs.
  25. # Since the batch size is 256, each GPU will process 32 samples.
  26. parallel_model.fit(x, y, epochs=20, batch_size=256)
  27. # Save model via the template model (which shares the same weights):
  28. model.save('my_model.h5')

Example 2 - Training models with weights merge on CPU using cpu_relocation

  1. ..
  2. # Not needed to change the device scope for model definition:
  3. model = Xception(weights=None, ..)
  4. try:
  5. parallel_model = multi_gpu_model(model, cpu_relocation=True)
  6. print("Training using multiple GPUs..")
  7. except ValueError:
  8. parallel_model = model
  9. print("Training using single GPU or CPU..")
  10. parallel_model.compile(..)
  11. ..

Example 3 - Training models with weights merge on GPU (recommended for NV-link)

On model saving