[source]

CustomObjectScope

keras.utils.generic_utils.CustomObjectScope()

Provides a scope that changes to _GLOBAL_CUSTOM_OBJECTS cannot escape.

Code within a with statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing with statement. At end of the with statement, global custom objects are reverted to state at beginning of the with statement.

Example

Consider a custom object MyObject

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

[source]

HDF5Matrix

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

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

Example

x_data = HDF5Matrix('input/file.hdf5', 'data')
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 will be 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

keras.utils.data_utils.Sequence()

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

Every Sequence must implements the __getitem__ and the __len__ methods.

Examples

from skimage.io import imread
from skimage.transform import resize
import numpy as np

__Here, `x_set` is list of path to the images__

# and `y_set` are the associated classes.

class CIFAR10Sequence(Sequence):
def __init__(self, x_set, y_set, batch_size):
    self.X,self.y = x_set,y_set
    self.batch_size = batch_size

def __len__(self):
    return len(self.X) // self.batch_size

def __getitem__(self,idx):
    batch_x = self.X[idx*self.batch_size:(idx+1)*self.batch_size]
    batch_y = self.y[idx*self.batch_size:(idx+1)*self.batch_size]

    return np.array([
    resize(imread(file_name), (200,200))
       for file_name in batch_x]), np.array(batch_y)

to_categorical

to_categorical(y, num_classes=None)

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.

Returns

A binary matrix representation of the input.


normalize

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.


custom_object_scope

custom_object_scope()

Provides a scope that changes to _GLOBAL_CUSTOM_OBJECTS cannot escape.

Convenience wrapper for CustomObjectScope. Code within a with statement will be able to access custom objects by name. Changes to global custom objects persist within the enclosing with statement. At end of the with statement, global custom objects are reverted to state at beginning of the with statement.

Example

Consider a custom object MyObject

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

Arguments

  • *args: Variable length list of dictionaries of name, class pairs to add to custom objects.

Returns

Object of type CustomObjectScope.


get_custom_objects

get_custom_objects()

Retrieves a live reference to the global dictionary of custom objects.

Updating and clearing custom objects using custom_object_scope is preferred, but get_custom_objects can be used to directly access _GLOBAL_CUSTOM_OBJECTS.

Example

get_custom_objects().clear()
get_custom_objects()['MyObject'] = MyObject

Returns

Global dictionary of names to classes (_GLOBAL_CUSTOM_OBJECTS).


serialize_keras_object

serialize_keras_object(instance)

deserialize_keras_object

deserialize_keras_object(identifier, module_objects=None, custom_objects=None, printable_module_name='object')

get_file

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 the cache_dir ~/.keras, placed in the cache_subdir datasets, and given the filename fname. The final location of a file example.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 line programs 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


convert_all_kernels_in_model

convert_all_kernels_in_model(model)

Converts all convolution kernels in a model from Theano to TensorFlow.

Also works from TensorFlow to Theano.

Arguments

  • model: target model for the conversion.

plot_model

plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB')

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.