Instantiates the EfficientNetB4 architecture.
Main aliases
tf.keras.applications.efficientnet.EfficientNetB4
See Migration guide for more details.
tf.compat.v1.keras.applications.EfficientNetB4, tf.compat.v1.keras.applications.efficientnet.EfficientNetB4
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".


Instantiates the EfficientNetB5 architecture.
Main aliases
tf.keras.applications.efficientnet.EfficientNetB5
See Migration guide for more details.
tf.compat.v1.keras.applications.EfficientNetB5, tf.compat.v1.keras.applications.efficientnet.EfficientNetB5
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".


Instantiates the EfficientNetB6 architecture.
Main aliases
tf.keras.applications.efficientnet.EfficientNetB6
See Migration guide for more details.
tf.compat.v1.keras.applications.EfficientNetB6, tf.compat.v1.keras.applications.efficientnet.EfficientNetB6
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".


Instantiates the EfficientNetB7 architecture.
Main aliases
tf.keras.applications.efficientnet.EfficientNetB7
See Migration guide for more details.
tf.compat.v1.keras.applications.EfficientNetB7, tf.compat.v1.keras.applications.efficientnet.EfficientNetB7
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".


Utilities for ImageNet data preprocessing & prediction decoding.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.imagenet_utils.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.imagenet_utils.preprocess_input
Usage example with applications.MobileNet:


Instantiates the Inception-ResNet v2 architecture.
Main aliases
tf.keras.applications.inception_resnet_v2.InceptionResNetV2
See Migration guide for more details.
tf.compat.v1.keras.applications.InceptionResNetV2, tf.compat.v1.keras.applications.inception_resnet_v2.InceptionResNetV2
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Instantiates the Inception v3 architecture.
Main aliases
tf.keras.applications.inception_v3.InceptionV3
See Migration guide for more details.
tf.compat.v1.keras.applications.InceptionV3, tf.compat.v1.keras.applications.inception_v3.InceptionV3
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in the tf.keras.backend.image_data_format().


Inception-ResNet V2 model for Keras.
InceptionResNetV2(...): Instantiates the Inception-ResNet v2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.inception_resnet_v2.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.inception_resnet_v2.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


Inception V3 model for Keras.
InceptionV3(...): Instantiates the Inception v3 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.inception_v3.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.inception_v3.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


MobileNet v1 models for Keras.
MobileNet is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance. The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 16 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.75, 0.5 and 0.25. For each of these alpha values, weights for 4 different input image sizes are provided (224, 192, 160, 128).
The following table describes the size and accuracy of the 100% MobileNet
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 0.75 MobileNet-224 | 68.4 % | 325 | 2.6 | | 0.50 MobileNet-224 | 63.7 % | 149 | 1.3 |
The following table describes the performance of
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 1.0 MobileNet-192 | 69.1 % | 529 | 4.2 | | 1.0 MobileNet-160 | 67.2 % | 529 | 4.2 |
MobileNet(...): Instantiates the MobileNet architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


Instantiates the MobileNetV2 architecture.
Main aliases
tf.keras.applications.mobilenet_v2.MobileNetV2
See Migration guide for more details.
tf.compat.v1.keras.applications.MobileNetV2, tf.compat.v1.keras.applications.mobilenet_v2.MobileNetV2
Optionally loads weights pre-trained on ImageNet.


Instantiates the MobileNetV3Large architecture.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.MobileNetV3Large
MACs stands for Multiply Adds
The weights for all 6 models are obtained and translated from the Tensorflow checkpoints from TensorFlow checkpoints found here.
Optionally loads weights pre-trained on ImageNet.


Instantiates the MobileNetV3Small architecture.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.MobileNetV3Small
MACs stands for Multiply Adds
The weights for all 6 models are obtained and translated from the Tensorflow checkpoints from TensorFlow checkpoints found here.
Optionally loads weights pre-trained on ImageNet.


MobileNet v2 models for Keras.
MobileNetV2 is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNetV2 is very similar to the original MobileNet, except that it uses inverted residual blocks with bottlenecking features. It has a drastically lower parameter count than the original MobileNet. MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance.
The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 22 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.35, 0.5, 0.75, 1.0, 1.3, and 1.4 For each of these alpha values, weights for 5 different input image sizes are provided (224, 192, 160, 128, and 96).
The following table describes the performance of
MACs stands for Multiply Adds Classification Checkpoint|MACs (M)|Parameters (M)|Top 1 Accuracy|Top 5 Accuracy --------------------------|------------|---------------|---------|----|--------- | [mobilenet_v2_1.4_224] | 582 | 6.06 | 75.0 | 92.5 | | [mobilenet_v2_1.3_224] | 509 | 5.34 | 74.4 | 92.1 | | [mobilenet_v2_1.0_224] | 300 | 3.47 | 71.8 | 91.0 | | [mobilenet_v2_1.0_192] | 221 | 3.47 | 70.7 | 90.1 | | [mobilenet_v2_1.0_160] | 154 | 3.47 | 68.8 | 89.0 | | [mobilenet_v2_1.0_128] | 99 | 3.47 | 65.3 | 86.9 | | [mobilenet_v2_1.0_96] | 56 | 3.47 | 60.3 | 83.2 | | [mobilenet_v2_0.75_224] | 209 | 2.61 | 69.8 | 89.6 | | [mobilenet_v2_0.75_192] | 153 | 2.61 | 68.7 | 88.9 | | [mobilenet_v2_0.75_160] | 107 | 2.61 | 66.4 | 87.3 | | [mobilenet_v2_0.75_128] | 69 | 2.61 | 63.2 | 85.3 | | [mobilenet_v2_0.75_96] | 39 | 2.61 | 58.8 | 81.6 | | [mobilenet_v2_0.5_224] | 97 | 1.95 | 65.4 | 86.4 | | [mobilenet_v2_0.5_192] | 71 | 1.95 | 63.9 | 85.4 | | [mobilenet_v2_0.5_160] | 50 | 1.95 | 61.0 | 83.2 | | [mobilenet_v2_0.5_128] | 32 | 1.95 | 57.7 | 80.8 | | [mobilenet_v2_0.5_96] | 18 | 1.95 | 51.2 | 75.8 | | [mobilenet_v2_0.35_224] | 59 | 1.66 | 60.3 | 82.9 | | [mobilenet_v2_0.35_192] | 43 | 1.66 | 58.2 | 81.2 | | [mobilenet_v2_0.35_160] | 30 | 1.66 | 55.7 | 79.1 | | [mobilenet_v2_0.35_128] | 20 | 1.66 | 50.8 | 75.0 | | [mobilenet_v2_0.35_96] | 11 | 1.66 | 45.5 | 70.4 |
Reference:
MobileNetV2(...): Instantiates the MobileNetV2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet_v2.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet_v2.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


MobileNet v3 models for Keras.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet_v3.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.mobilenet_v3.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


NASNet-A models for Keras.
NASNet refers to Neural Architecture Search Network, a family of models that were designed automatically by learning the model architectures directly on the dataset of interest.
Here we consider NASNet-A, the highest performance model that was found for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset, obtaining state of the art performance on CIFAR-10 and ImageNet 2012. Only the NASNet-A models, and their respective weights, which are suited for ImageNet 2012 are provided.
| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 |
NASNetLarge(...): Instantiates a NASNet model in ImageNet mode.
NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.nasnet.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.nasnet.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


Instantiates a NASNet model in ImageNet mode.
Main aliases
tf.keras.applications.nasnet.NASNetLarge
See Migration guide for more details.
tf.compat.v1.keras.applications.NASNetLarge, tf.compat.v1.keras.applications.nasnet.NASNetLarge
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Instantiates a Mobile NASNet model in ImageNet mode.
Main aliases
tf.keras.applications.nasnet.NASNetMobile
See Migration guide for more details.
tf.compat.v1.keras.applications.NASNetMobile, tf.compat.v1.keras.applications.nasnet.NASNetMobile
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


ResNet models for Keras.
ResNet101(...): Instantiates the ResNet101 architecture.
ResNet152(...): Instantiates the ResNet152 architecture.
ResNet50(...): Instantiates the ResNet50 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Main aliases
tf.keras.applications.resnet50.decode_predictions
See Migration guide for more details.
tf.compat.v1.keras.applications.resnet.decode_predictions, tf.compat.v1.keras.applications.resnet50.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Main aliases
tf.keras.applications.resnet50.preprocess_input
See Migration guide for more details.
tf.compat.v1.keras.applications.resnet.preprocess_input, tf.compat.v1.keras.applications.resnet50.preprocess_input
Usage example with applications.MobileNet:
The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.


Instantiates the ResNet101 architecture.
Main aliases
tf.keras.applications.resnet.ResNet101
See Migration guide for more details.
tf.compat.v1.keras.applications.ResNet101, tf.compat.v1.keras.applications.resnet.ResNet101
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Instantiates the ResNet101V2 architecture.
Main aliases
tf.keras.applications.resnet_v2.ResNet101V2
See Migration guide for more details.
tf.compat.v1.keras.applications.ResNet101V2, tf.compat.v1.keras.applications.resnet_v2.ResNet101V2
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Instantiates the ResNet152 architecture.
Main aliases
tf.keras.applications.resnet.ResNet152
See Migration guide for more details.
tf.compat.v1.keras.applications.ResNet152, tf.compat.v1.keras.applications.resnet.ResNet152
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Instantiates the ResNet152V2 architecture.
Main aliases
tf.keras.applications.resnet_v2.ResNet152V2
See Migration guide for more details.
tf.compat.v1.keras.applications.ResNet152V2, tf.compat.v1.keras.applications.resnet_v2.ResNet152V2
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


Public API for tf.keras.applications.resnet50 namespace.
ResNet50(...): Instantiates the ResNet50 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Instantiates the ResNet50V2 architecture.
Main aliases
tf.keras.applications.resnet_v2.ResNet50V2
See Migration guide for more details.
tf.compat.v1.keras.applications.ResNet50V2, tf.compat.v1.keras.applications.resnet_v2.ResNet50V2
Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.


ResNet v2 models for Keras.
ResNet101V2(...): Instantiates the ResNet101V2 architecture.
ResNet152V2(...): Instantiates the ResNet152V2 architecture.
ResNet50V2(...): Instantiates the ResNet50V2 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.resnet_v2.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.resnet_v2.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


VGG16 model for Keras.
VGG16(...): Instantiates the VGG16 model.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.vgg16.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.vgg16.preprocess_input
Usage example with applications.MobileNet:
The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.


VGG19 model for Keras.
VGG19(...): Instantiates the VGG19 architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.vgg19.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.vgg19.preprocess_input
Usage example with applications.MobileNet:
The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.


Xception V1 model for Keras.
On ImageNet, this model gets to a top-1 validation accuracy of 0.790 and a top-5 validation accuracy of 0.945.
Xception(...): Instantiates the Xception architecture.
decode_predictions(...): Decodes the prediction of an ImageNet model.
preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images.


Decodes the prediction of an ImageNet model.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.xception.decode_predictions


Preprocesses a tensor or Numpy array encoding a batch of images.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.applications.xception.preprocess_input
Usage example with applications.MobileNet:
The inputs pixel values are scaled between -1 and 1, sample-wise.


Keras backend API.
clear_session(...): Resets all state generated by Keras.
epsilon(...): Returns the value of the fuzz factor used in numeric expressions.
floatx(...): Returns the default float type, as a string.
get_uid(...): Associates a string prefix with an integer counter in a TensorFlow graph.
image_data_format(...): Returns the default image data format convention.
is_keras_tensor(...): Returns whether x is a Keras tensor.
reset_uids(...): Resets graph identifiers.
rnn(...): Iterates over the time dimension of a tensor.
set_epsilon(...): Sets the value of the fuzz factor used in numeric expressions.
set_floatx(...): Sets the default float type.
set_image_data_format(...): Sets the value of the image data format convention.


Resets all state generated by Keras.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.clear_session
Keras manages a global state, which it uses to implement the Functional model-building API and to uniquify autogenerated layer names.
If you are creating many models in a loop, this global state will consume an increasing amount of memory over time, and you may want to clear it. Calling clear_session() releases the global state: this helps avoid clutter from old models and layers, especially when memory is limited.
Example 1: calling clear_session() when creating models in a loop
Example 2: resetting the layer name generation counter


Returns the value of the fuzz factor used in numeric expressions.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.epsilon


Returns the default float type, as a string.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.floatx
E.g. 'float16', 'float32', 'float64'.


Associates a string prefix with an integer counter in a TensorFlow graph.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.get_uid


Returns the default image data format convention.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.image_data_format


Returns whether x is a Keras tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.is_keras_tensor
A "Keras tensor" is a tensor that was returned by a Keras layer, (Layer class) or by Input.


Resets graph identifiers.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.reset_uids


Iterates over the time dimension of a tensor.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.rnn


Sets the value of the fuzz factor used in numeric expressions.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.set_epsilon


Sets the default float type.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.set_floatx


Sets the value of the image data format convention.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.backend.set_image_data_format


Callbacks: utilities called at certain points during model training.
experimental module: Public API for tf.keras.callbacks.experimental namespace.
class BaseLogger: Callback that accumulates epoch averages of metrics.
class CSVLogger: Callback that streams epoch results to a CSV file.
class Callback: Abstract base class used to build new callbacks.
class CallbackList: Container abstracting a list of callbacks.
class EarlyStopping: Stop training when a monitored metric has stopped improving.
class History: Callback that records events into a History object.
class LambdaCallback: Callback for creating simple, custom callbacks on-the-fly.
class LearningRateScheduler: Learning rate scheduler.
class ModelCheckpoint: Callback to save the Keras model or model weights at some frequency.
class ProgbarLogger: Callback that prints metrics to stdout.
class ReduceLROnPlateau: Reduce learning rate when a metric has stopped improving.
class RemoteMonitor: Callback used to stream events to a server.
class TensorBoard: Enable visualizations for TensorBoard.
class TerminateOnNaN: Callback that terminates training when a NaN loss is encountered.


Callback that accumulates epoch averages of metrics.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.BaseLogger
This callback is automatically applied to every Keras model.
View source
View source


Abstract base class used to build new callbacks.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.Callback
The logs dictionary that callback methods take as argument will contain keys for quantities relevant to the current batch or epoch (see method-specific docstrings).
View source
A backwards compatibility alias for on_train_batch_begin.
View source
A backwards compatibility alias for on_train_batch_end.
View source
Called at the start of an epoch.
Subclasses should override for any actions to run. This function should only be called during TRAIN mode.
View source
Called at the end of an epoch.
Subclasses should override for any actions to run. This function should only be called during TRAIN mode.
View source
Called at the beginning of a batch in predict methods.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the end of a batch in predict methods.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the beginning of prediction.
Subclasses should override for any actions to run.
View source
Called at the end of prediction.
Subclasses should override for any actions to run.
View source
Called at the beginning of a batch in evaluate methods.
Also called at the beginning of a validation batch in the fit methods, if validation data is provided.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the end of a batch in evaluate methods.
Also called at the end of a validation batch in the fit methods, if validation data is provided.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the beginning of evaluation or validation.
Subclasses should override for any actions to run.
View source
Called at the end of evaluation or validation.
Subclasses should override for any actions to run.
View source
Called at the beginning of a training batch in fit methods.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the end of a training batch in fit methods.
Subclasses should override for any actions to run.
Note that if the steps_per_execution argument to compile in tf.keras.Model is set to N, this method will only be called every N batches.
View source
Called at the beginning of training.
Subclasses should override for any actions to run.
View source
Called at the end of training.
Subclasses should override for any actions to run.
View source
View source


Container abstracting a list of callbacks.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.CallbackList
View source
View source
View source
View source
Calls the on_epoch_begin methods of its callbacks.
This function should only be called during TRAIN mode.
View source
Calls the on_epoch_end methods of its callbacks.
This function should only be called during TRAIN mode.
View source
Calls the on_predict_batch_begin methods of its callbacks.
View source
Calls the on_predict_batch_end methods of its callbacks.
View source
Calls the 'on_predict_begin` methods of its callbacks.
View source
Calls the on_predict_end methods of its callbacks.
View source
Calls the on_test_batch_begin methods of its callbacks.
View source
Calls the on_test_batch_end methods of its callbacks.
View source
Calls the on_test_begin methods of its callbacks.
View source
Calls the on_test_end methods of its callbacks.
View source
Calls the on_train_batch_begin methods of its callbacks.
View source
Calls the on_train_batch_end methods of its callbacks.
View source
Calls the on_train_begin methods of its callbacks.
View source
Calls the on_train_end methods of its callbacks.
View source
View source
View source


Callback that streams epoch results to a CSV file.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.CSVLogger
Supports all values that can be represented as a string, including 1D iterables such as np.ndarray.
View source
View source


Stop training when a monitored metric has stopped improving.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.EarlyStopping
Assuming the goal of a training is to minimize the loss. With this, the metric to be monitored would be 'loss', and mode would be 'min'. A model.fit() training loop will check at end of every epoch whether the loss is no longer decreasing, considering the min_delta and patience if applicable. Once it's found no longer decreasing, model.stop_training is marked True and the training terminates.
The quantity to be monitored needs to be available in logs dict. To make it so, pass the loss or metrics at model.compile().
View source
View source
View source


Public API for tf.keras.callbacks.experimental namespace.
class BackupAndRestore: Callback to back up and restore the training state.


Callback to back up and restore the training state.
Inherits From: Callback
BackupAndRestore callback is intended to recover from interruptions that happened in the middle of a model.fit execution by backing up the training states in a temporary checkpoint file (based on TF CheckpointManager) at the end of each epoch. If training restarted before completion, the training state and model are restored to the most recently saved state at the beginning of a new model.fit() run. Note that user is responsible to bring jobs back up. This callback is important for the backup and restore mechanism for fault tolerance purpose. And the model to be restored from an previous checkpoint is expected to be the same as the one used to back up. If user changes arguments passed to compile or fit, the checkpoint saved for fault tolerance can become invalid.
View source
View source


Callback that records events into a History object.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.History
This callback is automatically applied to every Keras model. The History object gets returned by the fit method of models.
View source
View source


Callback for creating simple, custom callbacks on-the-fly.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.LambdaCallback
This callback is constructed with anonymous functions that will be called at the appropriate time. Note that the callbacks expects positional arguments, as:
View source
View source


Learning rate scheduler.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.LearningRateScheduler
At the beginning of every epoch, this callback gets the updated learning rate value from schedule function provided at __init__, with the current epoch and current learning rate, and applies the updated learning rate on the optimizer.
View source
View source


Callback to save the Keras model or model weights at some frequency.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.ModelCheckpoint
ModelCheckpoint callback is used in conjunction with training using model.fit() to save a model or weights (in a checkpoint file) at some interval, so the model or weights can be loaded later to continue the training from the state saved.
A few options this callback provides include:
View source
View source


Callback that prints metrics to stdout.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.ProgbarLogger
View source
View source


Reduce learning rate when a metric has stopped improving.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.ReduceLROnPlateau
Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a 'patience' number of epochs, the learning rate is reduced.
View source
View source
View source


Callback used to stream events to a server.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.RemoteMonitor
Requires the requests library. Events are sent to root + '/publish/epoch/end/' by default. Calls are HTTP POST, with a data argument which is a JSON-encoded dictionary of event data. If send_as_json=True, the content type of the request will be "application/json". Otherwise the serialized JSON will be sent within a form.
View source
View source


Enable visualizations for TensorBoard.
Inherits From: Callback
TensorBoard is a visualization tool provided with TensorFlow.
This callback logs events for TensorBoard, including:
If you have installed TensorFlow with pip, you should be able to launch TensorBoard from the command line:
You can find more information about TensorBoard here.
Custom batch-level summaries in a subclassed Model:
Custom batch-level summaries in a Functional API Model:
View source
Sets Keras model and writes graph if specified.
View source


Callback that terminates training when a NaN loss is encountered.
Inherits From: Callback
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.callbacks.TerminateOnNaN
View source
View source


Constraints: functions that impose constraints on weight values.
class Constraint
class MaxNorm: MaxNorm weight constraint.
class MinMaxNorm: MinMaxNorm weight constraint.
class NonNeg: Constrains the weights to be non-negative.
class RadialConstraint: Constrains Conv2D kernel weights to be the same for each radius.
class UnitNorm: Constrains the weights incident to each hidden unit to have unit norm.
class max_norm: MaxNorm weight constraint.
class min_max_norm: MinMaxNorm weight constraint.
class non_neg: Constrains the weights to be non-negative.
class radial_constraint: Constrains Conv2D kernel weights to be the same for each radius.
class unit_norm: Constrains the weights incident to each hidden unit to have unit norm.
deserialize(...)
get(...)
serialize(...)


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.constraints.Constraint
View source
View source
Call self as a function.


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.constraints.deserialize


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.constraints.get


MaxNorm weight constraint.
Inherits From: Constraint
Main aliases
tf.keras.constraints.max_norm
See Migration guide for more details.
tf.compat.v1.keras.constraints.MaxNorm, tf.compat.v1.keras.constraints.max_norm
Constrains the weights incident to each hidden unit to have a norm less than or equal to a desired value.
Also available via the shortcut function tf.keras.constraints.max_norm.


MinMaxNorm weight constraint.
Inherits From: Constraint
Main aliases
tf.keras.constraints.min_max_norm
See Migration guide for more details.
tf.compat.v1.keras.constraints.MinMaxNorm, tf.compat.v1.keras.constraints.min_max_norm
Constrains the weights incident to each hidden unit to have the norm between a lower bound and an upper bound.
Also available via the shortcut function tf.keras.constraints.min_max_norm.


Constrains the weights to be non-negative.
Inherits From: Constraint
Main aliases
tf.keras.constraints.non_neg
See Migration guide for more details.
tf.compat.v1.keras.constraints.NonNeg, tf.compat.v1.keras.constraints.non_neg
Also available via the shortcut function tf.keras.constraints.non_neg.
View source
View source
Call self as a function.


Constrains Conv2D kernel weights to be the same for each radius.
Inherits From: Constraint
Main aliases
tf.keras.constraints.radial_constraint
See Migration guide for more details.
tf.compat.v1.keras.constraints.RadialConstraint, tf.compat.v1.keras.constraints.radial_constraint
Also available via the shortcut function tf.keras.constraints.radial_constraint.
For example, the desired output for the following 4-by-4 kernel:
is this::
This constraint can be applied to any Conv2D layer version, including Conv2DTranspose and SeparableConv2D, and with either "channels_last" or "channels_first" data format. The method assumes the weight tensor is of shape (rows, cols, input_depth, output_depth).
View source


Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.constraints.serialize


Constrains the weights incident to each hidden unit to have unit norm.
Inherits From: Constraint
Main aliases
tf.keras.constraints.unit_norm
See Migration guide for more details.
tf.compat.v1.keras.constraints.UnitNorm, tf.compat.v1.keras.constraints.unit_norm
Also available via the shortcut function tf.keras.constraints.unit_norm.


Public API for tf.keras.datasets namespace.
boston_housing module: Boston housing price regression dataset.
cifar10 module: CIFAR10 small images classification dataset.
cifar100 module: CIFAR100 small images classification dataset.
fashion_mnist module: Fashion-MNIST dataset.
imdb module: IMDB sentiment classification dataset.
mnist module: MNIST handwritten digits dataset.
reuters module: Reuters topic classification dataset.


Boston housing price regression dataset.
load_data(...): Loads the Boston Housing dataset.


Loads the Boston Housing dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.boston_housing.load_data
This is a dataset taken from the StatLib library which is maintained at Carnegie Mellon University.
Samples contain 13 attributes of houses at different locations around the Boston suburbs in the late 1970s. Targets are the median values of the houses at a location (in k$).
The attributes themselves are defined in the StatLib website.
x_train, x_test: numpy arrays with shape (num_samples, 13) containing either the training samples (for x_train), or test samples (for y_train).
y_train, y_test: numpy arrays of shape (num_samples,) containing the target scalars. The targets are float scalars typically between 10 and 50 that represent the home prices in k$.


CIFAR10 small images classification dataset.
load_data(...): Loads CIFAR10 dataset.


Loads CIFAR10 dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.cifar10.load_data
This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 10 categories. See more info at the CIFAR homepage.
x_train, x_test: uint8 arrays of RGB image data with shape (num_samples, 3, 32, 32) if tf.keras.backend.image_data_format() is 'channels_first', or (num_samples, 32, 32, 3) if the data format is 'channels_last'.
y_train, y_test: uint8 arrays of category labels (integers in range 0-9) each with shape (num_samples, 1).


CIFAR100 small images classification dataset.
load_data(...): Loads CIFAR100 dataset.


Loads CIFAR100 dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.cifar100.load_data
This is a dataset of 50,000 32x32 color training images and 10,000 test images, labeled over 100 fine-grained classes that are grouped into 20 coarse-grained classes. See more info at the CIFAR homepage.
x_train, x_test: uint8 arrays of RGB image data with shape (num_samples, 3, 32, 32) if tf.keras.backend.image_data_format() is 'channels_first', or (num_samples, 32, 32, 3) if the data format is 'channels_last'.
y_train, y_test: uint8 arrays of category labels with shape (num_samples, 1).


Fashion-MNIST dataset.
load_data(...): Loads the Fashion-MNIST dataset.


Loads the Fashion-MNIST dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.fashion_mnist.load_data
This is a dataset of 60,000 28x28 grayscale images of 10 fashion categories, along with a test set of 10,000 images. This dataset can be used as a drop-in replacement for MNIST. The class labels are:
x_train, x_test: uint8 arrays of grayscale image data with shape (num_samples, 28, 28).
y_train, y_test: uint8 arrays of labels (integers in range 0-9) with shape (num_samples,).
The copyright for Fashion-MNIST is held by Zalando SE. Fashion-MNIST is licensed under the MIT license.


IMDB sentiment classification dataset.
get_word_index(...): Retrieves a dict mapping words to their index in the IMDB dataset.
load_data(...): Loads the IMDB dataset.


Retrieves a dict mapping words to their index in the IMDB dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.imdb.get_word_index


Loads the IMDB dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.imdb.load_data
This is a dataset of 25,000 movies reviews from IMDB, labeled by sentiment (positive/negative). Reviews have been preprocessed, and each review is encoded as a list of word indexes (integers). For convenience, words are indexed by overall frequency in the dataset, so that for instance the integer "3" encodes the 3rd most frequent word in the data. This allows for quick filtering operations such as: "only consider the top 10,000 most common words, but eliminate the top 20 most common words".
As a convention, "0" does not stand for a specific word, but instead is used to encode any unknown word.
x_train, x_test: lists of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words - 1. If the maxlen argument was specified, the largest possible sequence length is maxlen.
y_train, y_test: lists of integer labels (1 or 0).
Note that the 'out of vocabulary' character is only used for words that were present in the training set but are not included because they're not making the num_words cut here. Words that were not seen in the training set but are in the test set have simply been skipped.


MNIST handwritten digits dataset.
load_data(...): Loads the MNIST dataset.


Loads the MNIST dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.mnist.load_data
This is a dataset of 60,000 28x28 grayscale images of the 10 digits, along with a test set of 10,000 images. More info can be found at the MNIST homepage.
x_train, x_test: uint8 arrays of grayscale image data with shapes (num_samples, 28, 28).
y_train, y_test: uint8 arrays of digit labels (integers in range 0-9) with shapes (num_samples,).
Yann LeCun and Corinna Cortes hold the copyright of MNIST dataset, which is a derivative work from original NIST datasets. MNIST dataset is made available under the terms of the Creative Commons Attribution-Share Alike 3.0 license.


Reuters topic classification dataset.
get_word_index(...): Retrieves a dict mapping words to their index in the Reuters dataset.
load_data(...): Loads the Reuters newswire classification dataset.


Retrieves a dict mapping words to their index in the Reuters dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.reuters.get_word_index


Loads the Reuters newswire classification dataset.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.datasets.reuters.load_data
This is a dataset of 11,228 newswires from Reuters, labeled over 46 topics.
This was originally generated by parsing and preprocessing the classic Reuters-21578 dataset, but the preprocessing code is no longer packaged with Keras. See this github discussion for more info.
Each newswire is encoded as a list of word indexes (integers). For convenience, words are indexed by overall frequency in the dataset, so that for instance the integer "3" encodes the 3rd most frequent word in the data. This allows for quick filtering operations such as: "only consider the top 10,000 most common words, but eliminate the top 20 most common words".
As a convention, "0" does not stand for a specific word, but instead is used to encode any unknown word.
x_train, x_test: lists of sequences, which are lists of indexes (integers). If the num_words argument was specific, the maximum possible index value is num_words - 1. If the maxlen argument was specified, the largest possible sequence length is maxlen.
y_train, y_test: lists of integer labels (1 or 0).


Keras estimator API.
model_to_estimator(...): Constructs an Estimator instance from given keras model.


Constructs an Estimator instance from given keras model.
If you use infrastructure or other tooling that relies on Estimators, you can still build a Keras model and use model_to_estimator to convert the Keras model to an Estimator for use with downstream systems.
For usage example, please see: Creating estimators from Keras Models.
Estimators returned by model_to_estimator are configured so that they can handle sample weights (similar to keras_model.fit(x, y, sample_weights)).
To pass sample weights when training or evaluating the Estimator, the first item returned by the input function should be a dictionary with keys features and sample_weights. Example below:
Example with customized export signature:
To customize the estimator eval_metric_ops names, you can pass in the metric_names_map dictionary mapping the keras model output metric names to the custom names as follows:


Public API for tf.keras.experimental namespace.
class CosineDecay: A LearningRateSchedule that uses a cosine decay schedule.
class CosineDecayRestarts: A LearningRateSchedule that uses a cosine decay schedule with restarts.
class LinearCosineDecay: A LearningRateSchedule that uses a linear cosine decay schedule.
class LinearModel: Linear Model for regression and classification problems.
class NoisyLinearCosineDecay: A LearningRateSchedule that uses a noisy linear cosine decay schedule.
class PeepholeLSTMCell: Equivalent to LSTMCell class but adds peephole connections.
class SequenceFeatures: A layer for sequence input.
class WideDeepModel: Wide & Deep Model for regression and classification problems.


A LearningRateSchedule that uses a cosine decay schedule.
Inherits From: LearningRateSchedule
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.CosineDecay
See [Loshchilov & Hutter, ICLR2016], SGDR: Stochastic Gradient Descent with Warm Restarts. https://arxiv.org/abs/1608.03983
When training a model, it is often recommended to lower the learning rate as the training progresses. This schedule applies a cosine decay function to an optimizer step, given a provided initial learning rate. It requires a step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.
The schedule a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. It is computed as:
You can pass this schedule directly into a tf.keras.optimizers.Optimizer as the learning rate. The learning rate schedule is also serializable and deserializable using tf.keras.optimizers.schedules.serialize and tf.keras.optimizers.schedules.deserialize.
View source
Instantiates a LearningRateSchedule from its config.
View source
View source
Call self as a function.


A LearningRateSchedule that uses a cosine decay schedule with restarts.
Inherits From: LearningRateSchedule
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.CosineDecayRestarts
See [Loshchilov & Hutter, ICLR2016], SGDR: Stochastic Gradient Descent with Warm Restarts. https://arxiv.org/abs/1608.03983
When training a model, it is often recommended to lower the learning rate as the training progresses. This schedule applies a cosine decay function with restarts to an optimizer step, given a provided initial learning rate. It requires a step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.
The schedule a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions.
The learning rate multiplier first decays from 1 to alpha for first_decay_steps steps. Then, a warm restart is performed. Each new warm restart runs for t_mul times more steps and with m_mul times smaller initial learning rate.
You can pass this schedule directly into a tf.keras.optimizers.Optimizer as the learning rate. The learning rate schedule is also serializable and deserializable using tf.keras.optimizers.schedules.serialize and tf.keras.optimizers.schedules.deserialize.
View source
Instantiates a LearningRateSchedule from its config.
View source
View source
Call self as a function.


A LearningRateSchedule that uses a linear cosine decay schedule.
Inherits From: LearningRateSchedule
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.LinearCosineDecay
See [Bello et al., ICML2017] Neural Optimizer Search with RL. https://arxiv.org/abs/1709.07417
For the idea of warm starts here controlled by num_periods, see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent with Warm Restarts. https://arxiv.org/abs/1608.03983
Note that linear cosine decay is more aggressive than cosine decay and larger initial learning rates can typically be used.
When training a model, it is often recommended to lower the learning rate as the training progresses. This schedule applies a linear cosine decay function to an optimizer step, given a provided initial learning rate. It requires a step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.
The schedule a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. It is computed as:
You can pass this schedule directly into a tf.keras.optimizers.Optimizer as the learning rate. The learning rate schedule is also serializable and deserializable using tf.keras.optimizers.schedules.serialize and tf.keras.optimizers.schedules.deserialize.
View source
Instantiates a LearningRateSchedule from its config.
View source
View source
Call self as a function.


Linear Model for regression and classification problems.
Inherits From: Model, Layer, Module
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.LinearModel
This model approximates the following function:
where
is the bias and
is the weight for each feature.
This model accepts sparse float inputs as well:
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.
View source
Configures the model for training.
View source
Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the batch_size arg.)
See the discussion of Unpacking behavior for iterator-like inputs for Model.fit.
View source
Evaluates the model on a data generator.
Model.evaluate now supports generators, so there is no longer any need to use this endpoint.
View source
Trains the model for a fixed number of epochs (iterations on a dataset).
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.)
View source
Fits the model on data yielded batch-by-batch by a Python generator.
Model.fit now supports generators, so there is no longer any need to use this endpoint.
View source
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).
View source
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.
When loading weights in HDF5 format, returns None.
View source
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.
View source
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.
View source
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.
View source
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.
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.
View source
Generates predictions for the input samples from a data generator.
Model.predict now supports generators, so there is no longer any need to use this endpoint.
View source
Returns predictions for a single batch of samples.
View source
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.
View source
Resets the state of all the metrics in the model.
View source
View source
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.
View source
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:
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.
View source
Prints a string summary of the network.
View source
Test the model on a single batch of samples.
View source
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.
View source
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={}).
View source
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.
View source
Runs a single gradient update on a single batch of data.
View source
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.


A LearningRateSchedule that uses a noisy linear cosine decay schedule.
Inherits From: LearningRateSchedule
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.NoisyLinearCosineDecay
See [Bello et al., ICML2017] Neural Optimizer Search with RL. https://arxiv.org/abs/1709.07417
For the idea of warm starts here controlled by num_periods, see [Loshchilov & Hutter, ICLR2016] SGDR: Stochastic Gradient Descent with Warm Restarts. https://arxiv.org/abs/1608.03983
Note that linear cosine decay is more aggressive than cosine decay and larger initial learning rates can typically be used.
When training a model, it is often recommended to lower the learning rate as the training progresses. This schedule applies a noisy linear cosine decay function to an optimizer step, given a provided initial learning rate. It requires a step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.
The schedule a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. It is computed as:
where eps_t is 0-centered gaussian noise with variance initial_variance / (1 + global_step) ** variance_decay
You can pass this schedule directly into a tf.keras.optimizers.Optimizer as the learning rate. The learning rate schedule is also serializable and deserializable using tf.keras.optimizers.schedules.serialize and tf.keras.optimizers.schedules.deserialize.
View source
Instantiates a LearningRateSchedule from its config.
View source
View source
Call self as a function.


Equivalent to LSTMCell class but adds peephole connections.
Inherits From: LSTMCell, Layer, Module
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.PeepholeLSTMCell
Peephole connections allow the gates to utilize the previous internal state as well as the previous hidden state (which is what LSTMCell is limited to). This allows PeepholeLSTMCell to better learn precise timings over LSTMCell.
From Gers et al., 2002:
"We find that LSTM augmented by 'peephole connections' from its internal cells to its multiplicative gates can learn the fine distinction between sequences of spikes spaced either 50 or 49 time steps apart without the help of any short training exemplars."
The peephole implementation is based on:
Sak et al., 2014
View source
Get the dropout mask for RNN cell's input.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
View source
View source
Get the recurrent dropout mask for RNN cell.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
View source
Reset the cached dropout masks if any.
This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
View source
Reset the cached recurrent dropout masks if any.
This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.


A layer for sequence input.
Inherits From: Layer, Module
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.SequenceFeatures
All feature_columns must be sequence dense columns with the same sequence_length. The output of this method can be fed into sequence networks, such as RNN.
The output of this method is a 3D Tensor of shape [batch_size, T, D]. T is the maximum sequence length for this batch, which could differ from batch to batch.
If multiple feature_columns are given with Di num_elements each, their outputs are concatenated. So, the final Tensor has shape [batch_size, T, D0 + D1 + ... + Dn].


Wide & Deep Model for regression and classification problems.
Inherits From: Model, Layer, Module
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.keras.experimental.WideDeepModel
This model jointly train a linear and a dnn model.
Both linear and dnn model can be pre-compiled and trained separately before jointly training:
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.
View source
Configures the model for training.
View source
Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the batch_size arg.)
See the discussion of Unpacking behavior for iterator-like inputs for Model.fit.
View source
Evaluates the model on a data generator.
Model.evaluate now supports generators, so there is no longer any need to use this endpoint.
View source
Trains the model for a fixed number of epochs (iterations on a dataset).
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.)
View source
Fits the model on data yielded batch-by-batch by a Python generator.
Model.fit now supports generators, so there is no longer any need to use this endpoint.
View source
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).
View source
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.
When loading weights in HDF5 format, returns None.
View source
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.
View source
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.
View source
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.
View source
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.
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.
View source
Generates predictions for the input samples from a data generator.
Model.predict now supports generators, so there is no longer any need to use this endpoint.
View source
Returns predictions for a single batch of samples.
View source
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.
View source
Resets the state of all the metrics in the model.
View source
View source
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.
View source
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:
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.
View source
Prints a string summary of the network.
View source
Test the model on a single batch of samples.
View source
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.
View source
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={}).
View source
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.
View source
Runs a single gradient update on a single batch of data.
View source
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.


Keras initializer serialization / deserialization.
Main aliases
tf.initializers
class Constant: Initializer that generates tensors with constant values.
class GlorotNormal: The Glorot normal initializer, also called Xavier normal initializer.
class GlorotUniform: The Glorot uniform initializer, also called Xavier uniform initializer.
class HeNormal: He normal initializer.
class HeUniform: He uniform variance scaling initializer.
class Identity: Initializer that generates the identity matrix.
class Initializer: Initializer base class: all Keras initializers inherit from this class.
class LecunNormal: Lecun normal initializer.
class LecunUniform: Lecun uniform initializer.
class Ones: Initializer that generates tensors initialized to 1.
class Orthogonal: Initializer that generates an orthogonal matrix.
class RandomNormal: Initializer that generates tensors with a normal distribution.
class RandomUniform: Initializer that generates tensors with a uniform distribution.
class TruncatedNormal: Initializer that generates a truncated normal distribution.
class VarianceScaling: Initializer capable of adapting its scale to the shape of weights tensors.
class Zeros: Initializer that generates tensors initialized to 0.
class constant: Initializer that generates tensors with constant values.
class glorot_normal: The Glorot normal initializer, also called Xavier normal initializer.
class glorot_uniform: The Glorot uniform initializer, also called Xavier uniform initializer.
class he_normal: He normal initializer.
class he_uniform: He uniform variance scaling initializer.
class identity: Initializer that generates the identity matrix.
class lecun_normal: Lecun normal initializer.
class lecun_uniform: Lecun uniform initializer.
class ones: Initializer that generates tensors initialized to 1.
class orthogonal: Initializer that generates an orthogonal matrix.
class random_normal: Initializer that generates tensors with a normal distribution.
class random_uniform: Initializer that generates tensors with a uniform distribution.
class truncated_normal: Initializer that generates a truncated normal distribution.
class variance_scaling: Initializer capable of adapting its scale to the shape of weights tensors.
class zeros: Initializer that generates tensors initialized to 0.
deserialize(...): Return an Initializer object from its config.
get(...)
serialize(...)


Initializer that generates tensors with constant values.
Inherits From: Initializer
Main aliases
tf.initializers.Constant, tf.initializers.constant, tf.keras.initializers.constant
Also available via the shortcut function tf.keras.initializers.constant.
Only scalar values are allowed. The constant value provided must be convertible to the dtype requested when calling the initializer.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized to self.value.


Return an Initializer object from its config.
Main aliases
tf.initializers.deserialize
See Migration guide for more details.
tf.compat.v1.keras.initializers.deserialize


Main aliases
tf.initializers.get
See Migration guide for more details.
tf.compat.v1.keras.initializers.get


The Glorot normal initializer, also called Xavier normal initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.GlorotNormal, tf.initializers.glorot_normal, tf.keras.initializers.glorot_normal
Also available via the shortcut function tf.keras.initializers.glorot_normal.
Draws samples from a truncated normal distribution centered on 0 with stddev = sqrt(2 / (fan_in + fan_out)) where fan_in is the number of input units in the weight tensor and fan_out is the number of output units in the weight tensor.
Glorot et al., 2010 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


The Glorot uniform initializer, also called Xavier uniform initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.GlorotUniform, tf.initializers.glorot_uniform, tf.keras.initializers.glorot_uniform
Also available via the shortcut function tf.keras.initializers.glorot_uniform.
Draws samples from a uniform distribution within [-limit, limit], where limit = sqrt(6 / (fan_in + fan_out)) (fan_in is the number of input units in the weight tensor and fan_out is the number of output units).
Glorot et al., 2010 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


He normal initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.HeNormal, tf.initializers.he_normal, tf.keras.initializers.he_normal
Also available via the shortcut function tf.keras.initializers.he_normal.
It draws samples from a truncated normal distribution centered on 0 with stddev = sqrt(2 / fan_in) where fan_in is the number of input units in the weight tensor.
He et al., 2015 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


He uniform variance scaling initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.HeUniform, tf.initializers.he_uniform, tf.keras.initializers.he_uniform
Also available via the shortcut function tf.keras.initializers.he_uniform.
Draws samples from a uniform distribution within [-limit, limit], where limit = sqrt(6 / fan_in) (fan_in is the number of input units in the weight tensor).
He et al., 2015 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates the identity matrix.
Inherits From: Initializer
Main aliases
tf.initializers.Identity, tf.initializers.identity, tf.keras.initializers.identity
Also available via the shortcut function tf.keras.initializers.identity.
Only usable for generating 2D matrices.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized to a 2D identity matrix.


Initializer base class: all Keras initializers inherit from this class.
Main aliases
tf.initializers.Initializer
See Migration guide for more details.
tf.compat.v1.keras.initializers.Initializer
Initializers should implement a __call__ method with the following signature:
Optionally, you an also implement the method get_config and the class method from_config in order to support serialization -- just like with any Keras object.
Here's a simple example: a random normal initializer.
Note that we don't have to implement from_config in the example above since the constructor arguments of the class the keys in the config returned by get_config are the same. In this case, the default from_config works fine.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Lecun normal initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.LecunNormal, tf.initializers.lecun_normal, tf.keras.initializers.lecun_normal
Also available via the shortcut function tf.keras.initializers.lecun_normal.
Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized.
Draws samples from a truncated normal distribution centered on 0 with stddev = sqrt(1 / fan_in) where fan_in is the number of input units in the weight tensor.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Lecun uniform initializer.
Inherits From: VarianceScaling, Initializer
Main aliases
tf.initializers.LecunUniform, tf.initializers.lecun_uniform, tf.keras.initializers.lecun_uniform
Also available via the shortcut function tf.keras.initializers.lecun_uniform.
Draws samples from a uniform distribution within [-limit, limit], where limit = sqrt(3 / fan_in) (fan_in is the number of input units in the weight tensor).
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors initialized to 1.
Inherits From: ones_initializer, Initializer
Main aliases
tf.initializers.Ones, tf.initializers.ones, tf.keras.initializers.ones
Also available via the shortcut function tf.keras.initializers.ones.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates an orthogonal matrix.
Inherits From: Initializer
Main aliases
tf.initializers.Orthogonal, tf.initializers.orthogonal, tf.keras.initializers.orthogonal
Also available via the shortcut function tf.keras.initializers.orthogonal.
If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix has fewer rows than columns then the output will have orthogonal rows. Otherwise, the output will have orthogonal columns.
If the shape of the tensor to initialize is more than two-dimensional, a matrix of shape (shape[0] * ... * shape[n - 2], shape[n - 1]) is initialized, where n is the length of the shape vector. The matrix is subsequently reshaped to give a tensor of the desired shape.
Saxe et al., 2014 (pdf)
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized to an orthogonal matrix.


Initializer that generates tensors with a normal distribution.
Inherits From: random_normal_initializer, Initializer
Main aliases
tf.initializers.RandomNormal, tf.initializers.random_normal, tf.keras.initializers.random_normal
Also available via the shortcut function tf.keras.initializers.random_normal.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized to random normal values.


Initializer that generates tensors with a uniform distribution.
Inherits From: random_uniform_initializer, Initializer
Main aliases
tf.initializers.RandomUniform, tf.initializers.random_uniform, tf.keras.initializers.random_uniform
Also available via the shortcut function tf.keras.initializers.random_uniform.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Main aliases
tf.initializers.serialize
See Migration guide for more details.
tf.compat.v1.keras.initializers.serialize


Initializer that generates a truncated normal distribution.
Inherits From: Initializer
Main aliases
tf.initializers.TruncatedNormal, tf.initializers.truncated_normal, tf.keras.initializers.truncated_normal
Also available via the shortcut function tf.keras.initializers.truncated_normal.
The values generated are similar to values from a tf.keras.initializers.RandomNormal initializer except that values more than two standard deviations from the mean are discarded and re-drawn.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized to random normal values (truncated).


Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: Initializer
Main aliases
tf.initializers.VarianceScaling, tf.initializers.variance_scaling, tf.keras.initializers.variance_scaling
Also available via the shortcut function tf.keras.initializers.variance_scaling.
With distribution="truncated_normal" or "untruncated_normal", samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) stddev = sqrt(scale / n), where n is:
With distribution="uniform", samples are drawn from a uniform distribution within [-limit, limit], where limit = sqrt(3 * scale / n).
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Initializer that generates tensors initialized to 0.
Inherits From: zeros_initializer, Initializer
Main aliases
tf.initializers.Zeros, tf.initializers.zeros, tf.keras.initializers.zeros
Also available via the shortcut function tf.keras.initializers.zeros.
View source
Instantiates an initializer from a configuration dictionary.
View source
Returns the configuration of the initializer as a JSON-serializable dict.
View source
Returns a tensor object initialized as specified by the initializer.


Input() is used to instantiate a Keras tensor.
Main aliases
tf.keras.layers.Input
See Migration guide for more details.
tf.compat.v1.keras.Input, tf.compat.v1.keras.layers.Input
A Keras tensor is a TensorFlow symbolic tensor object, which we augment with certain attributes that allow us to build a Keras model just by knowing the inputs and outputs of the model.
For instance, if a, b and c are Keras tensors, it becomes possible to do: model = Model(input=[a, b], output=c)
Note that even if eager execution is enabled, Input produces a symbolic tensor (i.e. a placeholder). This symbolic tensor can be used with other TensorFlow ops, as such: