[source]

CustomObjectScope

  1. keras.utils.CustomObjectScope()

Provides a scope that changes to _GLOBAL_CUSTOM_OBJECTS 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

[source]

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.

Examples

  1. from skimage.io import imread
  2. from skimage.transform import resize
  3. import numpy as np
  4. # Here, `x_set` is list of path to the images
  5. # and `y_set` are the associated classes.
  6. class CIFAR10Sequence(Sequence):
  7. def __init__(self, x_set, y_set, batch_size):
  8. self.x, self.y = x_set, y_set
  9. self.batch_size = batch_size
  10. def __len__(self):
  11. return int(np.ceil(len(self.x) / float(self.batch_size)))
  12. def __getitem__(self, idx):
  13. batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
  14. batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
  15. return np.array([
  16. resize(imread(file_name), (200, 200))
  17. for file_name in batch_x]), np.array(batch_y)

to_categorical

  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.],
  12. [ 1., 0., 0.]], dtype=float32)

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.
  • order: Normalization order (e.g. 2 for L2 norm).

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 Keras Directory.

Returns

Path to the downloaded file

print_summary

  1. keras.utils.print_summary(model, line_length=None, positions=None, print_fn=None)

Prints a summary of a model.

Arguments

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

  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_merge=False)
  6. print("Training using multiple GPUs..")
  7. except:
  8. parallel_model = model
  9. print("Training using single GPU or CPU..")
  10. parallel_model.compile(..)
  11. ..

On model saving

To save the multi-gpu model, use .save(fname) or .save_weights(fname)with the template model (the argument you passed to multi_gpu_model),rather than the model returned by multi_gpu_model.