tf.keras.regularizers.Regularizer     View source on GitHub    Regularizer base class.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.regularizers.Regularizer  Regularizers allow you to apply penalties on layer parameters or layer activity during optimization. These penalties are summed into the loss function that the network optimizes. Regularization penalties are applied on a per-layer basis. The exact API will depend on the layer, but many layers (e.g. Dense, Conv1D, Conv2D and Conv3D) have a unified API. These layers expose 3 keyword arguments:
kernel_regularizer: Regularizer to apply a penalty on the layer's kernel
bias_regularizer: Regularizer to apply a penalty on the layer's bias
activity_regularizer: Regularizer to apply a penalty on the layer's output  All layers (including custom layers) expose activity_regularizer as a settable property, whether or not it is in the constructor arguments. The value returned by the activity_regularizer is divided by the input batch size so that the relative weighting between the weight regularizers and the activity regularizers does not change with the batch size. You can access a layer's regularization penalties by calling layer.losses after calling the layer on inputs. Example
layer = tf.keras.layers.Dense(
    5, input_dim=5,
    kernel_initializer='ones',
    kernel_regularizer=tf.keras.regularizers.L1(0.01),
    activity_regularizer=tf.keras.regularizers.L2(0.01))
tensor = tf.ones(shape=(5, 5)) * 2.0
out = layer(tensor)

# The kernel regularization term is 0.25
# The activity regularization term (after dividing by the batch size) is 5
tf.math.reduce_sum(layer.losses)
<tf.Tensor: shape=(), dtype=float32, numpy=5.25>
 Available penalties tf.keras.regularizers.L1(0.3)  # L1 Regularization Penalty
tf.keras.regularizers.L2(0.1)  # L2 Regularization Penalty
tf.keras.regularizers.L1L2(l1=0.01, l2=0.01)  # L1 + L2 penalties
 Directly calling a regularizer Compute a regularization loss on a tensor by directly calling a regularizer as if it is a one-argument function. E.g. >>> regularizer = tf.keras.regularizers.L2(2.)
>>> tensor = tf.ones(shape=(5, 5))
>>> regularizer(tensor)
<tf.Tensor: shape=(), dtype=float32, numpy=50.0>
 Developing new regularizers Any function that takes in a weight matrix and returns a scalar tensor can be used as a regularizer, e.g.:
@tf.keras.utils.register_keras_serializable(package='Custom', name='l1')
def l1_reg(weight_matrix):
   return 0.01 * tf.math.reduce_sum(tf.math.abs(weight_matrix))

layer = tf.keras.layers.Dense(5, input_dim=5,
    kernel_initializer='ones', kernel_regularizer=l1_reg)
tensor = tf.ones(shape=(5, 5))
out = layer(tensor)
layer.losses
[<tf.Tensor: shape=(), dtype=float32, numpy=0.25>]
 Alternatively, you can write your custom regularizers in an object-oriented way by extending this regularizer base class, e.g.:
@tf.keras.utils.register_keras_serializable(package='Custom', name='l2')
class L2Regularizer(tf.keras.regularizers.Regularizer):
  def __init__(self, l2=0.):
    self.l2 = l2

  def __call__(self, x):
    return self.l2 * tf.math.reduce_sum(tf.math.square(x))

  def get_config(self):
    return {'l2': float(self.l2)}

layer = tf.keras.layers.Dense(
  5, input_dim=5, kernel_initializer='ones',
  kernel_regularizer=L2Regularizer(l2=0.5))

tensor = tf.ones(shape=(5, 5))
out = layer(tensor)
layer.losses
[<tf.Tensor: shape=(), dtype=float32, numpy=12.5>]
 A note on serialization and deserialization: Registering the regularizers as serializable is optional if you are just training and executing models, exporting to and from SavedModels, or saving and loading weight checkpoints. Registration is required for Keras model_to_estimator, saving and loading models to HDF5 formats, Keras model cloning, some visualization utilities, and exporting models to and from JSON. If using this functionality, you must make sure any python process running your model has also defined and registered your custom regularizer. tf.keras.utils.register_keras_serializable is only available in TF 2.1 and beyond. In earlier versions of TensorFlow you must pass your custom regularizer to the custom_objects argument of methods that expect custom regularizers to be registered as serializable. Methods from_config View source
@classmethod
from_config(
    config
)
 Creates a regularizer from its config. This method is the reverse of get_config, capable of instantiating the same regularizer from the config dictionary. This method is used by Keras model_to_estimator, saving and loading models to HDF5 formats, Keras model cloning, some visualization utilities, and exporting models to and from JSON.

 Arguments
  config   A Python dictionary, typically the output of get_config.

 Returns   A regularizer instance.
 get_config View source
get_config()
 Returns the config of the regularizer. An regularizer config is a Python dictionary (serializable) containing all configuration parameters of the regularizer. The same regularizer can be reinstantiated later (without any saved state) from this configuration. This method is optional if you are just training and executing models, exporting to and from SavedModels, or using weight checkpoints. This method is required for Keras model_to_estimator, saving and loading models to HDF5 formats, Keras model cloning, some visualization utilities, and exporting models to and from JSON.

 Returns   Python dictionary.
 __call__ View source
__call__(
    x
)
 Compute a regularization penalty from an input tensor.


tf.keras.regularizers.serialize     View source on GitHub     View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.regularizers.serialize
tf.keras.regularizers.serialize(
    regularizer
)


tf.keras.Sequential     View source on GitHub    Sequential groups a linear stack of layers into a tf.keras.Model. Inherits From: Model, Layer, Module  View aliases  Main aliases
tf.keras.models.Sequential Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.Sequential, tf.compat.v1.keras.models.Sequential
tf.keras.Sequential(
    layers=None, name=None
)
 Sequential provides training and inference features on this model. Examples:
# Optionally, the first layer can receive an `input_shape` argument:
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8, input_shape=(16,)))
# Afterwards, we do automatic shape inference:
model.add(tf.keras.layers.Dense(4))

# This is identical to the following:
model = tf.keras.Sequential()
model.add(tf.keras.Input(shape=(16,)))
model.add(tf.keras.layers.Dense(8))

# Note that you can also omit the `input_shape` argument.
# In that case the model doesn't have any weights until the first call
# to a training/evaluation method (since it isn't yet built):
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8))
model.add(tf.keras.layers.Dense(4))
# model.weights not created yet

# Whereas if you specify the input shape, the model gets built
# continuously as you are adding layers:
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8, input_shape=(16,)))
model.add(tf.keras.layers.Dense(4))
len(model.weights)
4

# When using the delayed-build pattern (no input shape specified), you can
# choose to manually build your model by calling
# `build(batch_input_shape)`:
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8))
model.add(tf.keras.layers.Dense(4))
model.build((None, 16))
len(model.weights)
4
 # Note that when using the delayed-build pattern (no input shape specified),
# the model gets built the first time you call `fit`, `eval`, or `predict`,
# or the first time you call the model on some input data.
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(8))
model.add(tf.keras.layers.Dense(1))
model.compile(optimizer='sgd', loss='mse')
# This builds the model for the first time:
model.fit(x, y, batch_size=32, epochs=10)

 Args
  layers   Optional list of layers to add to the model.
  name   Optional name for the model.

 Attributes
  distribute_strategy   The tf.distribute.Strategy this model was created under.
  layers

  metrics_names   Returns the model's display labels for all outputs.
Note: metrics_names are available only after a keras.Model has been trained/evaluated on actual data.

inputs = tf.keras.layers.Input(shape=(3,))
outputs = tf.keras.layers.Dense(2)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
model.metrics_names
[]

x = np.random.random((2, 3))
y = np.random.randint(0, 2, (2, 2))
model.fit(x, y)
model.metrics_names
['loss', 'mae']

inputs = tf.keras.layers.Input(shape=(3,))
d = tf.keras.layers.Dense(2, name='out')
output_1 = d(inputs)
output_2 = d(inputs)
model = tf.keras.models.Model(
   inputs=inputs, outputs=[output_1, output_2])
model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"])
model.fit(x, (y, y))
model.metrics_names
['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae',
'out_1_acc']

  run_eagerly   Settable attribute indicating whether the model should run eagerly. Running eagerly means that your model will be run step by step, like Python code. Your model might run slower, but it should become easier for you to debug it by stepping into individual layer calls. By default, we will attempt to compile your model to a static graph to deliver the best execution performance.
   Methods add View source
add(
    layer
)
 Adds a layer instance on top of the layer stack.

 Arguments
  layer   layer instance.

 Raises
  TypeError   If layer is not a layer instance.
  ValueError   In case the layer argument does not know its input shape.
  ValueError   In case the layer argument has multiple output tensors, or is already connected somewhere else (forbidden in Sequential models).    compile View source
compile(
    optimizer='rmsprop', loss=None, metrics=None, loss_weights=None,
    weighted_metrics=None, run_eagerly=None, steps_per_execution=None, **kwargs
)
 Configures the model for training.

 Arguments
  optimizer   String (name of optimizer) or optimizer instance. See tf.keras.optimizers.
  loss   String (name of objective function), objective function or tf.keras.losses.Loss instance. See tf.keras.losses. An objective function is any callable with the signature loss = fn(y_true, y_pred), where y_true = ground truth values with shape = [batch_size, d0, .. dN], except sparse loss functions such as sparse categorical crossentropy where shape = [batch_size, d0, .. dN-1]. y_pred = predicted values with shape = [batch_size, d0, .. dN]. It returns a weighted loss float tensor. If a custom Loss instance is used and reduction is set to NONE, return value has the shape [batch_size, d0, .. dN-1] ie. per-sample or per-timestep loss values; otherwise, it is a scalar. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses.
  metrics   List of metrics to be evaluated by the model during training and testing. Each of this can be a string (name of a built-in function), function or a tf.keras.metrics.Metric instance. See tf.keras.metrics. Typically you will use metrics=['accuracy']. A function is any callable with the signature result = fn(y_true, y_pred). To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}. You can also pass a list (len = len(outputs)) of lists of metrics such as metrics=[['accuracy'], ['accuracy', 'mse']] or metrics=['accuracy', ['accuracy', 'mse']]. When you pass the strings 'accuracy' or 'acc', we convert this to one of tf.keras.metrics.BinaryAccuracy, tf.keras.metrics.CategoricalAccuracy, tf.keras.metrics.SparseCategoricalAccuracy based on the loss function used and the model output shape. We do a similar conversion for the strings 'crossentropy' and 'ce' as well.
  loss_weights   Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the weighted sum of all individual losses, weighted by the loss_weights coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients.
  weighted_metrics   List of metrics to be evaluated and weighted by sample_weight or class_weight during training and testing.
  run_eagerly   Bool. Defaults to False. If True, this Model's logic will not be wrapped in a tf.function. Recommended to leave this as None unless your Model cannot be run inside a tf.function.
  steps_per_execution   Int. Defaults to 1. The number of batches to run during each tf.function call. Running multiple batches inside a single tf.function call can greatly improve performance on TPUs or small models with a large Python overhead. At most, one full epoch will be run each execution. If a number larger than the size of the epoch is passed, the execution will be truncated to the size of the epoch. Note that if steps_per_execution is set to N, Callback.on_batch_begin and Callback.on_batch_end methods will only be called every N batches (i.e. before/after each tf.function execution).
  **kwargs   Arguments supported for backwards compatibility only.

 Raises
  ValueError   In case of invalid arguments for optimizer, loss or metrics.    evaluate View source
evaluate(
    x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None,
    callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False,
    return_dict=False
)
 Returns the loss value & metrics values for the model in test mode. Computation is done in batches (see the batch_size arg.)

 Arguments
  x   Input data. It could be:  A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). A dict mapping input names to the corresponding array/tensors, if the model has named inputs. A tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights). A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample_weights). A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the Unpacking behavior for iterator-like inputs section of Model.fit.

  y   Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, generator or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from the iterator/dataset).
  batch_size   Integer or None. Number of samples per batch of computation. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of a dataset, generators, or keras.utils.Sequence instances (since they generate batches).
  verbose   0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.
  sample_weight   Optional Numpy array of weights for the test samples, used for weighting the loss function. You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. This argument is not supported when x is a dataset, instead pass sample weights as the third element of x.
  steps   Integer or None. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of None. If x is a tf.data dataset and steps is None, 'evaluate' will run until the dataset is exhausted. This argument is not supported with array inputs.
  callbacks   List of keras.callbacks.Callback instances. List of callbacks to apply during evaluation. See callbacks.
  max_queue_size   Integer. Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
  workers   Integer. Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  use_multiprocessing   Boolean. Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.
  return_dict   If True, loss and metric results are returned as a dict, with each key being the name of the metric. If False, they are returned as a list.    See the discussion of Unpacking behavior for iterator-like inputs for Model.fit.

 Returns   Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.

 Raises
  RuntimeError   If model.evaluate is wrapped in tf.function.
  ValueError   in case of invalid arguments.    evaluate_generator View source
evaluate_generator(
    generator, steps=None, callbacks=None, max_queue_size=10, workers=1,
    use_multiprocessing=False, verbose=0
)
 Evaluates the model on a data generator. DEPRECATED: Model.evaluate now supports generators, so there is no longer any need to use this endpoint. fit View source
fit(
    x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None,
    validation_split=0.0, validation_data=None, shuffle=True, class_weight=None,
    sample_weight=None, initial_epoch=0, steps_per_epoch=None,
    validation_steps=None, validation_batch_size=None, validation_freq=1,
    max_queue_size=10, workers=1, use_multiprocessing=False
)
 Trains the model for a fixed number of epochs (iterations on a dataset).

 Arguments
  x   Input data. It could be:  A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). A dict mapping input names to the corresponding array/tensors, if the model has named inputs. A tf.data dataset. Should return a tuple of either (inputs, targets) or (inputs, targets, sample_weights). A generator or keras.utils.Sequence returning (inputs, targets) or (inputs, targets, sample_weights). A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given below.

  y   Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely). If x is a dataset, generator, or keras.utils.Sequence instance, y should not be specified (since targets will be obtained from x).
  batch_size   Integer or None. Number of samples per gradient update. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of datasets, generators, or keras.utils.Sequence instances (since they generate batches).
  epochs   Integer. Number of epochs to train the model. An epoch is an iteration over the entire x and y data provided. Note that in conjunction with initial_epoch, epochs is to be understood as "final epoch". The model is not trained for a number of iterations given by epochs, but merely until the epoch of index epochs is reached.
  verbose   0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment).
  callbacks   List of keras.callbacks.Callback instances. List of callbacks to apply during training. See tf.keras.callbacks. Note tf.keras.callbacks.ProgbarLogger and tf.keras.callbacks.History callbacks are created automatically and need not be passed into model.fit. tf.keras.callbacks.ProgbarLogger is created or not based on verbose argument to model.fit.
  validation_split   Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the x and y data provided, before shuffling. This argument is not supported when x is a dataset, generator or keras.utils.Sequence instance.
  validation_data   Data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. Thus, note the fact that the validation loss of data provided using validation_split or validation_data is not affected by regularization layers like noise and dropout. validation_data will override validation_split. validation_data could be: tuple (x_val, y_val) of Numpy arrays or tensors tuple (x_val, y_val, val_sample_weights) of Numpy arrays dataset For the first two cases, batch_size must be provided. For the last case, validation_steps could be provided. Note that validation_data does not support all the data types that are supported in x, eg, dict, generator or keras.utils.Sequence.

  shuffle   Boolean (whether to shuffle the training data before each epoch) or str (for 'batch'). This argument is ignored when x is a generator. 'batch' is a special option for dealing with the limitations of HDF5 data; it shuffles in batch-sized chunks. Has no effect when steps_per_epoch is not None.
  class_weight   Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.
  sample_weight   Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. This argument is not supported when x is a dataset, generator, or keras.utils.Sequence instance, instead provide the sample_weights as the third element of x.
  initial_epoch   Integer. Epoch at which to start training (useful for resuming a previous training run).
  steps_per_epoch   Integer or None. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default None is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a tf.data dataset, and 'steps_per_epoch' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the steps_per_epoch argument. This argument is not supported with array inputs.
  validation_steps   Only relevant if validation_data is provided and is a tf.data dataset. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If 'validation_steps' is None, validation will run until the validation_data dataset is exhausted. In the case of an infinitely repeated dataset, it will run into an infinite loop. If 'validation_steps' is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time.
  validation_batch_size   Integer or None. Number of samples per validation batch. If unspecified, will default to batch_size. Do not specify the validation_batch_size if your data is in the form of datasets, generators, or keras.utils.Sequence instances (since they generate batches).
  validation_freq   Only relevant if validation data is provided. Integer or collections_abc.Container instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. validation_freq=2 runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. validation_freq=[1, 2, 10] runs validation at the end of the 1st, 2nd, and 10th epochs.
  max_queue_size   Integer. Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
  workers   Integer. Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  use_multiprocessing   Boolean. Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.    Unpacking behavior for iterator-like inputs: A common pattern is to pass a tf.data.Dataset, generator, or tf.keras.utils.Sequence to the x argument of fit, which will in fact yield not only features (x) but optionally targets (y) and sample weights. Keras requires that the output of such iterator-likes be unambiguous. The iterator should return a tuple of length 1, 2, or 3, where the optional second and third elements will be used for y and sample_weight respectively. Any other type provided will be wrapped in a length one tuple, effectively treating everything as 'x'. When yielding dicts, they should still adhere to the top-level tuple structure. e.g. ({"x0": x0, "x1": x1}, y). Keras will not attempt to separate features, targets, and weights from the keys of a single dict. A notable unsupported data type is the namedtuple. The reason is that it behaves like both an ordered datatype (tuple) and a mapping datatype (dict). So given a namedtuple of the form: namedtuple("example_tuple", ["y", "x"]) it is ambiguous whether to reverse the order of the elements when interpreting the value. Even worse is a tuple of the form: namedtuple("other_tuple", ["x", "y", "z"]) where it is unclear if the tuple was intended to be unpacked into x, y, and sample_weight or passed through as a single element to x. As a result the data processing code will simply raise a ValueError if it encounters a namedtuple. (Along with instructions to remedy the issue.)

 Returns   A History object. Its History.history attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable).

 Raises
  RuntimeError    If the model was never compiled or, If model.fit is wrapped in tf.function.

  ValueError   In case of mismatch between the provided input data and what the model expects or when the input data is empty.    fit_generator View source
fit_generator(
    generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
    validation_data=None, validation_steps=None, validation_freq=1,
    class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False,
    shuffle=True, initial_epoch=0
)
 Fits the model on data yielded batch-by-batch by a Python generator. DEPRECATED: Model.fit now supports generators, so there is no longer any need to use this endpoint. get_layer View source
get_layer(
    name=None, index=None
)
 Retrieves a layer based on either its name (unique) or index. If name and index are both provided, index will take precedence. Indices are based on order of horizontal graph traversal (bottom-up).

 Arguments
  name   String, name of layer.
  index   Integer, index of layer.

 Returns   A layer instance.

 Raises
  ValueError   In case of invalid layer name or index.    load_weights View source
load_weights(
    filepath, by_name=False, skip_mismatch=False, options=None
)
 Loads all layer weights, either from a TensorFlow or an HDF5 weight file. If by_name is False weights are loaded based on the network's topology. This means the architecture should be the same as when the weights were saved. Note that layers that don't have weights are not taken into account in the topological ordering, so adding or removing layers is fine as long as they don't have weights. If by_name is True, weights are loaded into layers only if they share the same name. This is useful for fine-tuning or transfer-learning models where some of the layers have changed. Only topological loading (by_name=False) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from tf.keras.Model: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which layers are assigned in the Model's constructor.

 Arguments
  filepath   String, path to the weights file to load. For weight files in TensorFlow format, this is the file prefix (the same as was passed to save_weights).
  by_name   Boolean, whether to load weights by name or by topological order. Only topological loading is supported for weight files in TensorFlow format.
  skip_mismatch   Boolean, whether to skip loading of layers where there is a mismatch in the number of weights, or a mismatch in the shape of the weight (only valid when by_name=True).
  options   Optional tf.train.CheckpointOptions object that specifies options for loading weights.

 Returns   When loading a weight file in TensorFlow format, returns the same status object as tf.train.Checkpoint.restore. When graph building, restore ops are run automatically as soon as the network is built (on first call for user-defined classes inheriting from Model, immediately if it is already built). When loading weights in HDF5 format, returns None.

 Raises
  ImportError   If h5py is not available and the weight file is in HDF5 format.
  ValueError   If skip_mismatch is set to True when by_name is False.    make_predict_function View source
make_predict_function()
 Creates a function that executes one step of inference. This method can be overridden to support custom inference logic. This method is called by Model.predict and Model.predict_on_batch. Typically, this method directly controls tf.function and tf.distribute.Strategy settings, and delegates the actual evaluation logic to Model.predict_step. This function is cached the first time Model.predict or Model.predict_on_batch is called. The cache is cleared whenever Model.compile is called.

 Returns   Function. The function created by this method should accept a tf.data.Iterator, and return the outputs of the Model.
 make_test_function View source
make_test_function()
 Creates a function that executes one step of evaluation. This method can be overridden to support custom evaluation logic. This method is called by Model.evaluate and Model.test_on_batch. Typically, this method directly controls tf.function and tf.distribute.Strategy settings, and delegates the actual evaluation logic to Model.test_step. This function is cached the first time Model.evaluate or Model.test_on_batch is called. The cache is cleared whenever Model.compile is called.

 Returns   Function. The function created by this method should accept a tf.data.Iterator, and return a dict containing values that will be passed to tf.keras.Callbacks.on_test_batch_end.
 make_train_function View source
make_train_function()
 Creates a function that executes one step of training. This method can be overridden to support custom training logic. This method is called by Model.fit and Model.train_on_batch. Typically, this method directly controls tf.function and tf.distribute.Strategy settings, and delegates the actual training logic to Model.train_step. This function is cached the first time Model.fit or Model.train_on_batch is called. The cache is cleared whenever Model.compile is called.

 Returns   Function. The function created by this method should accept a tf.data.Iterator, and return a dict containing values that will be passed to tf.keras.Callbacks.on_train_batch_end, such as {'loss': 0.2, 'accuracy': 0.7}.
 pop View source
pop()
 Removes the last layer in the model.

 Raises
  TypeError   if there are no layers in the model.    predict View source
predict(
    x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10,
    workers=1, use_multiprocessing=False
)
 Generates output predictions for the input samples. Computation is done in batches. This method is designed for performance in large scale inputs. For small amount of inputs that fit in one batch, directly using __call__ is recommended for faster execution, e.g., model(x), or model(x, training=False) if you have layers such as tf.keras.layers.BatchNormalization that behaves differently during inference. Also, note the fact that test loss is not affected by regularization layers like noise and dropout.

 Arguments
  x   Input samples. It could be:  A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). A tf.data dataset. A generator or keras.utils.Sequence instance. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the Unpacking behavior for iterator-like inputs section of Model.fit.

  batch_size   Integer or None. Number of samples per batch. If unspecified, batch_size will default to 32. Do not specify the batch_size if your data is in the form of dataset, generators, or keras.utils.Sequence instances (since they generate batches).
  verbose   Verbosity mode, 0 or 1.
  steps   Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of None. If x is a tf.data dataset and steps is None, predict will run until the input dataset is exhausted.
  callbacks   List of keras.callbacks.Callback instances. List of callbacks to apply during prediction. See callbacks.
  max_queue_size   Integer. Used for generator or keras.utils.Sequence input only. Maximum size for the generator queue. If unspecified, max_queue_size will default to 10.
  workers   Integer. Used for generator or keras.utils.Sequence input only. Maximum number of processes to spin up when using process-based threading. If unspecified, workers will default to 1. If 0, will execute the generator on the main thread.
  use_multiprocessing   Boolean. Used for generator or keras.utils.Sequence input only. If True, use process-based threading. If unspecified, use_multiprocessing will default to False. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.    See the discussion of Unpacking behavior for iterator-like inputs for Model.fit. Note that Model.predict uses the same interpretation rules as Model.fit and Model.evaluate, so inputs must be unambiguous for all three methods.

 Returns   Numpy array(s) of predictions.

 Raises
  RuntimeError   If model.predict is wrapped in tf.function.
  ValueError   In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.    predict_classes View source
predict_classes(
    x, batch_size=32, verbose=0
)
 Generate class predictions for the input samples. The input samples are processed batch by batch.

 Arguments
  x   input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs).
  batch_size   integer.
  verbose   verbosity mode, 0 or 1.

 Returns   A numpy array of class predictions.
 predict_generator View source
predict_generator(
    generator, steps=None, callbacks=None, max_queue_size=10, workers=1,
    use_multiprocessing=False, verbose=0
)
 Generates predictions for the input samples from a data generator. DEPRECATED: Model.predict now supports generators, so there is no longer any need to use this endpoint. predict_on_batch View source
predict_on_batch(
    x
)
 Returns predictions for a single batch of samples.

 Arguments
  x   Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs).

 Returns   Numpy array(s) of predictions.

 Raises
  RuntimeError   If model.predict_on_batch is wrapped in tf.function.
  ValueError   In case of mismatch between given number of inputs and expectations of the model.    predict_proba View source
predict_proba(
    x, batch_size=32, verbose=0
)
 Generates class probability predictions for the input samples. The input samples are processed batch by batch.

 Arguments
  x   input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs).
  batch_size   integer.
  verbose   verbosity mode, 0 or 1.

 Returns   A Numpy array of probability predictions.
 predict_step View source
predict_step(
    data
)
 The logic for one inference step. This method can be overridden to support custom inference logic. This method is called by Model.make_predict_function. This method should contain the mathematical logic for one step of inference. This typically includes the forward pass. Configuration details for how this logic is run (e.g. tf.function and tf.distribute.Strategy settings), should be left to Model.make_predict_function, which can also be overridden.

 Arguments
  data   A nested structure of Tensors.

 Returns   The result of one inference step, typically the output of calling the Model on data.
 reset_metrics View source
reset_metrics()
 Resets the state of all the metrics in the model. Examples:
inputs = tf.keras.layers.Input(shape=(3,))
outputs = tf.keras.layers.Dense(2)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer="Adam", loss="mse", metrics=["mae"])

x = np.random.random((2, 3))
y = np.random.randint(0, 2, (2, 2))
_ = model.fit(x, y, verbose=0)
assert all(float(m.result()) for m in model.metrics)

model.reset_metrics()
assert all(float(m.result()) == 0 for m in model.metrics)
 reset_states View source
reset_states()
 save View source
save(
    filepath, overwrite=True, include_optimizer=True, save_format=None,
    signatures=None, options=None, save_traces=True
)
 Saves the model to Tensorflow SavedModel or a single HDF5 file. Please see tf.keras.models.save_model or the Serialization and Saving guide for details.

 Arguments
  filepath   String, PathLike, path to SavedModel or H5 file to save the model.
  overwrite   Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  include_optimizer   If True, save optimizer's state together.
  save_format   Either 'tf' or 'h5', indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X.
  signatures   Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the signatures argument in tf.saved_model.save for details.
  options   (only applies to SavedModel format) tf.saved_model.SaveOptions object that specifies options for saving to SavedModel.
  save_traces   (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to True. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a get_config() method.    Example: from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'
del model  # deletes the existing model

# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
 save_weights View source
save_weights(
    filepath, overwrite=True, save_format=None, options=None
)
 Saves all layer weights. Either saves in HDF5 or in TensorFlow format based on the save_format argument. When saving in HDF5 format, the weight file has:
layer_names (attribute), a list of strings (ordered names of model layers). For every layer, a group named layer.name  For every such layer group, a group attribute weight_names, a list of strings (ordered names of weights tensor of the layer). For every weight in the layer, a dataset storing the weight value, named after the weight tensor.
  When saving in TensorFlow format, all objects referenced by the network are saved in the same format as tf.train.Checkpoint, including any Layer instances or Optimizer instances assigned to object attributes. For networks constructed from inputs and outputs using tf.keras.Model(inputs, outputs), Layer instances used by the network are tracked/saved automatically. For user-defined classes which inherit from tf.keras.Model, Layer instances must be assigned to object attributes, typically in the constructor. See the documentation of tf.train.Checkpoint and tf.keras.Model for details. While the formats are the same, do not mix save_weights and tf.train.Checkpoint. Checkpoints saved by Model.save_weights should be loaded using Model.load_weights. Checkpoints saved using tf.train.Checkpoint.save should be restored using the corresponding tf.train.Checkpoint.restore. Prefer tf.train.Checkpoint over save_weights for training checkpoints. The TensorFlow format matches objects and variables by starting at a root object, self for save_weights, and greedily matching attribute names. For Model.save this is the Model, and for Checkpoint.save this is the Checkpoint even if the Checkpoint has a model attached. This means saving a tf.keras.Model using save_weights and loading into a tf.train.Checkpoint with a Model attached (or vice versa) will not match the Model's variables. See the guide to training checkpoints for details on the TensorFlow format.

 Arguments
  filepath   String or PathLike, path to the file to save the weights to. When saving in TensorFlow format, this is the prefix used for checkpoint files (multiple files are generated). Note that the '.h5' suffix causes weights to be saved in HDF5 format.
  overwrite   Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  save_format   Either 'tf' or 'h5'. A filepath ending in '.h5' or '.keras' will default to HDF5 if save_format is None. Otherwise None defaults to 'tf'.
  options   Optional tf.train.CheckpointOptions object that specifies options for saving weights.

 Raises
  ImportError   If h5py is not available when attempting to save in HDF5 format.
  ValueError   For invalid/unknown format arguments.    summary View source
summary(
    line_length=None, positions=None, print_fn=None
)
 Prints a string summary of the network.

 Arguments
  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. Defaults to print. 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.

 Raises
  ValueError   if summary() is called before the model is built.    test_on_batch View source
test_on_batch(
    x, y=None, sample_weight=None, reset_metrics=True, return_dict=False
)
 Test the model on a single batch of samples.

 Arguments
  x   Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs).  A dict mapping input names to the corresponding array/tensors, if the model has named inputs.

  y   Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely).
  sample_weight   Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample.
  reset_metrics   If True, the metrics returned will be only for this batch. If False, the metrics will be statefully accumulated across batches.
  return_dict   If True, loss and metric results are returned as a dict, with each key being the name of the metric. If False, they are returned as a list.

 Returns   Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.

 Raises
  RuntimeError   If model.test_on_batch is wrapped in tf.function.
  ValueError   In case of invalid user-provided arguments.    test_step View source
test_step(
    data
)
 The logic for one evaluation step. This method can be overridden to support custom evaluation logic. This method is called by Model.make_test_function. This function should contain the mathematical logic for one step of evaluation. This typically includes the forward pass, loss calculation, and metrics updates. Configuration details for how this logic is run (e.g. tf.function and tf.distribute.Strategy settings), should be left to Model.make_test_function, which can also be overridden.

 Arguments
  data   A nested structure of Tensors.

 Returns   A dict containing values that will be passed to tf.keras.callbacks.CallbackList.on_train_batch_end. Typically, the values of the Model's metrics are returned.
 to_json View source
to_json(
    **kwargs
)
 Returns a JSON string containing the network configuration. To load a network from a JSON save file, use keras.models.model_from_json(json_string, custom_objects={}).

 Arguments
  **kwargs   Additional keyword arguments to be passed to json.dumps().

 Returns   A JSON string.
 to_yaml View source
to_yaml(
    **kwargs
)
 Returns a yaml string containing the network configuration. To load a network from a yaml save file, use keras.models.model_from_yaml(yaml_string, custom_objects={}). custom_objects should be a dictionary mapping the names of custom losses / layers / etc to the corresponding functions / classes.

 Arguments
  **kwargs   Additional keyword arguments to be passed to yaml.dump().

 Returns   A YAML string.

 Raises
  ImportError   if yaml module is not found.    train_on_batch View source
train_on_batch(
    x, y=None, sample_weight=None, class_weight=None, reset_metrics=True,
    return_dict=False
)
 Runs a single gradient update on a single batch of data.

 Arguments
  x   Input data. It could be:  A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). A dict mapping input names to the corresponding array/tensors, if the model has named inputs.

  y   Target data. Like the input data x, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with x (you cannot have Numpy inputs and tensor targets, or inversely).
  sample_weight   Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample.
  class_weight   Optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class.
  reset_metrics   If True, the metrics returned will be only for this batch. If False, the metrics will be statefully accumulated across batches.
  return_dict   If True, loss and metric results are returned as a dict, with each key being the name of the metric. If False, they are returned as a list.

 Returns   Scalar training loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute model.metrics_names will give you the display labels for the scalar outputs.

 Raises
  RuntimeError   If model.train_on_batch is wrapped in tf.function.
  ValueError   In case of invalid user-provided arguments.    train_step View source
train_step(
    data
)
 The logic for one training step. This method can be overridden to support custom training logic. This method is called by Model.make_train_function. This method should contain the mathematical logic for one step of training. This typically includes the forward pass, loss calculation, backpropagation, and metric updates. Configuration details for how this logic is run (e.g. tf.function and tf.distribute.Strategy settings), should be left to Model.make_train_function, which can also be overridden.

 Arguments
  data   A nested structure of Tensors.

 Returns   A dict containing values that will be passed to tf.keras.callbacks.CallbackList.on_train_batch_end. Typically, the values of the Model's metrics are returned. Example: {'loss': 0.2, 'accuracy': 0.7}.


Module: tf.keras.utils Public API for tf.keras.utils namespace. Classes class CustomObjectScope: Exposes custom classes/functions to Keras deserialization internals. class GeneratorEnqueuer: Builds a queue out of a data generator. class OrderedEnqueuer: Builds a Enqueuer from a Sequence. class Progbar: Displays a progress bar. class Sequence: Base object for fitting to a sequence of data, such as a dataset. class SequenceEnqueuer: Base class to enqueue inputs. class custom_object_scope: Exposes custom classes/functions to Keras deserialization internals. Functions deserialize_keras_object(...): Turns the serialized form of a Keras object back into an actual object. get_custom_objects(...): Retrieves a live reference to the global dictionary of custom objects. get_file(...): Downloads a file from a URL if it not already in the cache. get_registered_name(...): Returns the name registered to an object within the Keras framework. get_registered_object(...): Returns the class associated with name if it is registered with Keras. get_source_inputs(...): Returns the list of input tensors necessary to compute tensor. model_to_dot(...): Convert a Keras model to dot format. normalize(...): Normalizes a Numpy array. pack_x_y_sample_weight(...): Packs user-provided data into a tuple. plot_model(...): Converts a Keras model to dot format and save to a file. register_keras_serializable(...): Registers an object with the Keras serialization framework. serialize_keras_object(...): Serialize a Keras object into a JSON-compatible representation. to_categorical(...): Converts a class vector (integers) to binary class matrix. unpack_x_y_sample_weight(...): Unpacks user-provided data tuple.


tf.keras.utils.CustomObjectScope     View source on GitHub    Exposes custom classes/functions to Keras deserialization internals.  View aliases  Main aliases
tf.keras.utils.custom_object_scope Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.utils.CustomObjectScope, tf.compat.v1.keras.utils.custom_object_scope
tf.keras.utils.CustomObjectScope(
    *args
)
 Under a scope with custom_object_scope(objects_dict), Keras methods such as tf.keras.models.load_model or tf.keras.models.model_from_config will be able to deserialize any custom object referenced by a saved config (e.g. a custom layer or metric). Example: Consider a custom regularizer my_regularizer: layer = Dense(3, kernel_regularizer=my_regularizer)
config = layer.get_config()  # Config contains a reference to `my_regularizer`
...
# Later:
with custom_object_scope({'my_regularizer': my_regularizer}):
  layer = Dense.from_config(config)

 Arguments
  *args   Dictionary or dictionaries of {name: object} pairs.    Methods __enter__ View source
__enter__()
 __exit__ View source
__exit__(
    *args, **kwargs
)


tf.keras.utils.deserialize_keras_object     View source on GitHub    Turns the serialized form of a Keras object back into an actual object.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.deserialize_keras_object
tf.keras.utils.deserialize_keras_object(
    identifier, module_objects=None, custom_objects=None,
    printable_module_name='object'
)


tf.keras.utils.GeneratorEnqueuer     View source on GitHub    Builds a queue out of a data generator. Inherits From: SequenceEnqueuer  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.GeneratorEnqueuer
tf.keras.utils.GeneratorEnqueuer(
    sequence, use_multiprocessing=False, random_seed=None
)
 The provided generator can be finite in which case the class will throw a StopIteration exception. Used in fit_generator, evaluate_generator, predict_generator.

 Arguments
  generator   a generator function which yields data
  use_multiprocessing   use multiprocessing if True, otherwise threading
  wait_time   time to sleep in-between calls to put()
  random_seed   Initial seed for workers, will be incremented by one for each worker.    Methods get View source
get()
 Creates a generator to extract data from the queue. Skip the data if it is None.

 Yields   The next element in the queue, i.e. a tuple (inputs, targets) or (inputs, targets, sample_weights).
 is_running View source
is_running()
 start View source
start(
    workers=1, max_queue_size=10
)
 Starts the handler's workers.

 Arguments
  workers   Number of workers.
  max_queue_size   queue size (when full, workers could block on put())    stop View source
stop(
    timeout=None
)
 Stops running threads and wait for them to exit, if necessary. Should be called by the same thread which called start().

 Arguments
  timeout   maximum time to wait on thread.join()


tf.keras.utils.get_custom_objects     View source on GitHub    Retrieves a live reference to the global dictionary of custom objects.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.get_custom_objects
tf.keras.utils.get_custom_objects()
 Updating and clearing custom objects using custom_object_scope is preferred, but get_custom_objects can be used to directly access the current collection of custom objects. Example: get_custom_objects().clear()
get_custom_objects()['MyObject'] = MyObject

 Returns   Global dictionary of names to classes (_GLOBAL_CUSTOM_OBJECTS).


tf.keras.utils.get_file     View source on GitHub    Downloads a file from a URL if it not already in the cache.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.get_file
tf.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
)
 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. Example: path_to_downloaded_file = tf.keras.utils.get_file(
    "flower_photos",
    "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz",
    untar=True)

 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 argument. boolean, whether the file should be decompressed
  md5_hash   Deprecated in favor of file_hash argument. 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' corresponds to ['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 default directory ~/.keras/.

 Returns   Path to the downloaded file


tf.keras.utils.get_registered_name Returns the name registered to an object within the Keras framework.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.get_registered_name
tf.keras.utils.get_registered_name(
    obj
)
 This function is part of the Keras serialization and deserialization framework. It maps objects to the string names associated with those objects for serialization/deserialization.

 Args
  obj   The object to look up.

 Returns   The name associated with the object, or the default Python name if the object is not registered.


tf.keras.utils.get_registered_object Returns the class associated with name if it is registered with Keras.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.get_registered_object
tf.keras.utils.get_registered_object(
    name, custom_objects=None, module_objects=None
)
 This function is part of the Keras serialization and deserialization framework. It maps strings to the objects associated with them for serialization/deserialization. Example: def from_config(cls, config, custom_objects=None):
  if 'my_custom_object_name' in config:
    config['hidden_cls'] = tf.keras.utils.get_registered_object(
        config['my_custom_object_name'], custom_objects=custom_objects)

 Args
  name   The name to look up.
  custom_objects   A dictionary of custom objects to look the name up in. Generally, custom_objects is provided by the user.
  module_objects   A dictionary of custom objects to look the name up in. Generally, module_objects is provided by midlevel library implementers.

 Returns   An instantiable class associated with 'name', or None if no such class exists.


tf.keras.utils.get_source_inputs     View source on GitHub    Returns the list of input tensors necessary to compute tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.get_source_inputs
tf.keras.utils.get_source_inputs(
    tensor, layer=None, node_index=None
)
 Output will always be a list of tensors (potentially with 1 element).

 Arguments
  tensor   The tensor to start from.
  layer   Origin layer of the tensor. Will be determined via tensor._keras_history if not provided.
  node_index   Origin node index of the tensor.

 Returns   List of input tensors.


tf.keras.utils.model_to_dot     View source on GitHub    Convert a Keras model to dot format.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.model_to_dot
tf.keras.utils.model_to_dot(
    model, show_shapes=False, show_dtype=False, show_layer_names=True,
    rankdir='TB', expand_nested=False, dpi=96, subgraph=False
)

 Arguments
  model   A Keras model instance.
  show_shapes   whether to display shape information.
  show_dtype   whether to display layer dtypes.
  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   Dots per inch.
  subgraph   whether to return a pydot.Cluster instance.

 Returns   A pydot.Dot instance representing the Keras model or a pydot.Cluster instance representing nested model if subgraph=True.

 Raises
  ImportError   if graphviz or pydot are not available.


tf.keras.utils.normalize     View source on GitHub    Normalizes a Numpy array.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.normalize
tf.keras.utils.normalize(
    x, axis=-1, order=2
)

 Arguments
  x   Numpy array to normalize.
  axis   axis along which to normalize.
  order   Normalization order (e.g. order=2 for L2 norm).

 Returns   A normalized copy of the array.


tf.keras.utils.OrderedEnqueuer     View source on GitHub    Builds a Enqueuer from a Sequence. Inherits From: SequenceEnqueuer  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.OrderedEnqueuer
tf.keras.utils.OrderedEnqueuer(
    sequence, use_multiprocessing=False, shuffle=False
)
 Used in fit_generator, evaluate_generator, predict_generator.

 Arguments
  sequence   A tf.keras.utils.data_utils.Sequence object.
  use_multiprocessing   use multiprocessing if True, otherwise threading
  shuffle   whether to shuffle the data at the beginning of each epoch    Methods get View source
get()
 Creates a generator to extract data from the queue. Skip the data if it is None.

 Yields   The next element in the queue, i.e. a tuple (inputs, targets) or (inputs, targets, sample_weights).
 is_running View source
is_running()
 start View source
start(
    workers=1, max_queue_size=10
)
 Starts the handler's workers.

 Arguments
  workers   Number of workers.
  max_queue_size   queue size (when full, workers could block on put())    stop View source
stop(
    timeout=None
)
 Stops running threads and wait for them to exit, if necessary. Should be called by the same thread which called start().

 Arguments
  timeout   maximum time to wait on thread.join()


tf.keras.utils.pack_x_y_sample_weight Packs user-provided data into a tuple.
tf.keras.utils.pack_x_y_sample_weight(
    x, y=None, sample_weight=None
)
 This is a convenience utility for packing data into the tuple formats that Model.fit uses. Standalone usage:
x = tf.ones((10, 1))
data = tf.keras.utils.pack_x_y_sample_weight(x)
isinstance(data, tf.Tensor)
True
y = tf.ones((10, 1))
data = tf.keras.utils.pack_x_y_sample_weight(x, y)
isinstance(data, tuple)
True
x, y = data

 Arguments
  x   Features to pass to Model.
  y   Ground-truth targets to pass to Model.
  sample_weight   Sample weight for each element.

 Returns   Tuple in the format used in Model.fit.


tf.keras.utils.plot_model     View source on GitHub    Converts a Keras model to dot format and save to a file.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.plot_model
tf.keras.utils.plot_model(
    model, to_file='model.png', show_shapes=False, show_dtype=False,
    show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96
)
 Example: input = tf.keras.Input(shape=(100,), dtype='int32', name='input')
x = tf.keras.layers.Embedding(
    output_dim=512, input_dim=10000, input_length=100)(input)
x = tf.keras.layers.LSTM(32)(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.keras.layers.Dense(64, activation='relu')(x)
output = tf.keras.layers.Dense(1, activation='sigmoid', name='output')(x)
model = tf.keras.Model(inputs=[input], outputs=[output])
dot_img_file = '/tmp/model_1.png'
tf.keras.utils.plot_model(model, to_file=dot_img_file, show_shapes=True)

 Arguments
  model   A Keras model instance
  to_file   File name of the plot image.
  show_shapes   whether to display shape information.
  show_dtype   whether to display layer dtypes.
  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   Dots per inch.

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


tf.keras.utils.Progbar     View source on GitHub    Displays a progress bar.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.Progbar
tf.keras.utils.Progbar(
    target, width=30, verbose=1, interval=0.05, stateful_metrics=None,
    unit_name='step'
)

 Arguments
  target   Total number of steps expected, None if unknown.
  width   Progress bar width on screen.
  verbose   Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)
  stateful_metrics   Iterable of string names of metrics that should not be averaged over time. Metrics in this list will be displayed as-is. All others will be averaged by the progbar before display.
  interval   Minimum visual progress update interval (in seconds).
  unit_name   Display name for step counts (usually "step" or "sample").    Methods add View source
add(
    n, values=None
)
 update View source
update(
    current, values=None, finalize=None
)
 Updates the progress bar.

 Arguments
  current   Index of current step.
  values   List of tuples: (name, value_for_last_step). If name is in stateful_metrics, value_for_last_step will be displayed as-is. Else, an average of the metric over time will be displayed.
  finalize   Whether this is the last update for the progress bar. If None, defaults to current >= self.target.


tf.keras.utils.register_keras_serializable Registers an object with the Keras serialization framework.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.register_keras_serializable
tf.keras.utils.register_keras_serializable(
    package='Custom', name=None
)
 This decorator injects the decorated class or function into the Keras custom object dictionary, so that it can be serialized and deserialized without needing an entry in the user-provided custom object dict. It also injects a function that Keras will call to get the object's serializable string key. Note that to be serialized and deserialized, classes must implement the get_config() method. Functions do not have this requirement. The object will be registered under the key 'package>name' where name, defaults to the object name if not passed.

 Arguments
  package   The package that this class belongs to.
  name   The name to serialize this class under in this package. If None, the class' name will be used.

 Returns   A decorator that registers the decorated class with the passed names.


tf.keras.utils.Sequence     View source on GitHub    Base object for fitting to a sequence of data, such as a dataset.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.Sequence  Every Sequence must implement the __getitem__ and the __len__ methods. If you want to modify your dataset between epochs you may implement on_epoch_end. The method __getitem__ should return a complete batch. Notes: Sequence are a safer way to do multiprocessing. This structure guarantees that the network will only train once on each sample per epoch which is not the case with generators. Examples: from skimage.io import imread
from skimage.transform import resize
import numpy as np
import math

# 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 math.ceil(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)
 Methods on_epoch_end View source
on_epoch_end()
 Method called at the end of every epoch. __getitem__ View source
__getitem__(
    index
)
 Gets batch at position index.

 Arguments
  index   position of the batch in the Sequence.

 Returns   A batch
 __iter__ View source
__iter__()
 Create a generator that iterate over the Sequence. __len__ View source
__len__()
 Number of batch in the Sequence.

 Returns   The number of batches in the Sequence.


tf.keras.utils.SequenceEnqueuer     View source on GitHub    Base class to enqueue inputs.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.SequenceEnqueuer
tf.keras.utils.SequenceEnqueuer(
    sequence, use_multiprocessing=False
)
 The task of an Enqueuer is to use parallelism to speed up preprocessing. This is done with processes or threads. Example: enqueuer = SequenceEnqueuer(...)
enqueuer.start()
datas = enqueuer.get()
for data in datas:
    # Use the inputs; training, evaluating, predicting.
    # ... stop sometime.
enqueuer.stop()
 The enqueuer.get() should be an infinite stream of datas. Methods get View source
get()
 Creates a generator to extract data from the queue. Skip the data if it is None. Returns: Generator yielding tuples (inputs, targets) or (inputs, targets, sample_weights). is_running View source
is_running()
 start View source
start(
    workers=1, max_queue_size=10
)
 Starts the handler's workers.

 Arguments
  workers   Number of workers.
  max_queue_size   queue size (when full, workers could block on put())    stop View source
stop(
    timeout=None
)
 Stops running threads and wait for them to exit, if necessary. Should be called by the same thread which called start().

 Arguments
  timeout   maximum time to wait on thread.join()


tf.keras.utils.serialize_keras_object     View source on GitHub    Serialize a Keras object into a JSON-compatible representation.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.serialize_keras_object
tf.keras.utils.serialize_keras_object(
    instance
)


tf.keras.utils.to_categorical     View source on GitHub    Converts a class vector (integers) to binary class matrix.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.utils.to_categorical
tf.keras.utils.to_categorical(
    y, num_classes=None, dtype='float32'
)
 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. If None, this would be inferred as the (largest number in y) + 1.
  dtype   The data type expected by the input. Default: 'float32'.

 Returns   A binary matrix representation of the input. The classes axis is placed last.
 Example:
a = tf.keras.utils.to_categorical([0, 1, 2, 3], num_classes=4)
a = tf.constant(a, shape=[4, 4])
print(a)
tf.Tensor(
  [[1. 0. 0. 0.]
   [0. 1. 0. 0.]
   [0. 0. 1. 0.]
   [0. 0. 0. 1.]], shape=(4, 4), dtype=float32)

b = tf.constant([.9, .04, .03, .03,
                 .3, .45, .15, .13,
                 .04, .01, .94, .05,
                 .12, .21, .5, .17],
                shape=[4, 4])
loss = tf.keras.backend.categorical_crossentropy(a, b)
print(np.around(loss, 5))
[0.10536 0.82807 0.1011  1.77196]

loss = tf.keras.backend.categorical_crossentropy(a, a)
print(np.around(loss, 5))
[0. 0. 0. 0.]

 Raises   Value Error: If input contains string value


tf.keras.utils.unpack_x_y_sample_weight Unpacks user-provided data tuple.
tf.keras.utils.unpack_x_y_sample_weight(
    data
)
 This is a convenience utility to be used when overriding Model.train_step, Model.test_step, or Model.predict_step. This utility makes it easy to support data of the form (x,), (x, y), or (x, y, sample_weight). Standalone usage:
features_batch = tf.ones((10, 5))
labels_batch = tf.zeros((10, 5))
data = (features_batch, labels_batch)
# `y` and `sample_weight` will default to `None` if not provided.
x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)
sample_weight is None
True
 Example in overridden Model.train_step: class MyModel(tf.keras.Model):

  def train_step(self, data):
    # If `sample_weight` is not provided, all samples will be weighted
    # equally.
    x, y, sample_weight = tf.keras.utils.unpack_x_y_sample_weight(data)

    with tf.GradientTape() as tape:
      y_pred = self(x, training=True)
      loss = self.compiled_loss(
        y, y_pred, sample_weight, regularization_losses=self.losses)
      trainable_variables = self.trainable_variables
      gradients = tape.gradient(loss, trainable_variables)
      self.optimizer.apply_gradients(zip(gradients, trainable_variables))

    self.compiled_metrics.update_state(y, y_pred, sample_weight)
    return {m.name: m.result() for m in self.metrics}

 Arguments
  data   A tuple of the form (x,), (x, y), or (x, y, sample_weight).

 Returns   The unpacked tuple, with Nones for y and sample_weight if they are not provided.


Module: tf.keras.wrappers Public API for tf.keras.wrappers namespace. Modules scikit_learn module: Wrapper for using the Scikit-Learn API with Keras models.


Module: tf.keras.wrappers.scikit_learn Wrapper for using the Scikit-Learn API with Keras models. Classes class KerasClassifier: Implementation of the scikit-learn classifier API for Keras. class KerasRegressor: Implementation of the scikit-learn regressor API for Keras.


tf.keras.wrappers.scikit_learn.KerasClassifier     View source on GitHub    Implementation of the scikit-learn classifier API for Keras.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.wrappers.scikit_learn.KerasClassifier
tf.keras.wrappers.scikit_learn.KerasClassifier(
    build_fn=None, **sk_params
)
 Methods check_params View source
check_params(
    params
)
 Checks for user typos in params.

 Arguments
  params   dictionary; the parameters to be checked

 Raises
  ValueError   if any member of params is not a valid argument.    filter_sk_params View source
filter_sk_params(
    fn, override=None
)
 Filters sk_params and returns those in fn's arguments.

 Arguments
  fn   arbitrary function
  override   dictionary, values to override sk_params

 Returns
  res   dictionary containing variables in both sk_params and fn's arguments.    fit View source
fit(
    x, y, **kwargs
)
 Constructs a new model with build_fn & fit the model to (x, y).

 Arguments
  x   array-like, shape (n_samples, n_features) Training samples where n_samples is the number of samples and n_features is the number of features.
  y   array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.fit

 Returns
  history   object details about the training history at each epoch.

 Raises
  ValueError   In case of invalid shape for y argument.    get_params View source
get_params(
    **params
)
 Gets parameters for this estimator.

 Arguments
  **params   ignored (exists for API compatibility).

 Returns   Dictionary of parameter names mapped to their values.
 predict View source
predict(
    x, **kwargs
)
 Returns the class predictions for the given test data.

 Arguments
  x   array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.predict_classes.

 Returns
  preds   array-like, shape (n_samples,) Class predictions.    predict_proba View source
predict_proba(
    x, **kwargs
)
 Returns class probability estimates for the given test data.

 Arguments
  x   array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.predict_classes.

 Returns
  proba   array-like, shape (n_samples, n_outputs) Class probability estimates. In the case of binary classification, to match the scikit-learn API, will return an array of shape (n_samples, 2) (instead of (n_sample, 1) as in Keras).    score View source
score(
    x, y, **kwargs
)
 Returns the mean accuracy on the given test data and labels.

 Arguments
  x   array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
  y   array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.evaluate.

 Returns
  score   float Mean accuracy of predictions on x wrt. y.

 Raises
  ValueError   If the underlying model isn't configured to compute accuracy. You should pass metrics=["accuracy"] to the .compile() method of the model.    set_params View source
set_params(
    **params
)
 Sets the parameters of this estimator.

 Arguments
  **params   Dictionary of parameter names mapped to their values.

 Returns   self


tf.keras.wrappers.scikit_learn.KerasRegressor     View source on GitHub    Implementation of the scikit-learn regressor API for Keras.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.wrappers.scikit_learn.KerasRegressor
tf.keras.wrappers.scikit_learn.KerasRegressor(
    build_fn=None, **sk_params
)
 Methods check_params View source
check_params(
    params
)
 Checks for user typos in params.

 Arguments
  params   dictionary; the parameters to be checked

 Raises
  ValueError   if any member of params is not a valid argument.    filter_sk_params View source
filter_sk_params(
    fn, override=None
)
 Filters sk_params and returns those in fn's arguments.

 Arguments
  fn   arbitrary function
  override   dictionary, values to override sk_params

 Returns
  res   dictionary containing variables in both sk_params and fn's arguments.    fit View source
fit(
    x, y, **kwargs
)
 Constructs a new model with build_fn & fit the model to (x, y).

 Arguments
  x   array-like, shape (n_samples, n_features) Training samples where n_samples is the number of samples and n_features is the number of features.
  y   array-like, shape (n_samples,) or (n_samples, n_outputs) True labels for x.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.fit

 Returns
  history   object details about the training history at each epoch.    get_params View source
get_params(
    **params
)
 Gets parameters for this estimator.

 Arguments
  **params   ignored (exists for API compatibility).

 Returns   Dictionary of parameter names mapped to their values.
 predict View source
predict(
    x, **kwargs
)
 Returns predictions for the given test data.

 Arguments
  x   array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.predict.

 Returns
  preds   array-like, shape (n_samples,) Predictions.    score View source
score(
    x, y, **kwargs
)
 Returns the mean loss on the given test data and labels.

 Arguments
  x   array-like, shape (n_samples, n_features) Test samples where n_samples is the number of samples and n_features is the number of features.
  y   array-like, shape (n_samples,) True labels for x.
  **kwargs   dictionary arguments Legal arguments are the arguments of Sequential.evaluate.

 Returns
  score   float Mean accuracy of predictions on x wrt. y.    set_params View source
set_params(
    **params
)
 Sets the parameters of this estimator.

 Arguments
  **params   Dictionary of parameter names mapped to their values.

 Returns   self


Module: tf.linalg Operations for linear algebra. Modules experimental module: Public API for tf.linalg.experimental namespace. Classes class LinearOperator: Base class defining a [batch of] linear operator[s]. class LinearOperatorAdjoint: LinearOperator representing the adjoint of another operator. class LinearOperatorBlockDiag: Combines one or more LinearOperators in to a Block Diagonal matrix. class LinearOperatorBlockLowerTriangular: Combines LinearOperators into a blockwise lower-triangular matrix. class LinearOperatorCirculant: LinearOperator acting like a circulant matrix. class LinearOperatorCirculant2D: LinearOperator acting like a block circulant matrix. class LinearOperatorCirculant3D: LinearOperator acting like a nested block circulant matrix. class LinearOperatorComposition: Composes one or more LinearOperators. class LinearOperatorDiag: LinearOperator acting like a [batch] square diagonal matrix. class LinearOperatorFullMatrix: LinearOperator that wraps a [batch] matrix. class LinearOperatorHouseholder: LinearOperator acting like a [batch] of Householder transformations. class LinearOperatorIdentity: LinearOperator acting like a [batch] square identity matrix. class LinearOperatorInversion: LinearOperator representing the inverse of another operator. class LinearOperatorKronecker: Kronecker product between two LinearOperators. class LinearOperatorLowRankUpdate: Perturb a LinearOperator with a rank K update. class LinearOperatorLowerTriangular: LinearOperator acting like a [batch] square lower triangular matrix. class LinearOperatorPermutation: LinearOperator acting like a [batch] of permutation matrices. class LinearOperatorScaledIdentity: LinearOperator acting like a scaled [batch] identity matrix A = c I. class LinearOperatorToeplitz: LinearOperator acting like a [batch] of toeplitz matrices. class LinearOperatorTridiag: LinearOperator acting like a [batch] square tridiagonal matrix. class LinearOperatorZeros: LinearOperator acting like a [batch] zero matrix. Functions adjoint(...): Transposes the last two dimensions of and conjugates tensor matrix. band_part(...): Copy a tensor setting everything outside a central band in each innermost matrix to zero. banded_triangular_solve(...): Solve triangular systems of equations with a banded solver. cholesky(...): Computes the Cholesky decomposition of one or more square matrices. cholesky_solve(...): Solves systems of linear eqns A X = RHS, given Cholesky factorizations. cross(...): Compute the pairwise cross product. det(...): Computes the determinant of one or more square matrices. diag(...): Returns a batched diagonal tensor with given batched diagonal values. diag_part(...): Returns the batched diagonal part of a batched tensor. eig(...): Computes the eigen decomposition of a batch of matrices. eigh(...): Computes the eigen decomposition of a batch of self-adjoint matrices. eigvals(...): Computes the eigenvalues of one or more matrices. eigvalsh(...): Computes the eigenvalues of one or more self-adjoint matrices. einsum(...): Tensor contraction over specified indices and outer product. expm(...): Computes the matrix exponential of one or more square matrices. eye(...): Construct an identity matrix, or a batch of matrices. global_norm(...): Computes the global norm of multiple tensors. inv(...): Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes). l2_normalize(...): Normalizes along dimension axis using an L2 norm. logdet(...): Computes log of the determinant of a hermitian positive definite matrix. logm(...): Computes the matrix logarithm of one or more square matrices: lstsq(...): Solves one or more linear least-squares problems. lu(...): Computes the LU decomposition of one or more square matrices. lu_matrix_inverse(...): Computes the inverse given the LU decomposition(s) of one or more matrices. lu_reconstruct(...): The reconstruct one or more matrices from their LU decomposition(s). lu_solve(...): Solves systems of linear eqns A X = RHS, given LU factorizations. matmul(...): Multiplies matrix a by matrix b, producing a * b. matrix_rank(...): Compute the matrix rank of one or more matrices. matrix_transpose(...): Transposes last two dimensions of tensor a. matvec(...): Multiplies matrix a by vector b, producing a * b. norm(...): Computes the norm of vectors, matrices, and tensors. normalize(...): Normalizes tensor along dimension axis using specified norm. pinv(...): Compute the Moore-Penrose pseudo-inverse of one or more matrices. qr(...): Computes the QR decompositions of one or more matrices. set_diag(...): Returns a batched matrix tensor with new batched diagonal values. slogdet(...): Computes the sign and the log of the absolute value of the determinant of solve(...): Solves systems of linear equations. sqrtm(...): Computes the matrix square root of one or more square matrices: svd(...): Computes the singular value decompositions of one or more matrices. tensor_diag(...): Returns a diagonal tensor with a given diagonal values. tensor_diag_part(...): Returns the diagonal part of the tensor. tensordot(...): Tensor contraction of a and b along specified axes and outer product. trace(...): Compute the trace of a tensor x. triangular_solve(...): Solve systems of linear equations with upper or lower triangular matrices. tridiagonal_matmul(...): Multiplies tridiagonal matrix by matrix. tridiagonal_solve(...): Solves tridiagonal systems of equations.


tf.linalg.adjoint     View source on GitHub    Transposes the last two dimensions of and conjugates tensor matrix.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.adjoint
tf.linalg.adjoint(
    matrix, name=None
)
 For example: x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],
                 [4 + 4j, 5 + 5j, 6 + 6j]])
tf.linalg.adjoint(x)  # [[1 - 1j, 4 - 4j],
                      #  [2 - 2j, 5 - 5j],
                      #  [3 - 3j, 6 - 6j]]

 Args
  matrix   A Tensor. Must be float16, float32, float64, complex64, or complex128 with shape [..., M, M].
  name   A name to give this Op (optional).

 Returns   The adjoint (a.k.a. Hermitian transpose a.k.a. conjugate transpose) of matrix.


tf.linalg.banded_triangular_solve Solve triangular systems of equations with a banded solver.
tf.linalg.banded_triangular_solve(
    bands, rhs, lower=True, adjoint=False, name=None
)
 bands is a tensor of shape [..., K, M], where K represents the number of bands stored. This corresponds to a batch of M by M matrices, whose K subdiagonals (when lower is True) are stored. This operator broadcasts the batch dimensions of bands and the batch dimensions of rhs. Examples: Storing 2 bands of a 3x3 matrix. Note that first element in the second row is ignored due to the 'LEFT_RIGHT' padding.
x = [[2., 3., 4.], [1., 2., 3.]]
x2 = [[2., 3., 4.], [10000., 2., 3.]]
y = tf.zeros([3, 3])
z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(-1, 0))
z
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[2., 0., 0.],
       [2., 3., 0.],
       [0., 3., 4.]], dtype=float32)>
soln = tf.linalg.banded_triangular_solve(x, tf.ones([3, 1]))
soln
<tf.Tensor: shape=(3, 1), dtype=float32, numpy=
array([[0.5 ],
       [0.  ],
       [0.25]], dtype=float32)>
are_equal = soln == tf.linalg.banded_triangular_solve(x2, tf.ones([3, 1]))
tf.reduce_all(are_equal).numpy()
True
are_equal = soln == tf.linalg.triangular_solve(z, tf.ones([3, 1]))
tf.reduce_all(are_equal).numpy()
True
 Storing 2 superdiagonals of a 4x4 matrix. Because of the 'LEFT_RIGHT' padding the last element of the first row is ignored.
x = [[2., 3., 4., 5.], [-1., -2., -3., -4.]]
y = tf.zeros([4, 4])
z = tf.linalg.set_diag(y, x, align='LEFT_RIGHT', k=(0, 1))
z
<tf.Tensor: shape=(4, 4), dtype=float32, numpy=
array([[-1.,  2.,  0.,  0.],
       [ 0., -2.,  3.,  0.],
       [ 0.,  0., -3.,  4.],
       [ 0.,  0., -0., -4.]], dtype=float32)>
soln = tf.linalg.banded_triangular_solve(x, tf.ones([4, 1]), lower=False)
soln
<tf.Tensor: shape=(4, 1), dtype=float32, numpy=
array([[-4.       ],
       [-1.5      ],
       [-0.6666667],
       [-0.25     ]], dtype=float32)>
are_equal = (soln == tf.linalg.triangular_solve(
  z, tf.ones([4, 1]), lower=False))
tf.reduce_all(are_equal).numpy()
True

 Args
  bands   A Tensor describing the bands of the left hand side, with shape [..., K, M]. The K rows correspond to the diagonal to the K - 1-th diagonal (the diagonal is the top row) when lower is True and otherwise the K - 1-th superdiagonal to the diagonal (the diagonal is the bottom row) when lower is False. The bands are stored with 'LEFT_RIGHT' alignment, where the superdiagonals are padded on the right and subdiagonals are padded on the left. This is the alignment cuSPARSE uses. See tf.linalg.set_diag for more details.
  rhs   A Tensor of shape [..., M] or [..., M, N] and with the same dtype as diagonals. Note that if the shape of rhs and/or diags isn't known statically, rhs will be treated as a matrix rather than a vector.
  lower   An optional bool. Defaults to True. Boolean indicating whether bands represents a lower or upper triangular matrix.
  adjoint   An optional bool. Defaults to False. Boolean indicating whether to solve with the matrix's block-wise adjoint.
  name   A name to give this Op (optional).

 Returns   A Tensor of shape [..., M] or [..., M, N] containing the solutions.


tf.linalg.band_part Copy a tensor setting everything outside a central band in each innermost matrix to zero.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.band_part, tf.compat.v1.matrix_band_part
tf.linalg.band_part(
    input, num_lower, num_upper, name=None
)
 The band part is computed as follows: Assume input has k dimensions [I, J, K, ..., M, N], then the output is a tensor with the same shape where band[i, j, k, ..., m, n] = in_band(m, n) * input[i, j, k, ..., m, n]. The indicator function in_band(m, n) = (num_lower < 0 || (m-n) <= num_lower)) && (num_upper < 0 || (n-m) <= num_upper). For example: # if 'input' is [[ 0,  1,  2, 3]
                 [-1,  0,  1, 2]
                 [-2, -1,  0, 1]
                 [-3, -2, -1, 0]],

tf.matrix_band_part(input, 1, -1) ==> [[ 0,  1,  2, 3]
                                       [-1,  0,  1, 2]
                                       [ 0, -1,  0, 1]
                                       [ 0,  0, -1, 0]],

tf.matrix_band_part(input, 2, 1) ==> [[ 0,  1,  0, 0]
                                      [-1,  0,  1, 0]
                                      [-2, -1,  0, 1]
                                      [ 0, -2, -1, 0]]
 Useful special cases: tf.matrix_band_part(input, 0, -1) ==> Upper triangular part.
tf.matrix_band_part(input, -1, 0) ==> Lower triangular part.
tf.matrix_band_part(input, 0, 0) ==> Diagonal.

 Args
  input   A Tensor. Rank k tensor.
  num_lower   A Tensor. Must be one of the following types: int32, int64. 0-D tensor. Number of subdiagonals to keep. If negative, keep entire lower triangle.
  num_upper   A Tensor. Must have the same type as num_lower. 0-D tensor. Number of superdiagonals to keep. If negative, keep entire upper triangle.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.linalg.cholesky Computes the Cholesky decomposition of one or more square matrices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cholesky, tf.compat.v1.linalg.cholesky
tf.linalg.cholesky(
    input, name=None
)
 The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The input has to be symmetric and positive definite. Only the lower-triangular part of the input will be used for this operation. The upper-triangular part will not be read. The output is a tensor of the same shape as the input containing the Cholesky decompositions for all input submatrices [..., :, :].
Note: The gradient computation on GPU is faster for large matrices but not for large batch dimensions when the submatrices are small. In this case it might be faster to use the CPU.

 Args
  input   A Tensor. Must be one of the following types: float64, float32, half, complex64, complex128. Shape is [..., M, M].
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.linalg.cholesky_solve     View source on GitHub    Solves systems of linear eqns A X = RHS, given Cholesky factorizations.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cholesky_solve, tf.compat.v1.linalg.cholesky_solve
tf.linalg.cholesky_solve(
    chol, rhs, name=None
)
 Specifically, returns X from A X = RHS, where A = L L^T, L is the chol arg and RHS is the rhs arg. # Solve 10 separate 2x2 linear systems:
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 1
chol = tf.linalg.cholesky(A)  # shape 10 x 2 x 2
X = tf.linalg.cholesky_solve(chol, RHS)  # shape 10 x 2 x 1
# tf.matmul(A, X) ~ RHS
X[3, :, 0]  # Solution to the linear system A[3, :, :] x = RHS[3, :, 0]

# Solve five linear systems (K = 5) for every member of the length 10 batch.
A = ... # shape 10 x 2 x 2
RHS = ... # shape 10 x 2 x 5
...
X[3, :, 2]  # Solution to the linear system A[3, :, :] x = RHS[3, :, 2]

 Args
  chol   A Tensor. Must be float32 or float64, shape is [..., M, M]. Cholesky factorization of A, e.g. chol = tf.linalg.cholesky(A). For that reason, only the lower triangular parts (including the diagonal) of the last two dimensions of chol are used. The strictly upper part is assumed to be zero and not accessed.
  rhs   A Tensor, same type as chol, shape is [..., M, K].
  name   A name to give this Op. Defaults to cholesky_solve.

 Returns   Solution to A x = rhs, shape [..., M, K].


tf.linalg.cross Compute the pairwise cross product.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.cross, tf.compat.v1.linalg.cross
tf.linalg.cross(
    a, b, name=None
)
 a and b must be the same shape; they can either be simple 3-element vectors, or any shape where the innermost dimension is 3. In the latter case, each pair of corresponding 3-element vectors is cross-multiplied independently.

 Args
  a   A Tensor. Must be one of the following types: float32, float64, int32, uint8, int16, int8, int64, bfloat16, uint16, half, uint32, uint64. A tensor containing 3-element vectors.
  b   A Tensor. Must have the same type as a. Another tensor, of same type and shape as a.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as a.


tf.linalg.det Computes the determinant of one or more square matrices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.linalg.det, tf.compat.v1.matrix_determinant
tf.linalg.det(
    input, name=None
)
 The input is a tensor of shape [..., M, M] whose inner-most 2 dimensions form square matrices. The output is a tensor containing the determinants for all input submatrices [..., :, :].

 Args
  input   A Tensor. Must be one of the following types: half, float32, float64, complex64, complex128. Shape is [..., M, M].
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.