Module keras.api.keras.models
Public API for tf.keras.models namespace.
Expand source code
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.keras.models namespace.
"""
from __future__ import print_function as _print_function
import sys as _sys
from keras.engine.sequential import Sequential
from keras.engine.training import Model
from keras.models import clone_model
from keras.saving.model_config import model_from_config
from keras.saving.model_config import model_from_json
from keras.saving.model_config import model_from_yaml
from keras.saving.save import load_model
from keras.saving.save import save_model
del _print_function
from tensorflow.python.util import module_wrapper as _module_wrapper
if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):
_sys.modules[__name__] = _module_wrapper.TFModuleWrapper(
_sys.modules[__name__], "keras.models", public_apis=None, deprecation=True,
has_lite=False)
Functions
def clone_model(model, input_tensors=None, clone_function=None)
-
Clone a Functional or Sequential
Model
instance.Model cloning is similar to calling a model on new inputs, except that it creates new layers (and thus new weights) instead of sharing the weights of the existing layers.
Note that
clone_model()
will not preserve the uniqueness of shared objects within the model (e.g. a single variable attached to two distinct layers will be restored as two separate variables).Args
model
- Instance of
Model
(could be a Functional model or a Sequential model). input_tensors
- optional list of input tensors or InputLayer objects
to build the model upon. If not provided,
new
Input
objects will be created. clone_function
- Callable to be used to clone each layer in the target
model (except
InputLayer
instances). It takes as argument the layer instance to be cloned, and returns the corresponding layer instance to be used in the model copy. If unspecified, this callable defaults to the following serialization/deserialization function:lambda layer: layer.__class__.from_config(layer.get_config())
. By passing a custom callable, you can customize your copy of the model, e.g. by wrapping certain layers of interest (you might want to replace allLSTM
instances with equivalentBidirectional(LSTM(…))
instances, for example).
Returns
An instance of
Model
reproducing the behavior of the original model, on top of new inputs tensors, using newly instantiated weights. The cloned model may behave differently from the original model if a customclone_function
modifies the layer. Example:# Create a test Sequential model. model = keras.Sequential([ keras.Input(shape=(728,)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1, activation='sigmoid'), ]) # Create a copy of the test model (with freshly initialized weights). new_model = clone_model(model)
Note that subclassed models cannot be cloned, since their internal layer structure is not known. To achieve equivalent functionality as
clone_model()
in the case of a subclassed model, simply make sure that the model class implementsget_config()
(and optionallyfrom_config()
), and call:new_model = model.__class__.from_config(model.get_config())
Expand source code
@keras_export('keras.models.clone_model') def clone_model(model, input_tensors=None, clone_function=None): """Clone a Functional or Sequential `Model` instance. Model cloning is similar to calling a model on new inputs, except that it creates new layers (and thus new weights) instead of sharing the weights of the existing layers. Note that `clone_model` will not preserve the uniqueness of shared objects within the model (e.g. a single variable attached to two distinct layers will be restored as two separate variables). Args: model: Instance of `Model` (could be a Functional model or a Sequential model). input_tensors: optional list of input tensors or InputLayer objects to build the model upon. If not provided, new `Input` objects will be created. clone_function: Callable to be used to clone each layer in the target model (except `InputLayer` instances). It takes as argument the layer instance to be cloned, and returns the corresponding layer instance to be used in the model copy. If unspecified, this callable defaults to the following serialization/deserialization function: `lambda layer: layer.__class__.from_config(layer.get_config())`. By passing a custom callable, you can customize your copy of the model, e.g. by wrapping certain layers of interest (you might want to replace all `LSTM` instances with equivalent `Bidirectional(LSTM(...))` instances, for example). Returns: An instance of `Model` reproducing the behavior of the original model, on top of new inputs tensors, using newly instantiated weights. The cloned model may behave differently from the original model if a custom `clone_function` modifies the layer. Example: ```python # Create a test Sequential model. model = keras.Sequential([ keras.Input(shape=(728,)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1, activation='sigmoid'), ]) # Create a copy of the test model (with freshly initialized weights). new_model = clone_model(model) ``` Note that subclassed models cannot be cloned, since their internal layer structure is not known. To achieve equivalent functionality as `clone_model` in the case of a subclassed model, simply make sure that the model class implements `get_config()` (and optionally `from_config()`), and call: ```python new_model = model.__class__.from_config(model.get_config()) ``` """ with generic_utils.DisableSharedObjectScope(): if clone_function is None: clone_function = _clone_layer if isinstance(model, Sequential): return _clone_sequential_model( model, input_tensors=input_tensors, layer_fn=clone_function) else: return _clone_functional_model( model, input_tensors=input_tensors, layer_fn=clone_function)
def load_model(filepath, custom_objects=None, compile=True, options=None)
-
Loads a model saved via
model.save()
.Usage:
>>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x))
Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as
"dense_1/kernel:0"
. It is recommended that you use the layer properties to access specific variables, e.g.model.get_layer("dense_1").kernel
.Args
filepath
- One of the following:
- String or
pathlib.Path
object, path to the saved model -h5py.File
object from which to load the model custom_objects
- Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization.
compile
- Boolean, whether to compile the model after loading.
options
- Optional
tf.saved_model.LoadOptions
object that specifies options for loading from SavedModel.
Returns
A Keras model instance. If the original model was compiled, and saved with the optimizer, then the returned model will be compiled. Otherwise, the model will be left uncompiled. In the case that an uncompiled model is returned, a warning is displayed if the
compile
argument is set toTrue
.Raises
ImportError
- if loading from an hdf5 file and h5py is not available.
IOError
- In case of an invalid savefile.
Expand source code
@keras_export('keras.models.load_model') def load_model(filepath, custom_objects=None, compile=True, options=None): # pylint: disable=redefined-builtin """Loads a model saved via `model.save()`. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as `"dense_1/kernel:0"`. It is recommended that you use the layer properties to access specific variables, e.g. `model.get_layer("dense_1").kernel`. Args: filepath: One of the following: - String or `pathlib.Path` object, path to the saved model - `h5py.File` object from which to load the model custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. compile: Boolean, whether to compile the model after loading. options: Optional `tf.saved_model.LoadOptions` object that specifies options for loading from SavedModel. Returns: A Keras model instance. If the original model was compiled, and saved with the optimizer, then the returned model will be compiled. Otherwise, the model will be left uncompiled. In the case that an uncompiled model is returned, a warning is displayed if the `compile` argument is set to `True`. Raises: ImportError: if loading from an hdf5 file and h5py is not available. IOError: In case of an invalid savefile. """ with generic_utils.SharedObjectLoadingScope(): with generic_utils.CustomObjectScope(custom_objects or {}): with load_context.load_context(options): if (h5py is not None and (isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))): return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile) filepath = path_to_string(filepath) if isinstance(filepath, str): return saved_model_load.load(filepath, compile, options) raise IOError( 'Unable to load model. Filepath is not an hdf5 file (or h5py is not ' 'available) or SavedModel.')
def model_from_config(config, custom_objects=None)
-
Instantiates a Keras model from its config.
Usage:
# for a Functional API model tf.keras.Model().from_config(model.get_config()) # for a Sequential model tf.keras.Sequential().from_config(model.get_config())
Args
config
- Configuration dictionary.
custom_objects
- Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization.
Returns
A Keras model instance (uncompiled).
Raises
TypeError
- if
config
is not a dictionary.
Expand source code
@keras_export('keras.models.model_from_config') def model_from_config(config, custom_objects=None): """Instantiates a Keras model from its config. Usage: ``` # for a Functional API model tf.keras.Model().from_config(model.get_config()) # for a Sequential model tf.keras.Sequential().from_config(model.get_config()) ``` Args: config: Configuration dictionary. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). Raises: TypeError: if `config` is not a dictionary. """ if isinstance(config, list): raise TypeError('`model_from_config` expects a dictionary, not a list. ' 'Maybe you meant to use ' '`Sequential.from_config(config)`?') from keras.layers import deserialize # pylint: disable=g-import-not-at-top return deserialize(config, custom_objects=custom_objects)
def model_from_json(json_string, custom_objects=None)
-
Parses a JSON model configuration string and returns a model instance.
Usage:
>>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model = tf.keras.models.model_from_json(config)
Args
json_string
- JSON string encoding a model configuration.
custom_objects
- Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization.
Returns
A Keras model instance (uncompiled).
Expand source code
@keras_export('keras.models.model_from_json') def model_from_json(json_string, custom_objects=None): """Parses a JSON model configuration string and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model = tf.keras.models.model_from_json(config) Args: json_string: JSON string encoding a model configuration. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). """ config = json_utils.decode(json_string) from keras.layers import deserialize # pylint: disable=g-import-not-at-top return deserialize(config, custom_objects=custom_objects)
def model_from_yaml(yaml_string, custom_objects=None)
-
Parses a yaml model configuration file and returns a model instance.
Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError.
Args
yaml_string
- YAML string or open file encoding a model configuration.
custom_objects
- Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization.
Returns
A Keras model instance (uncompiled).
Raises
RuntimeError
- announces that the method poses a security risk
Expand source code
@keras_export('keras.models.model_from_yaml') def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. Args: yaml_string: YAML string or open file encoding a model configuration. custom_objects: Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. Returns: A Keras model instance (uncompiled). Raises: RuntimeError: announces that the method poses a security risk """ raise RuntimeError( 'Method `model_from_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `Model.to_json()` and ' '`model_from_json()` instead.' )
def save_model(model, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True)
-
Saves a model as a TensorFlow SavedModel or HDF5 file.
See the Serialization and Saving guide for details.
Usage:
>>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x))
The SavedModel and HDF5 file contains:
- the model's configuration (topology)
- the model's weights
- the model's optimizer's state (if any)
Thus models can be reinstantiated in the exact same state, without any of the code used for model definition or training.
Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as
"dense_1/kernel:0"
. It is recommended that you use the layer properties to access specific variables, e.g.model.get_layer("dense_1").kernel
.SavedModel serialization format
Keras SavedModel uses
tf.saved_model.save
to save the model and all trackable objects attached to the model (e.g. layers and variables). The model config, weights, and optimizer are saved in the SavedModel. Additionally, for every Keras layer attached to the model, the SavedModel stores:- the config and metadata – e.g. name, dtype, trainable status
- traced call and loss functions, which are stored as TensorFlow subgraphs.
The traced functions allow the SavedModel format to save and load custom layers without the original class definition.
You can choose to not save the traced functions by disabling the
save_traces
option. This will decrease the time it takes to save the model and the amount of disk space occupied by the output SavedModel. If you enable this option, then you must provide all custom class definitions when loading the model. See thecustom_objects
argument intf.keras.models.load_model
.Args
model
- Keras model instance to be saved.
filepath
- One of the following:
- String or
pathlib.Path
object, path where to save the model -h5py.File
object where to save the model overwrite
- Whether we should overwrite any existing model at the target location, or instead ask the user with a manual prompt.
include_optimizer
- If True, save optimizer's state together.
save_format
- Either 'tf' or 'h5', indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X.
signatures
- Signatures to save with the SavedModel. Applicable to the 'tf'
format only. Please see the
signatures
argument intf.saved_model.save
for details. options
- (only applies to SavedModel format)
tf.saved_model.SaveOptions
object that specifies options for saving to SavedModel. save_traces
- (only applies to SavedModel format) When enabled, the
SavedModel will store the function traces for each layer. This
can be disabled, so that only the configs of each layer are stored.
Defaults to
True
. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement aget_config()
method.
Raises
ImportError
- If save format is hdf5, and h5py is not available.
Expand source code
@keras_export('keras.models.save_model') def save_model(model, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True): # pylint: disable=line-too-long """Saves a model as a TensorFlow SavedModel or HDF5 file. See the [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) for details. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> model.save('/tmp/model') >>> loaded_model = tf.keras.models.load_model('/tmp/model') >>> x = tf.random.uniform((10, 3)) >>> assert np.allclose(model.predict(x), loaded_model.predict(x)) The SavedModel and HDF5 file contains: - the model's configuration (topology) - the model's weights - the model's optimizer's state (if any) Thus models can be reinstantiated in the exact same state, without any of the code used for model definition or training. Note that the model weights may have different scoped names after being loaded. Scoped names include the model/layer names, such as `"dense_1/kernel:0"`. It is recommended that you use the layer properties to access specific variables, e.g. `model.get_layer("dense_1").kernel`. __SavedModel serialization format__ Keras SavedModel uses `tf.saved_model.save` to save the model and all trackable objects attached to the model (e.g. layers and variables). The model config, weights, and optimizer are saved in the SavedModel. Additionally, for every Keras layer attached to the model, the SavedModel stores: * the config and metadata -- e.g. name, dtype, trainable status * traced call and loss functions, which are stored as TensorFlow subgraphs. The traced functions allow the SavedModel format to save and load custom layers without the original class definition. You can choose to not save the traced functions by disabling the `save_traces` option. This will decrease the time it takes to save the model and the amount of disk space occupied by the output SavedModel. If you enable this option, then you _must_ provide all custom class definitions when loading the model. See the `custom_objects` argument in `tf.keras.models.load_model`. Args: model: Keras model instance to be saved. filepath: One of the following: - String or `pathlib.Path` object, path where to save the model - `h5py.File` object where to save the model overwrite: Whether we should overwrite any existing model at the target location, or instead ask the user with a manual prompt. include_optimizer: If True, save optimizer's state together. save_format: Either 'tf' or 'h5', indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. signatures: Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the `signatures` argument in `tf.saved_model.save` for details. options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` object that specifies options for saving to SavedModel. save_traces: (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to `True`. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a `get_config()` method. Raises: ImportError: If save format is hdf5, and h5py is not available. """ # pylint: enable=line-too-long from keras.engine import sequential # pylint: disable=g-import-not-at-top default_format = 'tf' if tf.__internal__.tf2.enabled() else 'h5' save_format = save_format or default_format filepath = path_to_string(filepath) # If the user has not already called fit or built the underlying metrics, we # should do that before saving to ensure the metric names have all # appropriate name transformations applied. saving_utils.try_build_compiled_arguments(model) if (save_format == 'h5' or (h5py is not None and isinstance(filepath, h5py.File)) or saving_utils.is_hdf5_filepath(filepath)): # TODO(b/130258301): add utility method for detecting model type. if (not model._is_graph_network and # pylint:disable=protected-access not isinstance(model, sequential.Sequential)): raise NotImplementedError( 'Saving the model to HDF5 format requires the model to be a ' 'Functional model or a Sequential model. It does not work for ' 'subclassed models, because such models are defined via the body of ' 'a Python method, which isn\'t safely serializable. Consider saving ' 'to the Tensorflow SavedModel format (by setting save_format="tf") ' 'or using `save_weights`.') hdf5_format.save_model_to_hdf5( model, filepath, overwrite, include_optimizer) else: with generic_utils.SharedObjectSavingScope(): saved_model_save.save(model, filepath, overwrite, include_optimizer, signatures, options, save_traces)
Classes
class Model (*args, **kwargs)
-
Model
groups layers into an object with training and inference features.Args
inputs
- The input(s) of the model: a
keras.Input
object or list ofkeras.Input
objects. outputs
- The output(s) of the model. See Functional API example below.
name
- String, the name of the model.
There are two ways to instantiate a
Model
:1 - With the "Functional API", where you start from
Input
, you chain layer calls to specify the model's forward pass, and finally you create your model from inputs and outputs:import tensorflow as tf inputs = tf.keras.Input(shape=(3,)) x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) model = tf.keras.Model(inputs=inputs, outputs=outputs)
Note: Only dicts, lists, and tuples of input tensors are supported. Nested inputs are not supported (e.g. lists of list or dicts of dict).
2 - By subclassing the
Model
class: in that case, you should define your layers in__init__
and you should implement the model's forward pass incall
.import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) def call(self, inputs): x = self.dense1(inputs) return self.dense2(x) model = MyModel()
If you subclass
Model
, you can optionally have atraining
argument (boolean) incall
, which you can use to specify a different behavior in training and inference:import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) self.dropout = tf.keras.layers.Dropout(0.5) def call(self, inputs, training=False): x = self.dense1(inputs) if training: x = self.dropout(x, training=training) return self.dense2(x) model = MyModel()
Once the model is created, you can config the model with losses and metrics with
model.compile()
, train the model withmodel.fit()
, or use the model to do prediction withmodel.predict()
.Expand source code
class Model(base_layer.Layer, version_utils.ModelVersionSelector): """`Model` groups layers into an object with training and inference features. Args: inputs: The input(s) of the model: a `keras.Input` object or list of `keras.Input` objects. outputs: The output(s) of the model. See Functional API example below. name: String, the name of the model. There are two ways to instantiate a `Model`: 1 - With the "Functional API", where you start from `Input`, you chain layer calls to specify the model's forward pass, and finally you create your model from inputs and outputs: ```python import tensorflow as tf inputs = tf.keras.Input(shape=(3,)) x = tf.keras.layers.Dense(4, activation=tf.nn.relu)(inputs) outputs = tf.keras.layers.Dense(5, activation=tf.nn.softmax)(x) model = tf.keras.Model(inputs=inputs, outputs=outputs) ``` Note: Only dicts, lists, and tuples of input tensors are supported. Nested inputs are not supported (e.g. lists of list or dicts of dict). 2 - By subclassing the `Model` class: in that case, you should define your layers in `__init__` and you should implement the model's forward pass in `call`. ```python import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) def call(self, inputs): x = self.dense1(inputs) return self.dense2(x) model = MyModel() ``` If you subclass `Model`, you can optionally have a `training` argument (boolean) in `call`, which you can use to specify a different behavior in training and inference: ```python import tensorflow as tf class MyModel(tf.keras.Model): def __init__(self): super(MyModel, self).__init__() self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax) self.dropout = tf.keras.layers.Dropout(0.5) def call(self, inputs, training=False): x = self.dense1(inputs) if training: x = self.dropout(x, training=training) return self.dense2(x) model = MyModel() ``` Once the model is created, you can config the model with losses and metrics with `model.compile()`, train the model with `model.fit()`, or use the model to do prediction with `model.predict()`. """ _TF_MODULE_IGNORED_PROPERTIES = frozenset( itertools.chain(('_train_counter', '_test_counter', '_predict_counter', '_steps_per_execution'), base_layer.Layer._TF_MODULE_IGNORED_PROPERTIES)) # pylint: disable=protected-access def __new__(cls, *args, **kwargs): # Signature detection if is_functional_model_init_params(args, kwargs) and cls == Model: # Functional model from keras.engine import functional # pylint: disable=g-import-not-at-top return functional.Functional(skip_init=True, *args, **kwargs) else: return super(Model, cls).__new__(cls, *args, **kwargs) @tf.__internal__.tracking.no_automatic_dependency_tracking def __init__(self, *args, **kwargs): self._is_model_for_instrumentation = True base_layer.keras_api_gauge.get_cell('model').set(True) # Special case for Subclassed Functional Model, which we couldn't detect # when __new__ is called. We only realize it is a functional model when it # calls super.__init__ with input and output tensor. from keras.engine import functional # pylint: disable=g-import-not-at-top if (is_functional_model_init_params(args, kwargs) and not isinstance(self, functional.Functional)): # Filter the kwargs for multiple inheritance. supported_kwargs = ['inputs', 'outputs', 'name', 'trainable', 'skip_init'] model_kwargs = {k: kwargs[k] for k in kwargs if k in supported_kwargs} other_kwargs = {k: kwargs[k] for k in kwargs if k not in supported_kwargs} inject_functional_model_class(self.__class__) functional.Functional.__init__(self, *args, **model_kwargs) # In case there is any multiple inheritance here, we need to call the # __init__ for any class that appears after the Functional class. clz_to_init = [] found_functional_class = False for clz in self.__class__.__bases__: if issubclass(clz, functional.Functional): found_functional_class = True continue if found_functional_class: clz_to_init.append(clz) if clz_to_init: for clz in clz_to_init: clz.__init__(self, *args, **other_kwargs) elif other_kwargs: # In case there are unused kwargs, we should raise an error to user, in # case they have a typo in the param name. raise TypeError( 'The following keyword arguments aren\'t supported: {}'.format( other_kwargs)) return base_layer.keras_api_gauge.get_cell('Model subclass').set(True) # The following are implemented as property functions: # self.trainable_weights # self.non_trainable_weights # `inputs` / `outputs` will only appear in kwargs if either are misspelled. generic_utils.validate_kwargs(kwargs, { 'trainable', 'dtype', 'dynamic', 'name', 'autocast', 'inputs', 'outputs' }) super(Model, self).__init__(**kwargs) # By default, Model is a subclass model, which is not in graph network. self._is_graph_network = False self.inputs = None self.outputs = None self.input_names = None self.output_names = None # stop_training is used by callback to stop training when error happens self.stop_training = False self.history = None # These objects are used in the default `Model.compile`. They are not # guaranteed to be set after `Model.compile` is called, as users can # override compile with custom logic. self.compiled_loss = None self.compiled_metrics = None # This is True for Sequential networks and Functional networks. self._compute_output_and_mask_jointly = False # Don't reset compilation if already done. This may occur if calling # `__init__` (or `_init_graph_network`) on an already-compiled model # such as a Sequential model. Sequential models may need to rebuild # themselves after compilation. self._maybe_create_attribute('_is_compiled', False) self._maybe_create_attribute('optimizer', None) # Model must be created under scope of DistStrat it will be trained with. if tf.distribute.has_strategy(): self._distribution_strategy = tf.distribute.get_strategy() else: self._distribution_strategy = None self._cluster_coordinator = None # Defaults to value of `tf.config.experimental_functions_run_eagerly`. self._run_eagerly = None # Initialize cache attrs. self._reset_compile_cache() # Fault-tolerance handler. Set in `ModelCheckpoint`. self._training_state = None self._saved_model_inputs_spec = None self._saved_model_arg_spec = None self._trackable_saver = saver_with_op_caching(self) self._steps_per_execution = None self._init_batch_counters() self._base_model_initialized = True @tf.__internal__.tracking.no_automatic_dependency_tracking def _init_batch_counters(self): # Untracked Variables, used to keep track of mini-batches seen in `fit`, # `evaluate`, and `predict`. agg = tf.VariableAggregation.ONLY_FIRST_REPLICA self._train_counter = tf.Variable(0, dtype='int64', aggregation=agg) self._test_counter = tf.Variable(0, dtype='int64', aggregation=agg) self._predict_counter = tf.Variable( 0, dtype='int64', aggregation=agg) def __setattr__(self, name, value): if not getattr(self, '_self_setattr_tracking', True): super(Model, self).__setattr__(name, value) return if all( isinstance(v, (base_layer.Layer, tf.Variable)) or base_layer_utils.has_weights(v) for v in tf.nest.flatten(value)): try: self._base_model_initialized except AttributeError: raise RuntimeError( 'It looks like you are subclassing `Model` and you ' 'forgot to call `super().__init__()`.' ' Always start with this line.') super(Model, self).__setattr__(name, value) @generic_utils.default def build(self, input_shape): """Builds the model based on input shapes received. This is to be used for subclassed models, which do not know at instantiation time what their inputs look like. This method only exists for users who want to call `model.build()` in a standalone way (as a substitute for calling the model on real data to build it). It will never be called by the framework (and thus it will never throw unexpected errors in an unrelated workflow). Args: input_shape: Single tuple, TensorShape, or list/dict of shapes, where shapes are tuples, integers, or TensorShapes. Raises: ValueError: 1. In case of invalid user-provided data (not of type tuple, list, TensorShape, or dict). 2. If the model requires call arguments that are agnostic to the input shapes (positional or kwarg in call signature). 3. If not all layers were properly built. 4. If float type inputs are not supported within the layers. In each of these cases, the user should build their model by calling it on real tensor data. """ if self._is_graph_network: super(Model, self).build(input_shape) return if input_shape is None: raise ValueError('Input shape must be defined when calling build on a ' 'model subclass network.') valid_types = (tuple, list, tf.TensorShape, dict) if not isinstance(input_shape, valid_types): raise ValueError('Specified input shape is not one of the valid types. ' 'Please specify a batch input shape of type tuple or ' 'list of input shapes. User provided ' 'input type: {}'.format(type(input_shape))) if input_shape and not self.inputs: # We create placeholders for the `None`s in the shape and build the model # in a Graph. Since tf.Variable is compatible with both eager execution # and graph building, the variables created after building the model in # a Graph are still valid when executing eagerly. if tf.executing_eagerly(): graph = tf.__internal__.FuncGraph('build_graph') else: graph = backend.get_graph() with graph.as_default(): if (isinstance(input_shape, list) and all(d is None or isinstance(d, int) for d in input_shape)): input_shape = tuple(input_shape) if isinstance(input_shape, list): x = [base_layer_utils.generate_placeholders_from_shape(shape) for shape in input_shape] elif isinstance(input_shape, dict): x = { k: base_layer_utils.generate_placeholders_from_shape(shape) for k, shape in input_shape.items() } else: x = base_layer_utils.generate_placeholders_from_shape(input_shape) kwargs = {} call_signature = self._call_full_argspec call_args = call_signature.args # Exclude `self`, `inputs`, and any argument with a default value. if len(call_args) > 2: if call_signature.defaults: call_args = call_args[2:-len(call_signature.defaults)] else: call_args = call_args[2:] for arg in call_args: if arg == 'training': # Case where `training` is a positional arg with no default. kwargs['training'] = False else: # Has invalid call signature with unknown positional arguments. raise ValueError( 'Currently, you cannot build your model if it has ' 'positional or keyword arguments that are not ' 'inputs to the model, but are required for its ' '`call` method. Instead, in order to instantiate ' 'and build your model, `call` your model on real ' 'tensor data with all expected call arguments.') elif len(call_args) < 2: # Signature without `inputs`. raise ValueError('You can only call `build` on a model if its `call` ' 'method accepts an `inputs` argument.') try: self.call(x, **kwargs) except (tf.errors.InvalidArgumentError, TypeError): raise ValueError('You cannot build your model by calling `build` ' 'if your layers do not support float type inputs. ' 'Instead, in order to instantiate and build your ' 'model, `call` your model on real tensor data (of ' 'the correct dtype).') super(Model, self).build(input_shape) @doc_controls.doc_in_current_and_subclasses def call(self, inputs, training=None, mask=None): """Calls the model on new inputs. In this case `call` just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs). Note: This method should not be called directly. It is only meant to be overridden when subclassing `tf.keras.Model`. To call a model on an input, always use the `__call__` method, i.e. `model(inputs)`, which relies on the underlying `call` method. Args: inputs: Input tensor, or dict/list/tuple of input tensors. training: Boolean or boolean scalar tensor, indicating whether to run the `Network` in training mode or inference mode. mask: A mask or list of masks. A mask can be either a tensor or None (no mask). Returns: A tensor if there is a single output, or a list of tensors if there are more than one outputs. """ raise NotImplementedError('When subclassing the `Model` class, you should ' 'implement a `call` method.') def compile(self, optimizer='rmsprop', loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, steps_per_execution=None, **kwargs): """Configures the model for training. Example: ```python model.compile(optimizer=tf.keras.optimizer.Adam(learning_rate=1e-3), loss=tf.keras.losses.BinaryCrossentropy(), metrics=[tf.keras.metrics.BinaryAccuracy(), tf.keras.metrics.FalseNegatives()]) ``` Args: optimizer: String (name of optimizer) or optimizer instance. See `tf.keras.optimizers`. loss: Loss function. Maybe be a string (name of loss function), or a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss function is any callable with the signature `loss = fn(y_true, y_pred)`, where `y_true` are the ground truth values, and `y_pred` are the model's predictions. `y_true` should have shape `(batch_size, d0, .. dN)` (except in the case of sparse loss functions such as sparse categorical crossentropy which expects integer arrays of shape `(batch_size, d0, .. dN-1)`). `y_pred` should have shape `(batch_size, d0, .. dN)`. The loss function should return a float tensor. If a custom `Loss` instance is used and reduction is set to `None`, return value has shape `(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss values; otherwise, it is a scalar. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses, unless `loss_weights` is specified. metrics: List of metrics to be evaluated by the model during training and testing. Each of this can be a string (name of a built-in function), function or a `tf.keras.metrics.Metric` instance. See `tf.keras.metrics`. Typically you will use `metrics=['accuracy']`. A function is any callable with the signature `result = fn(y_true, y_pred)`. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`. You can also pass a list to specify a metric or a list of metrics for each output, such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the strings 'accuracy' or 'acc', we convert this to one of `tf.keras.metrics.BinaryAccuracy`, `tf.keras.metrics.CategoricalAccuracy`, `tf.keras.metrics.SparseCategoricalAccuracy` based on the loss function used and the model output shape. We do a similar conversion for the strings 'crossentropy' and 'ce' as well. loss_weights: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the *weighted sum* of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients. weighted_metrics: List of metrics to be evaluated and weighted by `sample_weight` or `class_weight` during training and testing. run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s logic will not be wrapped in a `tf.function`. Recommended to leave this as `None` unless your `Model` cannot be run inside a `tf.function`. `run_eagerly=True` is not supported when using `tf.distribute.experimental.ParameterServerStrategy`. steps_per_execution: Int. Defaults to 1. The number of batches to run during each `tf.function` call. Running multiple batches inside a single `tf.function` call can greatly improve performance on TPUs or small models with a large Python overhead. At most, one full epoch will be run each execution. If a number larger than the size of the epoch is passed, the execution will be truncated to the size of the epoch. Note that if `steps_per_execution` is set to `N`, `Callback.on_batch_begin` and `Callback.on_batch_end` methods will only be called every `N` batches (i.e. before/after each `tf.function` execution). **kwargs: Arguments supported for backwards compatibility only. Raises: ValueError: In case of invalid arguments for `optimizer`, `loss` or `metrics`. """ base_layer.keras_api_gauge.get_cell('compile').set(True) with self.distribute_strategy.scope(): if 'experimental_steps_per_execution' in kwargs: logging.warning('The argument `steps_per_execution` is no longer ' 'experimental. Pass `steps_per_execution` instead of ' '`experimental_steps_per_execution`.') if not steps_per_execution: steps_per_execution = kwargs.pop('experimental_steps_per_execution') # When compiling from an already-serialized model, we do not want to # reapply some processing steps (e.g. metric renaming for multi-output # models, which have prefixes added for each corresponding output name). from_serialized = kwargs.pop('from_serialized', False) self._validate_compile(optimizer, metrics, **kwargs) self._run_eagerly = run_eagerly self.optimizer = self._get_optimizer(optimizer) self.compiled_loss = compile_utils.LossesContainer( loss, loss_weights, output_names=self.output_names) self.compiled_metrics = compile_utils.MetricsContainer( metrics, weighted_metrics, output_names=self.output_names, from_serialized=from_serialized) self._configure_steps_per_execution(steps_per_execution or 1) # Initializes attrs that are reset each time `compile` is called. self._reset_compile_cache() self._is_compiled = True self.loss = loss or {} # Backwards compat. def _get_optimizer(self, optimizer): """Wraps `optimizer` in `LossScaleOptimizer` if necessary.""" # The deprecated PolicyV1 has a loss_scale, which we use for backwards # compatibility to match TF 2.3 behavior. The new Policy does not have a # loss_scale, so we use dynamic loss scaling if the mixed_float16 policy is # used. if isinstance(self._dtype_policy, policy.PolicyV1): loss_scale = self._dtype_policy.loss_scale elif self._dtype_policy.name == 'mixed_float16': loss_scale = 'dynamic' else: loss_scale = None def _get_single_optimizer(opt): opt = optimizers.get(opt) if (loss_scale is not None and not isinstance(opt, lso.LossScaleOptimizer)): if loss_scale == 'dynamic': opt = lso.LossScaleOptimizer(opt) else: opt = lso.LossScaleOptimizerV1(opt, loss_scale) return opt return tf.nest.map_structure(_get_single_optimizer, optimizer) @tf.__internal__.tracking.no_automatic_dependency_tracking def _reset_compile_cache(self): self.train_function = None self.test_function = None self.predict_function = None # Used to cache the `tf.function`'ed `train_function` to be logged in # TensorBoard, since the original `train_function` is not necessarily # a `tf.function` (e.g., with ParameterServerStrategy, the `train_function` # is a scheduling of the actual training function to a remote worker). self.train_tf_function = None # Used to cache `trainable` attr of `Layer`s for `fit`. self._compiled_trainable_state = self._get_trainable_state() @tf.__internal__.tracking.no_automatic_dependency_tracking def _configure_steps_per_execution(self, steps_per_execution): self._steps_per_execution = tf.Variable( steps_per_execution, dtype='int64', aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA) @property def _should_compute_mask(self): return False @property def metrics(self): """Returns the model's metrics added using `compile`, `add_metric` APIs. Note: Metrics passed to `compile()` are available only after a `keras.Model` has been trained/evaluated on actual data. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> [m.name for m in model.metrics] [] >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> [m.name for m in model.metrics] ['loss', 'mae'] >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.add_metric( ... tf.reduce_sum(output_2), name='mean', aggregation='mean') >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> [m.name for m in model.metrics] ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc', 'mean'] """ metrics = [] if self._is_compiled: # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects # so that attr names are not load-bearing. if self.compiled_loss is not None: metrics += self.compiled_loss.metrics if self.compiled_metrics is not None: metrics += self.compiled_metrics.metrics for l in self._flatten_layers(): metrics.extend(l._metrics) # pylint: disable=protected-access return metrics @property def metrics_names(self): """Returns the model's display labels for all outputs. Note: `metrics_names` are available only after a `keras.Model` has been trained/evaluated on actual data. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> model.metrics_names [] >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> model.metrics_names ['loss', 'mae'] >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> model.metrics_names ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc'] """ # This property includes all output names including `loss` and per-output # losses for backward compatibility. return [m.name for m in self.metrics] @property def distribute_strategy(self): """The `tf.distribute.Strategy` this model was created under.""" return self._distribution_strategy or tf.distribute.get_strategy() @property def run_eagerly(self): """Settable attribute indicating whether the model should run eagerly. Running eagerly means that your model will be run step by step, like Python code. Your model might run slower, but it should become easier for you to debug it by stepping into individual layer calls. By default, we will attempt to compile your model to a static graph to deliver the best execution performance. Returns: Boolean, whether the model should run eagerly. """ if self.dynamic and self._run_eagerly is False: # pylint:disable=g-bool-id-comparison # TODO(fchollet): consider using py_func to enable this. raise ValueError('Your model contains layers that can only be ' 'successfully run in eager execution (layers ' 'constructed with `dynamic=True`). ' 'You cannot set `run_eagerly=False`.') if self._cluster_coordinator and self._run_eagerly: raise ValueError('When using `Model` with `ParameterServerStrategy`, ' '`run_eagerly` is not supported.') # Run eagerly logic, by priority: # (1) Dynamic models must be run eagerly. # (2) Explicitly setting run_eagerly causes a Model to be run eagerly. # (3) Not explicitly setting run_eagerly defaults to TF's global setting. return (self.dynamic or self._run_eagerly or (tf.config.functions_run_eagerly() and self._run_eagerly is None)) @run_eagerly.setter def run_eagerly(self, value): self._run_eagerly = value def train_step(self, data): """The logic for one training step. This method can be overridden to support custom training logic. For concrete examples of how to override this method see [Customizing what happends in fit](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). 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. Args: data: A nested structure of `Tensor`s. Returns: A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned. Example: `{'loss': 0.2, 'accuracy': 0.7}`. """ # These are the only transformations `Model.fit` applies to user-input # data when a `tf.data.Dataset` is provided. data = data_adapter.expand_1d(data) x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) # Run forward pass. with tf.GradientTape() as tape: y_pred = self(x, training=True) loss = self.compiled_loss( y, y_pred, sample_weight, regularization_losses=self.losses) # Run backwards pass. self.optimizer.minimize(loss, self.trainable_variables, tape=tape) self.compiled_metrics.update_state(y, y_pred, sample_weight) # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if isinstance(result, dict): return_metrics.update(result) else: return_metrics[metric.name] = result return return_metrics def make_train_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the train function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return a `dict` containing values that will be passed to `tf.keras.Callbacks.on_train_batch_end`, such as `{'loss': 0.2, 'accuracy': 0.7}`. """ if self.train_function is not None and not force: return self.train_function def step_function(model, iterator): """Runs a single training step.""" def run_step(data): outputs = model.train_step(data) # Ensure counter is updated only if `train_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._train_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='first') write_scalar_summaries(outputs, step=model._train_counter) # pylint: disable=protected-access return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def train_function(iterator): """Runs a training execution with one step.""" return step_function(self, iterator) else: def train_function(iterator): """Runs a training execution with multiple steps.""" for _ in tf.range(self._steps_per_execution): outputs = step_function(self, iterator) return outputs if not self.run_eagerly: train_function = tf.function( train_function, experimental_relax_shapes=True) self.train_tf_function = train_function self.train_function = train_function if self._cluster_coordinator: self.train_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda train_function, args=(iterator,)) return self.train_function def fit(self, x=None, y=None, batch_size=None, epochs=1, verbose='auto', callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False): """Trains the model for a fixed number of epochs (iterations on a dataset). Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. - A `tf.data` dataset. Should return a tuple of either `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A `tf.keras.utils.experimental.DatasetCreator`, which wraps a callable that takes a single argument of type `tf.distribute.InputContext`, and returns a `tf.data.Dataset`. `DatasetCreator` should be used when users prefer to specify the per-replica batching and sharding logic for the `Dataset`. See `tf.keras.utils.experimental.DatasetCreator` doc for more information. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given below. If using `tf.distribute.experimental.ParameterServerStrategy`, only `DatasetCreator` type is supported for `x`. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). If `x` is a dataset, generator, or `keras.utils.Sequence` instance, `y` should not be specified (since targets will be obtained from `x`). batch_size: Integer or `None`. Number of samples per gradient update. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of datasets, generators, or `keras.utils.Sequence` instances (since they generate batches). epochs: Integer. Number of epochs to train the model. An epoch is an iteration over the entire `x` and `y` data provided. Note that in conjunction with `initial_epoch`, `epochs` is to be understood as "final epoch". The model is not trained for a number of iterations given by `epochs`, but merely until the epoch of index `epochs` is reached. verbose: 'auto', 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. 'auto' defaults to 1 for most cases, but 2 when used with `ParameterServerStrategy`. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during training. See `tf.keras.callbacks`. Note `tf.keras.callbacks.ProgbarLogger` and `tf.keras.callbacks.History` callbacks are created automatically and need not be passed into `model.fit`. `tf.keras.callbacks.ProgbarLogger` is created or not based on `verbose` argument to `model.fit`. Callbacks with batch-level calls are currently unsupported with `tf.distribute.experimental.ParameterServerStrategy`, and users are advised to implement epoch-level calls instead with an appropriate `steps_per_epoch` value. validation_split: Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the `x` and `y` data provided, before shuffling. This argument is not supported when `x` is a dataset, generator or `keras.utils.Sequence` instance. `validation_split` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. validation_data: Data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. Thus, note the fact that the validation loss of data provided using `validation_split` or `validation_data` is not affected by regularization layers like noise and dropout. `validation_data` will override `validation_split`. `validation_data` could be: - A tuple `(x_val, y_val)` of Numpy arrays or tensors. - A tuple `(x_val, y_val, val_sample_weights)` of NumPy arrays. - A `tf.data.Dataset`. - A Python generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. `validation_data` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. shuffle: Boolean (whether to shuffle the training data before each epoch) or str (for 'batch'). This argument is ignored when `x` is a generator or an object of tf.data.Dataset. 'batch' is a special option for dealing with the limitations of HDF5 data; it shuffles in batch-sized chunks. Has no effect when `steps_per_epoch` is not `None`. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape `(samples, sequence_length)`, to apply a different weight to every timestep of every sample. This argument is not supported when `x` is a dataset, generator, or `keras.utils.Sequence` instance, instead provide the sample_weights as the third element of `x`. initial_epoch: Integer. Epoch at which to start training (useful for resuming a previous training run). steps_per_epoch: Integer or `None`. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default `None` is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a `tf.data` dataset, and 'steps_per_epoch' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the `steps_per_epoch` argument. If `steps_per_epoch=-1` the training will run indefinitely with an infinitely repeating dataset. This argument is not supported with array inputs. When using `tf.distribute.experimental.ParameterServerStrategy`: * `steps_per_epoch=None` is not supported. validation_steps: Only relevant if `validation_data` is provided and is a `tf.data` dataset. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If 'validation_steps' is None, validation will run until the `validation_data` dataset is exhausted. In the case of an infinitely repeated dataset, it will run into an infinite loop. If 'validation_steps' is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time. validation_batch_size: Integer or `None`. Number of samples per validation batch. If unspecified, will default to `batch_size`. Do not specify the `validation_batch_size` if your data is in the form of datasets, generators, or `keras.utils.Sequence` instances (since they generate batches). validation_freq: Only relevant if validation data is provided. Integer or `collections.abc.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. Unpacking behavior for iterator-like inputs: A common pattern is to pass a tf.data.Dataset, generator, or tf.keras.utils.Sequence to the `x` argument of fit, which will in fact yield not only features (x) but optionally targets (y) and sample weights. Keras requires that the output of such iterator-likes be unambiguous. The iterator should return a tuple of length 1, 2, or 3, where the optional second and third elements will be used for y and sample_weight respectively. Any other type provided will be wrapped in a length one tuple, effectively treating everything as 'x'. When yielding dicts, they should still adhere to the top-level tuple structure. e.g. `({"x0": x0, "x1": x1}, y)`. Keras will not attempt to separate features, targets, and weights from the keys of a single dict. A notable unsupported data type is the namedtuple. The reason is that it behaves like both an ordered datatype (tuple) and a mapping datatype (dict). So given a namedtuple of the form: `namedtuple("example_tuple", ["y", "x"])` it is ambiguous whether to reverse the order of the elements when interpreting the value. Even worse is a tuple of the form: `namedtuple("other_tuple", ["x", "y", "z"])` where it is unclear if the tuple was intended to be unpacked into x, y, and sample_weight or passed through as a single element to `x`. As a result the data processing code will simply raise a ValueError if it encounters a namedtuple. (Along with instructions to remedy the issue.) Returns: A `History` object. Its `History.history` attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable). Raises: RuntimeError: 1. If the model was never compiled or, 2. If `model.fit` is wrapped in `tf.function`. ValueError: In case of mismatch between the provided input data and what the model expects or when the input data is empty. """ base_layer.keras_api_gauge.get_cell('fit').set(True) # Legacy graph support is contained in `training_v1.Model`. version_utils.disallow_legacy_graph('Model', 'fit') self._assert_compile_was_called() self._check_call_args('fit') _disallow_inside_tf_function('fit') if verbose == 'auto': if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access verbose = 2 # Default to epoch-level logging for PSStrategy. else: verbose = 1 # Default to batch-level logging otherwise. if validation_split: # Create the validation data using the training data. Only supported for # `Tensor` and `NumPy` input. (x, y, sample_weight), validation_data = ( data_adapter.train_validation_split( (x, y, sample_weight), validation_split=validation_split)) if validation_data: val_x, val_y, val_sample_weight = ( data_adapter.unpack_x_y_sample_weight(validation_data)) if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access self._cluster_coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( self.distribute_strategy) with self.distribute_strategy.scope(), \ training_utils.RespectCompiledTrainableState(self): # Creates a `tf.data.Dataset` and handles batch and epoch iteration. data_handler = data_adapter.get_data_handler( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps_per_epoch, initial_epoch=initial_epoch, epochs=epochs, shuffle=shuffle, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=epochs, steps=data_handler.inferred_steps) self.stop_training = False self.train_function = self.make_train_function() self._train_counter.assign(0) callbacks.on_train_begin() training_logs = None # Handle fault-tolerance for multi-worker. # TODO(omalleyt): Fix the ordering issues that mean this has to # happen after `callbacks.on_train_begin`. data_handler._initial_epoch = ( # pylint: disable=protected-access self._maybe_load_initial_epoch_from_ckpt(initial_epoch)) logs = None for epoch, iterator in data_handler.enumerate_epochs(): self.reset_metrics() callbacks.on_epoch_begin(epoch) with data_handler.catch_stop_iteration(): for step in data_handler.steps(): with tf.profiler.experimental.Trace( 'train', epoch_num=epoch, step_num=step, batch_size=batch_size, _r=1): callbacks.on_train_batch_begin(step) tmp_logs = self.train_function(iterator) if data_handler.should_sync: context.async_wait() logs = tmp_logs # No error, now safe to assign to logs. end_step = step + data_handler.step_increment callbacks.on_train_batch_end(end_step, logs) if self.stop_training: break logs = tf_utils.sync_to_numpy_or_python_type(logs) if logs is None: raise ValueError('Expect x to be a non-empty array or dataset.') epoch_logs = copy.copy(logs) # Run validation. if validation_data and self._should_eval(epoch, validation_freq): # Create data_handler for evaluation and cache it. if getattr(self, '_eval_data_handler', None) is None: self._eval_data_handler = data_adapter.get_data_handler( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps_per_epoch=validation_steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) val_logs = self.evaluate( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps=validation_steps, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, return_dict=True, _use_cached_eval_dataset=True) val_logs = {'val_' + name: val for name, val in val_logs.items()} epoch_logs.update(val_logs) callbacks.on_epoch_end(epoch, epoch_logs) training_logs = epoch_logs if self.stop_training: break # If eval data_hanlder exists, delete it after all epochs are done. if getattr(self, '_eval_data_handler', None) is not None: del self._eval_data_handler callbacks.on_train_end(logs=training_logs) return self.history def test_step(self, data): """The logic for one evaluation step. This method can be overridden to support custom evaluation logic. This method is called by `Model.make_test_function`. This function should contain the mathematical logic for one step of evaluation. This typically includes the forward pass, loss calculation, and metrics updates. Configuration details for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_test_function`, which can also be overridden. Args: data: A nested structure of `Tensor`s. Returns: A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned. """ data = data_adapter.expand_1d(data) x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) y_pred = self(x, training=False) # Updates stateful loss metrics. self.compiled_loss( y, y_pred, sample_weight, regularization_losses=self.losses) self.compiled_metrics.update_state(y, y_pred, sample_weight) # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if isinstance(result, dict): return_metrics.update(result) else: return_metrics[metric.name] = result return return_metrics def make_test_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the test function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return a `dict` containing values that will be passed to `tf.keras.Callbacks.on_test_batch_end`. """ if self.test_function is not None and not force: return self.test_function def step_function(model, iterator): """Runs a single evaluation step.""" def run_step(data): outputs = model.test_step(data) # Ensure counter is updated only if `test_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._test_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='first') return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def test_function(iterator): """Runs an evaluation execution with one step.""" return step_function(self, iterator) else: def test_function(iterator): """Runs an evaluation execution with multiple steps.""" for _ in tf.range(self._steps_per_execution): outputs = step_function(self, iterator) return outputs if not self.run_eagerly: test_function = tf.function( test_function, experimental_relax_shapes=True) self.test_function = test_function if self._cluster_coordinator: self.test_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda test_function, args=(iterator,)) return self.test_function def evaluate(self, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, return_dict=False, **kwargs): """Returns the loss value & metrics values for the model in test mode. Computation is done in batches (see the `batch_size` arg.) Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. - A `tf.data` dataset. Should return a tuple of either `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the `Unpacking behavior for iterator-like inputs` section of `Model.fit`. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). If `x` is a dataset, generator or `keras.utils.Sequence` instance, `y` should not be specified (since targets will be obtained from the iterator/dataset). batch_size: Integer or `None`. Number of samples per batch of computation. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of a dataset, generators, or `keras.utils.Sequence` instances (since they generate batches). verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar. sample_weight: Optional Numpy array of weights for the test samples, used for weighting the loss function. You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape `(samples, sequence_length)`, to apply a different weight to every timestep of every sample. This argument is not supported when `x` is a dataset, instead pass sample weights as the third element of `x`. steps: Integer or `None`. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of `None`. If x is a `tf.data` dataset and `steps` is None, 'evaluate' will run until the dataset is exhausted. This argument is not supported with array inputs. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during evaluation. See [callbacks](/api_docs/python/tf/keras/callbacks). max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. **kwargs: Unused at this time. See the discussion of `Unpacking behavior for iterator-like inputs` for `Model.fit`. `Model.evaluate` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. Returns: Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.evaluate` is wrapped in `tf.function`. ValueError: in case of invalid arguments. """ base_layer.keras_api_gauge.get_cell('evaluate').set(True) version_utils.disallow_legacy_graph('Model', 'evaluate') self._assert_compile_was_called() self._check_call_args('evaluate') _disallow_inside_tf_function('evaluate') use_cached_eval_dataset = kwargs.pop('_use_cached_eval_dataset', False) if kwargs: raise TypeError('Invalid keyword arguments: %s' % (kwargs,)) if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access self._cluster_coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( self.distribute_strategy) with self.distribute_strategy.scope(): # Use cached evaluation data only when it's called in `Model.fit` if (use_cached_eval_dataset and getattr(self, '_eval_data_handler', None) is not None): data_handler = self._eval_data_handler else: # Creates a `tf.data.Dataset` and handles batch and epoch iteration. data_handler = data_adapter.get_data_handler( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=1, steps=data_handler.inferred_steps) logs = {} self.test_function = self.make_test_function() self._test_counter.assign(0) callbacks.on_test_begin() for _, iterator in data_handler.enumerate_epochs(): # Single epoch. self.reset_metrics() with data_handler.catch_stop_iteration(): for step in data_handler.steps(): with tf.profiler.experimental.Trace('test', step_num=step, _r=1): callbacks.on_test_batch_begin(step) tmp_logs = self.test_function(iterator) if data_handler.should_sync: context.async_wait() logs = tmp_logs # No error, now safe to assign to logs. end_step = step + data_handler.step_increment callbacks.on_test_batch_end(end_step, logs) logs = tf_utils.sync_to_numpy_or_python_type(logs) callbacks.on_test_end(logs=logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names) def predict_step(self, data): """The logic for one inference step. This method can be overridden to support custom inference logic. This method is called by `Model.make_predict_function`. This method should contain the mathematical logic for one step of inference. This typically includes the forward pass. Configuration details for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_predict_function`, which can also be overridden. Args: data: A nested structure of `Tensor`s. Returns: The result of one inference step, typically the output of calling the `Model` on data. """ data = data_adapter.expand_1d(data) x, _, _ = data_adapter.unpack_x_y_sample_weight(data) return self(x, training=False) def make_predict_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the predict function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return the outputs of the `Model`. """ if self.predict_function is not None and not force: return self.predict_function def step_function(model, iterator): """Runs a single evaluation step.""" def run_step(data): outputs = model.predict_step(data) # Ensure counter is updated only if `test_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._predict_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='concat') return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def predict_function(iterator): """Runs an evaluation execution with one step.""" return step_function(self, iterator) else: def predict_function(iterator): """Runs an evaluation execution with multiple steps.""" outputs = step_function(self, iterator) for _ in tf.range(self._steps_per_execution - 1): tf.autograph.experimental.set_loop_options( shape_invariants=[( t, tf_utils.get_tensor_spec(t, dynamic_batch=True).shape) for t in tf.nest.flatten(outputs)]) step_outputs = step_function(self, iterator) outputs = tf.nest.map_structure(lambda t1, t2: concat([t1, t2]), outputs, step_outputs) return outputs if not self.run_eagerly: predict_function = tf.function( predict_function, experimental_relax_shapes=True) self.predict_function = predict_function return self.predict_function def predict(self, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): """Generates output predictions for the input samples. Computation is done in batches. This method is designed for performance in large scale inputs. For small amount of inputs that fit in one batch, directly using `__call__` is recommended for faster execution, e.g., `model(x)`, or `model(x, training=False)` if you have layers such as `tf.keras.layers.BatchNormalization` that behaves differently during inference. Also, note the fact that test loss is not affected by regularization layers like noise and dropout. Args: x: Input samples. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A `tf.data` dataset. - A generator or `keras.utils.Sequence` instance. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the `Unpacking behavior for iterator-like inputs` section of `Model.fit`. batch_size: Integer or `None`. Number of samples per batch. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of dataset, generators, or `keras.utils.Sequence` instances (since they generate batches). verbose: Verbosity mode, 0 or 1. steps: Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of `None`. If x is a `tf.data` dataset and `steps` is None, `predict` will run until the input dataset is exhausted. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during prediction. See [callbacks](/api_docs/python/tf/keras/callbacks). max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. See the discussion of `Unpacking behavior for iterator-like inputs` for `Model.fit`. Note that Model.predict uses the same interpretation rules as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all three methods. Returns: Numpy array(s) of predictions. Raises: RuntimeError: If `model.predict` is wrapped in `tf.function`. ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size. """ base_layer.keras_api_gauge.get_cell('predict').set(True) version_utils.disallow_legacy_graph('Model', 'predict') self._check_call_args('predict') _disallow_inside_tf_function('predict') # TODO(yashkatariya): Cache model on the coordinator for faster prediction. # If running under PSS, then swap it with OneDeviceStrategy so that # execution will run on the coordinator. original_pss_strategy = None if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access original_pss_strategy = self.distribute_strategy self._distribution_strategy = None # Cluster coordinator is set by `.fit()` and `.evaluate()` which is not # needed in `.predict()` because all the predictions happen on the # coordinator/locally. if self._cluster_coordinator: self._cluster_coordinator = None outputs = None with self.distribute_strategy.scope(): # Creates a `tf.data.Dataset` and handles batch and epoch iteration. dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset) if (self._in_multi_worker_mode() or _is_tpu_multi_host( self.distribute_strategy)) and isinstance(x, dataset_types): try: options = tf.data.Options() data_option = tf.data.experimental.AutoShardPolicy.DATA options.experimental_distribute.auto_shard_policy = data_option x = x.with_options(options) except ValueError: warnings.warn('Using Model.predict with ' 'MultiWorkerDistributionStrategy or TPUStrategy and ' 'AutoShardPolicy.FILE might lead to out-of-order result' '. Consider setting it to AutoShardPolicy.DATA.') data_handler = data_adapter.get_data_handler( x=x, batch_size=batch_size, steps_per_epoch=steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=1, steps=data_handler.inferred_steps) self.predict_function = self.make_predict_function() self._predict_counter.assign(0) callbacks.on_predict_begin() batch_outputs = None for _, iterator in data_handler.enumerate_epochs(): # Single epoch. with data_handler.catch_stop_iteration(): for step in data_handler.steps(): callbacks.on_predict_batch_begin(step) tmp_batch_outputs = self.predict_function(iterator) if data_handler.should_sync: context.async_wait() batch_outputs = tmp_batch_outputs # No error, now safe to assign. if outputs is None: outputs = tf.nest.map_structure(lambda batch_output: [batch_output], batch_outputs) else: tf.__internal__.nest.map_structure_up_to( batch_outputs, lambda output, batch_output: output.append(batch_output), outputs, batch_outputs) end_step = step + data_handler.step_increment callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs}) if batch_outputs is None: raise ValueError('Expect x to be a non-empty array or dataset.') callbacks.on_predict_end() all_outputs = tf.__internal__.nest.map_structure_up_to(batch_outputs, concat, outputs) # If originally PSS strategy was used, then replace it back since predict # is running under `OneDeviceStrategy` after the swap and once its done # we need to replace it back to PSS again. if original_pss_strategy is not None: self._distribution_strategy = original_pss_strategy return tf_utils.sync_to_numpy_or_python_type(all_outputs) def reset_metrics(self): """Resets the state of all the metrics in the model. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> _ = model.fit(x, y, verbose=0) >>> assert all(float(m.result()) for m in model.metrics) >>> model.reset_metrics() >>> assert all(float(m.result()) == 0 for m in model.metrics) """ for m in self.metrics: m.reset_state() def train_on_batch(self, x, y=None, sample_weight=None, class_weight=None, reset_metrics=True, return_dict=False): """Runs a single gradient update on a single batch of data. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). sample_weight: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. reset_metrics: If `True`, the metrics returned will be only for this batch. If `False`, the metrics will be statefully accumulated across batches. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. Returns: Scalar training loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.train_on_batch` is wrapped in `tf.function`. ValueError: In case of invalid user-provided arguments. """ self._assert_compile_was_called() self._check_call_args('train_on_batch') _disallow_inside_tf_function('train_on_batch') with self.distribute_strategy.scope(), \ training_utils.RespectCompiledTrainableState(self): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, y, sample_weight, class_weight) self.train_function = self.make_train_function() logs = self.train_function(iterator) if reset_metrics: self.reset_metrics() logs = tf_utils.sync_to_numpy_or_python_type(logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names) def test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True, return_dict=False): """Test the model on a single batch of samples. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). sample_weight: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. reset_metrics: If `True`, the metrics returned will be only for this batch. If `False`, the metrics will be statefully accumulated across batches. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. Returns: Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.test_on_batch` is wrapped in `tf.function`. ValueError: In case of invalid user-provided arguments. """ self._assert_compile_was_called() self._check_call_args('test_on_batch') _disallow_inside_tf_function('test_on_batch') with self.distribute_strategy.scope(): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, y, sample_weight) self.test_function = self.make_test_function() logs = self.test_function(iterator) if reset_metrics: self.reset_metrics() logs = tf_utils.sync_to_numpy_or_python_type(logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names) def predict_on_batch(self, x): """Returns predictions for a single batch of samples. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). Returns: Numpy array(s) of predictions. Raises: RuntimeError: If `model.predict_on_batch` is wrapped in `tf.function`. ValueError: In case of mismatch between given number of inputs and expectations of the model. """ self._check_call_args('predict_on_batch') _disallow_inside_tf_function('predict_on_batch') with self.distribute_strategy.scope(): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x) self.predict_function = self.make_predict_function() outputs = self.predict_function(iterator) return tf_utils.sync_to_numpy_or_python_type(outputs) @doc_controls.do_not_generate_docs def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0): """Fits the model on data yielded batch-by-batch by a Python generator. DEPRECATED: `Model.fit` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.fit_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.fit`, which supports generators.') return self.fit( generator, steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, shuffle=shuffle, initial_epoch=initial_epoch) @doc_controls.do_not_generate_docs def evaluate_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0): """Evaluates the model on a data generator. DEPRECATED: `Model.evaluate` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.evaluate_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.evaluate`, which supports generators.') self._check_call_args('evaluate_generator') return self.evaluate( generator, steps=steps, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, verbose=verbose, callbacks=callbacks) @doc_controls.do_not_generate_docs def predict_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0): """Generates predictions for the input samples from a data generator. DEPRECATED: `Model.predict` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.predict_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.predict`, which supports generators.') return self.predict( generator, steps=steps, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, verbose=verbose, callbacks=callbacks) ###################################################################### # Functions below are not training related. They are for model weights # tracking, save/load, serialization, etc. ###################################################################### @property def trainable_weights(self): self._assert_weights_created() if not self._trainable: return [] trainable_variables = [] for trackable_obj in self._self_tracked_trackables: trainable_variables += trackable_obj.trainable_variables trainable_variables += self._trainable_weights return self._dedup_weights(trainable_variables) @property def non_trainable_weights(self): self._assert_weights_created() non_trainable_variables = [] for trackable_obj in self._self_tracked_trackables: non_trainable_variables += trackable_obj.non_trainable_variables if not self._trainable: # Return order is all trainable vars, then all non-trainable vars. trainable_variables = [] for trackable_obj in self._self_tracked_trackables: trainable_variables += trackable_obj.trainable_variables non_trainable_variables = ( trainable_variables + self._trainable_weights + non_trainable_variables + self._non_trainable_weights) else: non_trainable_variables = ( non_trainable_variables + self._non_trainable_weights) return self._dedup_weights(non_trainable_variables) def get_weights(self): """Retrieves the weights of the model. Returns: A flat list of Numpy arrays. """ with self.distribute_strategy.scope(): return super(Model, self).get_weights() def save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True): # pylint: disable=line-too-long """Saves the model to Tensorflow SavedModel or a single HDF5 file. Please see `tf.keras.models.save_model` or the [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) for details. Args: filepath: String, PathLike, path to SavedModel or H5 file to save the model. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. include_optimizer: If True, save optimizer's state together. save_format: Either `'tf'` or `'h5'`, indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. signatures: Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the `signatures` argument in `tf.saved_model.save` for details. options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` object that specifies options for saving to SavedModel. save_traces: (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to `True`. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a `get_config()` method. Example: ```python from keras.models import load_model model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a compiled model # identical to the previous one model = load_model('my_model.h5') ``` """ # pylint: enable=line-too-long save.save_model(self, filepath, overwrite, include_optimizer, save_format, signatures, options, save_traces) def save_weights(self, filepath, overwrite=True, save_format=None, options=None): """Saves all layer weights. Either saves in HDF5 or in TensorFlow format based on the `save_format` argument. When saving in HDF5 format, the weight file has: - `layer_names` (attribute), a list of strings (ordered names of model layers). - For every layer, a `group` named `layer.name` - For every such layer group, a group attribute `weight_names`, a list of strings (ordered names of weights tensor of the layer). - For every weight in the layer, a dataset storing the weight value, named after the weight tensor. When saving in TensorFlow format, all objects referenced by the network are saved in the same format as `tf.train.Checkpoint`, including any `Layer` instances or `Optimizer` instances assigned to object attributes. For networks constructed from inputs and outputs using `tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network are tracked/saved automatically. For user-defined classes which inherit from `tf.keras.Model`, `Layer` instances must be assigned to object attributes, typically in the constructor. See the documentation of `tf.train.Checkpoint` and `tf.keras.Model` for details. While the formats are the same, do not mix `save_weights` and `tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should be loaded using `Model.load_weights`. Checkpoints saved using `tf.train.Checkpoint.save` should be restored using the corresponding `tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over `save_weights` for training checkpoints. The TensorFlow format matches objects and variables by starting at a root object, `self` for `save_weights`, and greedily matching attribute names. For `Model.save` this is the `Model`, and for `Checkpoint.save` this is the `Checkpoint` even if the `Checkpoint` has a model attached. This means saving a `tf.keras.Model` using `save_weights` and loading into a `tf.train.Checkpoint` with a `Model` attached (or vice versa) will not match the `Model`'s variables. See the [guide to training checkpoints](https://www.tensorflow.org/guide/checkpoint) for details on the TensorFlow format. Args: filepath: String or PathLike, path to the file to save the weights to. When saving in TensorFlow format, this is the prefix used for checkpoint files (multiple files are generated). Note that the '.h5' suffix causes weights to be saved in HDF5 format. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or '.keras' will default to HDF5 if `save_format` is `None`. Otherwise `None` defaults to 'tf'. options: Optional `tf.train.CheckpointOptions` object that specifies options for saving weights. Raises: ImportError: If h5py is not available when attempting to save in HDF5 format. ValueError: For invalid/unknown format arguments. """ self._assert_weights_created() filepath = path_to_string(filepath) filepath_is_h5 = saving_utils.is_hdf5_filepath(filepath) if save_format is None: if filepath_is_h5: save_format = 'h5' else: save_format = 'tf' else: user_format = save_format.lower().strip() if user_format in ('tensorflow', 'tf'): save_format = 'tf' elif user_format in ('hdf5', 'h5', 'keras'): save_format = 'h5' else: raise ValueError( 'Unknown format "%s". Was expecting one of {"tf", "h5"}.' % ( save_format,)) if save_format == 'tf' and filepath_is_h5: raise ValueError( ('save_weights got save_format="tf"/"tensorflow", but the ' 'filepath ("%s") looks like an HDF5 file. Omit the ".h5"/".keras" ' 'when saving in TensorFlow format.') % filepath) if save_format == 'h5' and h5py is None: raise ImportError( '`save_weights` requires h5py when saving in hdf5.') if save_format == 'tf': check_filepath = filepath + '.index' else: check_filepath = filepath # If file exists and should not be overwritten: if not overwrite and os.path.isfile(check_filepath): proceed = ask_to_proceed_with_overwrite(check_filepath) if not proceed: return if save_format == 'h5': with h5py.File(filepath, 'w') as f: hdf5_format.save_weights_to_hdf5_group(f, self.layers) else: if tf.executing_eagerly(): session = None else: session = backend.get_session() self._trackable_saver.save(filepath, session=session, options=options) # Record this checkpoint so it's visible from tf.train.latest_checkpoint. tf.__internal__.train.update_checkpoint_state( save_dir=os.path.dirname(filepath), model_checkpoint_path=filepath, save_relative_paths=True, all_model_checkpoint_paths=[filepath]) def load_weights(self, filepath, by_name=False, skip_mismatch=False, options=None): """Loads all layer weights, either from a TensorFlow or an HDF5 weight file. If `by_name` is False weights are loaded based on the network's topology. This means the architecture should be the same as when the weights were saved. Note that layers that don't have weights are not taken into account in the topological ordering, so adding or removing layers is fine as long as they don't have weights. If `by_name` is True, weights are loaded into layers only if they share the same name. This is useful for fine-tuning or transfer-learning models where some of the layers have changed. Only topological loading (`by_name=False`) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which layers are assigned in the `Model`'s constructor. Args: filepath: String, path to the weights file to load. For weight files in TensorFlow format, this is the file prefix (the same as was passed to `save_weights`). This can also be a path to a SavedModel saved from `model.save`. by_name: Boolean, whether to load weights by name or by topological order. Only topological loading is supported for weight files in TensorFlow format. skip_mismatch: Boolean, whether to skip loading of layers where there is a mismatch in the number of weights, or a mismatch in the shape of the weight (only valid when `by_name=True`). options: Optional `tf.train.CheckpointOptions` object that specifies options for loading weights. Returns: When loading a weight file in TensorFlow format, returns the same status object as `tf.train.Checkpoint.restore`. When graph building, restore ops are run automatically as soon as the network is built (on first call for user-defined classes inheriting from `Model`, immediately if it is already built). When loading weights in HDF5 format, returns `None`. Raises: ImportError: If h5py is not available and the weight file is in HDF5 format. ValueError: If `skip_mismatch` is set to `True` when `by_name` is `False`. """ if backend.is_tpu_strategy(self._distribution_strategy): if (self._distribution_strategy.extended.steps_per_run > 1 and (not saving_utils.is_hdf5_filepath(filepath))): raise ValueError('Load weights is not yet supported with TPUStrategy ' 'with steps_per_run greater than 1.') if skip_mismatch and not by_name: raise ValueError( 'When calling model.load_weights, skip_mismatch can only be set to ' 'True when by_name is True.') filepath, save_format = _detect_save_format(filepath) if save_format == 'tf': status = self._trackable_saver.restore(filepath, options) if by_name: raise NotImplementedError( 'Weights may only be loaded based on topology into Models when ' 'loading TensorFlow-formatted weights (got by_name=True to ' 'load_weights).') if not tf.executing_eagerly(): session = backend.get_session() # Restore existing variables (if any) immediately, and set up a # streaming restore for any variables created in the future. tf.__internal__.tracking.streaming_restore(status=status, session=session) status.assert_nontrivial_match() else: status = None if h5py is None: raise ImportError( '`load_weights` requires h5py when loading weights from HDF5.') if not self._is_graph_network and not self.built: raise ValueError( 'Unable to load weights saved in HDF5 format into a subclassed ' 'Model which has not created its variables yet. Call the Model ' 'first, then load the weights.') self._assert_weights_created() with h5py.File(filepath, 'r') as f: if 'layer_names' not in f.attrs and 'model_weights' in f: f = f['model_weights'] if by_name: hdf5_format.load_weights_from_hdf5_group_by_name( f, self.layers, skip_mismatch=skip_mismatch) else: hdf5_format.load_weights_from_hdf5_group(f, self.layers) # Perform any layer defined finalization of the layer state. for layer in self.layers: layer.finalize_state() return status def _updated_config(self): """Util shared between different serialization methods. Returns: Model config with Keras version information added. """ from keras import __version__ as keras_version # pylint: disable=g-import-not-at-top config = self.get_config() model_config = { 'class_name': self.__class__.__name__, 'config': config, 'keras_version': keras_version, 'backend': backend.backend() } return model_config def get_config(self): raise NotImplementedError @classmethod def from_config(cls, config, custom_objects=None): # `from_config` assumes `cls` is either `Functional` or a child class of # `Functional`. In the case that `cls` is meant to behave like a child class # of `Functional` but only inherits from the `Model` class, we have to call # `cls(...)` instead of `Functional.from_config`. from keras.engine import functional # pylint: disable=g-import-not-at-top with generic_utils.SharedObjectLoadingScope(): input_tensors, output_tensors, created_layers = ( functional.reconstruct_from_config(config, custom_objects)) # Initialize a model belonging to `cls`, which can be user-defined or # `Functional`. model = cls(inputs=input_tensors, outputs=output_tensors, name=config.get('name')) functional.connect_ancillary_layers(model, created_layers) return model def to_json(self, **kwargs): """Returns a JSON string containing the network configuration. To load a network from a JSON save file, use `keras.models.model_from_json(json_string, custom_objects={})`. Args: **kwargs: Additional keyword arguments to be passed to `json.dumps()`. Returns: A JSON string. """ model_config = self._updated_config() return json.dumps( model_config, default=json_utils.get_json_type, **kwargs) def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. 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. Args: **kwargs: Additional keyword arguments to be passed to `yaml.dump()`. Returns: A YAML string. Raises: RuntimeError: announces that the method poses a security risk (Use the safer `safe_load` function instead of `unsafe_load` when possible) """ raise RuntimeError( 'Method `model.to_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `model.to_json()` instead.' ) def reset_states(self): for layer in self.layers: if hasattr(layer, 'reset_states') and getattr(layer, 'stateful', False): layer.reset_states() @property @doc_controls.do_not_generate_docs def state_updates(self): """Deprecated, do NOT use! Returns the `updates` from all layers that are stateful. This is useful for separating training updates and state updates, e.g. when we need to update a layer's internal state during prediction. Returns: A list of update ops. """ warnings.warn('`Model.state_updates` will be removed in a future version. ' 'This property should not be used in TensorFlow 2.0, ' 'as `updates` are applied automatically.') state_updates = [] for layer in self.layers: if getattr(layer, 'stateful', False): if hasattr(layer, 'updates'): state_updates += layer.updates return state_updates @property def weights(self): """Returns the list of all layer variables/weights. Note: This will not track the weights of nested `tf.Modules` that are not themselves Keras layers. Returns: A list of variables. """ return self._dedup_weights(self._undeduplicated_weights) @property def _undeduplicated_weights(self): """Returns the undeduplicated list of all layer variables/weights.""" self._assert_weights_created() weights = [] for layer in self._self_tracked_trackables: weights += layer.variables weights += (self._trainable_weights + self._non_trainable_weights) return weights def summary(self, line_length=None, positions=None, print_fn=None): """Prints a string summary of the network. Args: line_length: Total length of printed lines (e.g. set this to adapt the display to different terminal window sizes). positions: Relative or absolute positions of log elements in each line. If not provided, defaults to `[.33, .55, .67, 1.]`. print_fn: Print function to use. Defaults to `print`. It will be called on each line of the summary. You can set it to a custom function in order to capture the string summary. Raises: ValueError: if `summary()` is called before the model is built. """ if not self.built: raise ValueError('This model has not yet been built. ' 'Build the model first by calling `build()` or calling ' '`fit()` with some data, or specify ' 'an `input_shape` argument in the first layer(s) for ' 'automatic build.') layer_utils.print_summary(self, line_length=line_length, positions=positions, print_fn=print_fn) @property def layers(self): return list(self._flatten_layers(include_self=False, recursive=False)) def get_layer(self, name=None, index=None): """Retrieves a layer based on either its name (unique) or index. If `name` and `index` are both provided, `index` will take precedence. Indices are based on order of horizontal graph traversal (bottom-up). Args: name: String, name of layer. index: Integer, index of layer. Returns: A layer instance. Raises: ValueError: In case of invalid layer name or index. """ # TODO(fchollet): We could build a dictionary based on layer names # since they are constant, but we have not done that yet. if index is not None and name is not None: raise ValueError('Provide only a layer name or a layer index.') if index is not None: if len(self.layers) <= index: raise ValueError('Was asked to retrieve layer at index ' + str(index) + ' but model only has ' + str(len(self.layers)) + ' layers.') else: return self.layers[index] if name is not None: for layer in self.layers: if layer.name == name: return layer raise ValueError('No such layer: ' + name + '.') raise ValueError('Provide either a layer name or layer index.') @tf.__internal__.tracking.no_automatic_dependency_tracking def _set_save_spec(self, inputs, args=None, kwargs=None): """Defines the save spec so that serialization is able to trace model call. The TensorSpecs of the call function `inputs`, `args`, and `kwargs` are saved into a tuple of `([inputs] + args, kwargs)`. The input `TensorSpec` names are updated to match the built `input_names`. The specs can be retrieved with the `save_spec` property. Args: inputs: possibly nested inputs passed into the call function. args: a list of positional arguments passed into call. kwargs: a dictionary of keyword arguments passed into call. """ if self._saved_model_inputs_spec is not None: return # Already set. args = args or [] kwargs = kwargs or {} input_names = self.input_names if not input_names: input_names = compile_utils.create_pseudo_input_names(inputs) flat_inputs = tf.nest.flatten(inputs) inputs_spec = [] for name, tensor in zip(input_names, flat_inputs): inputs_spec.append( tf_utils.get_tensor_spec(tensor, dynamic_batch=False, name=name)) inputs_spec = tf.nest.pack_sequence_as(inputs, inputs_spec) super(Model, self)._set_save_spec(inputs_spec, args, kwargs) # Store the input shapes if (self.__class__.__name__ == 'Sequential' and self._build_input_shape is None): self._build_input_shape = tf.nest.map_structure( lambda x: None if x is None else x.shape, inputs_spec) def save_spec(self, dynamic_batch=True): """Returns the `tf.TensorSpec` of call inputs as a tuple `(args, kwargs)`. This value is automatically defined after calling the model for the first time. Afterwards, you can use it when exporting the model for serving: ```python model = tf.keras.Model(...) @tf.function def serve(*args, **kwargs): outputs = model(*args, **kwargs) # Apply postprocessing steps, or add additional outputs. ... return outputs # arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this example, is # an empty dict since functional models do not use keyword arguments. arg_specs, kwarg_specs = model.save_spec() model.save(path, signatures={ 'serving_default': serve.get_concrete_function(*arg_specs, **kwarg_specs) }) ``` Args: dynamic_batch: Whether to set the batch sizes of all the returned `tf.TensorSpec` to `None`. (Note that when defining functional or Sequential models with `tf.keras.Input([...], batch_size=X)`, the batch size will always be preserved). Defaults to `True`. Returns: If the model inputs are defined, returns a tuple `(args, kwargs)`. All elements in `args` and `kwargs` are `tf.TensorSpec`. If the model inputs are not defined, returns `None`. The model inputs are automatically set when calling the model, `model.fit`, `model.evaluate` or `model.predict`. """ return self._get_save_spec(dynamic_batch, inputs_only=False) def _assert_weights_created(self): """Asserts that all the weights for the model have been created. For a non-dynamic model, the weights must already be created after the layer has been called. For a dynamic model, the exact list of weights can never be known for certain since it may change at any time during execution. We run this check right before accessing weights or getting the Numpy value for the current weights. Otherwise, if the layer has never been called, the user would just get an empty list, which is misleading. Raises: ValueError: if the weights of the network has not yet been created. """ if self.dynamic: return if ('build' in self.__class__.__dict__ and self.__class__ != Model and not self.built): # For any model that has customized build() method but hasn't # been invoked yet, this will cover both sequential and subclass model. # Also make sure to exclude Model class itself which has build() defined. raise ValueError('Weights for model %s have not yet been created. ' 'Weights are created when the Model is first called on ' 'inputs or `build()` is called with an `input_shape`.' % self.name) def _check_call_args(self, method_name): """Check that `call` has only one positional arg.""" # Always allow first arg, regardless of arg name. fullargspec = self._call_full_argspec if fullargspec.defaults: positional_args = fullargspec.args[:-len(fullargspec.defaults)] else: positional_args = fullargspec.args if 'training' in positional_args: positional_args.remove('training') # self and first arg can be positional. if len(positional_args) > 2: extra_args = positional_args[2:] raise ValueError( 'Models passed to `' + method_name + '` can only have `training` ' 'and the first argument in `call` as positional arguments, ' 'found: ' + str(extra_args) + '.') def _validate_compile(self, optimizer, metrics, **kwargs): """Performs validation checks for the default `compile`.""" if any( isinstance(opt, optimizer_v1.Optimizer) for opt in tf.nest.flatten(optimizer)): raise ValueError( '`tf.compat.v1.keras` Optimizer (', optimizer, ') is ' 'not supported when eager execution is enabled. Use a ' '`tf.keras` Optimizer instead, or disable eager ' 'execution.') kwargs.pop('cloning', None) # Legacy DistStrat argument, never used. kwargs.pop('experimental_run_tf_function', None) # Always `True`. if kwargs.pop('distribute', None) is not None: raise ValueError( 'Distribute argument in compile is not available in TF 2.0 please ' 'create the model under the distribution strategy scope.') if kwargs.pop('target_tensors', None) is not None: raise ValueError( 'target_tensors argument is not supported when executing eagerly.') invalid_kwargs = set(kwargs) - {'sample_weight_mode'} if invalid_kwargs: raise TypeError('Invalid keyword argument(s) in `compile`: %s' % (invalid_kwargs,)) # Model must be created and compiled with the same DistStrat. if self.built and tf.distribute.has_strategy(): strategy = tf.distribute.get_strategy() for v in self.variables: if not strategy.extended.variable_created_in_scope(v): raise ValueError( 'Variable (%s) was not created in the distribution strategy ' 'scope of (%s). It is most likely due to not all layers or ' 'the model or optimizer being created outside the distribution ' 'strategy scope. Try to make sure your code looks similar ' 'to the following.\n' 'with strategy.scope():\n' ' model=_create_model()\n' ' model.compile(...)' % (v, strategy)) # Model metrics must be created in the same distribution strategy scope # as the model. strategy = self.distribute_strategy for metric in tf.nest.flatten(metrics): for v in getattr(metric, 'variables', []): if not strategy.extended.variable_created_in_scope(v): raise ValueError( 'Metric (%s) passed to model.compile was created inside of a ' 'different distribution strategy scope than the model. All ' 'metrics must be created in the same distribution strategy ' 'scope as the model (in this case %s). If you pass in a string ' 'identifier for a metric to compile the metric will ' 'automatically be created in the correct distribution ' 'strategy scope.' % (metric, strategy) ) # Model metrics must be created in the same distribution strategy scope # as the model. for opt in tf.nest.flatten(optimizer): for v in getattr(opt, '_weights', []): if not strategy.extended.variable_created_in_scope(v): raise ValueError( 'Optimizer (%s) passed to model.compile was created inside of a ' 'different distribution strategy scope than the model. All ' 'optimizers must be created in the same distribution strategy ' 'scope as the model (in this case %s). If you pass in a string ' 'identifier for an optimizer to compile the optimizer will ' 'automatically be created in the correct distribution ' 'strategy scope.' % (opt, strategy)) def _maybe_load_initial_epoch_from_ckpt(self, initial_epoch): """Maybe load initial epoch from ckpt considering possible worker recovery. Refer to tensorflow/python/keras/distribute/worker_training_state.py for more information. Args: initial_epoch: The original initial_epoch user passes in in `fit()`. Returns: If the training is recovering from previous failure under multi-worker training setting, return the epoch the training is supposed to continue at. Otherwise, return the `initial_epoch` the user passes in. """ if self._training_state is not None: return self._training_state.maybe_load_initial_epoch_from_ckpt( initial_epoch, mode=ModeKeys.TRAIN) return initial_epoch def _assert_compile_was_called(self): # Checks whether `compile` has been called. If it has been called, # then the optimizer is set. This is different from whether the # model is compiled # (i.e. whether the model is built and its inputs/outputs are set). if not self._is_compiled: raise RuntimeError('You must compile your model before ' 'training/testing. ' 'Use `model.compile(optimizer, loss)`.') def _set_inputs(self, inputs, outputs=None, training=None): """This method is for compat with Modelv1. Only inputs are needed here.""" self._set_save_spec(inputs) @property def _trackable_saved_model_saver(self): return model_serialization.ModelSavedModelSaver(self) def _list_functions_for_serialization(self, serialization_cache): # SavedModel needs to ignore the execution functions. train_function = self.train_function test_function = self.test_function predict_function = self.predict_function train_tf_function = self.train_tf_function self.train_function = None self.test_function = None self.predict_function = None self.train_tf_function = None functions = super( Model, self)._list_functions_for_serialization(serialization_cache) self.train_function = train_function self.test_function = test_function self.predict_function = predict_function self.train_tf_function = train_tf_function return functions def _should_eval(self, epoch, validation_freq): epoch = epoch + 1 # one-index the user-facing epoch. if isinstance(validation_freq, int): return epoch % validation_freq == 0 elif isinstance(validation_freq, list): return epoch in validation_freq else: raise ValueError('Expected `validation_freq` to be a list or int.') ###################################################################### # Functions below exist only as v1 / v2 compatibility shims. ###################################################################### def _get_compile_args(self, user_metrics=True): """Used for saving or cloning a Model. Args: user_metrics: Whether to return user-supplied metrics or `Metric` objects. Defaults to returning the user-supplied metrics. Returns: Dictionary of arguments that were used when compiling the model. """ self._assert_compile_was_called() # pylint: disable=protected-access saved_metrics = self.compiled_metrics._user_metrics saved_weighted_metrics = self.compiled_metrics._user_weighted_metrics if not user_metrics: if saved_metrics is not None: saved_metrics = self.compiled_metrics._metrics if saved_weighted_metrics is not None: saved_weighted_metrics = self.compiled_metrics._weighted_metrics compile_args = { 'optimizer': self.optimizer, 'loss': self.compiled_loss._user_losses, 'metrics': saved_metrics, 'weighted_metrics': saved_weighted_metrics, 'loss_weights': self.compiled_loss._user_loss_weights, } # pylint: enable=protected-access return compile_args def _get_callback_model(self): return self def _in_multi_worker_mode(self): return self.distribute_strategy.extended._in_multi_worker_mode() # pylint: disable=protected-access @property def _compile_was_called(self): return self._is_compiled
Ancestors
- Layer
- tensorflow.python.module.module.Module
- tensorflow.python.training.tracking.tracking.AutoTrackable
- tensorflow.python.training.tracking.base.Trackable
- LayerVersionSelector
- ModelVersionSelector
Subclasses
- DeterministicModel
- SubclassedModel
- keras.distribute.simple_models._SimpleModel
- Functional
- Model
- LinearModel
- WideDeepModel
- SmallSubclassMLP
- keras.testing_utils._MultiIOSubclassModel
- keras.testing_utils._MultiIOSubclassModelCustomBuild
- keras.testing_utils._SmallSubclassMLPCustomBuild
- keras.testing_utils._SubclassModel
- keras.testing_utils._SubclassModelCustomBuild
- MySubclassModel
- CustomCallModel
- NestedTestModel1
- NestedTestModel2
- SimpleConvTestModel
- TrainingMaskingModel
- TrainingNoDefaultModel
Instance variables
var distribute_strategy
-
The
tf.distribute.Strategy
this model was created under.Expand source code
@property def distribute_strategy(self): """The `tf.distribute.Strategy` this model was created under.""" return self._distribution_strategy or tf.distribute.get_strategy()
var layers
-
Expand source code
@property def layers(self): return list(self._flatten_layers(include_self=False, recursive=False))
var metrics
-
Returns the model's metrics added using
compile
,add_metric
APIs.Note: Metrics passed to
compile()
are available only after akeras.Model
has been trained/evaluated on actual data.Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> [m.name for m in model.metrics] []
>>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> [m.name for m in model.metrics] ['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.add_metric( ... tf.reduce_sum(output_2), name='mean', aggregation='mean') >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> [m.name for m in model.metrics] ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc', 'mean']
Expand source code
@property def metrics(self): """Returns the model's metrics added using `compile`, `add_metric` APIs. Note: Metrics passed to `compile()` are available only after a `keras.Model` has been trained/evaluated on actual data. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> [m.name for m in model.metrics] [] >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> [m.name for m in model.metrics] ['loss', 'mae'] >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.add_metric( ... tf.reduce_sum(output_2), name='mean', aggregation='mean') >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> [m.name for m in model.metrics] ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc', 'mean'] """ metrics = [] if self._is_compiled: # TODO(omalleyt): Track `LossesContainer` and `MetricsContainer` objects # so that attr names are not load-bearing. if self.compiled_loss is not None: metrics += self.compiled_loss.metrics if self.compiled_metrics is not None: metrics += self.compiled_metrics.metrics for l in self._flatten_layers(): metrics.extend(l._metrics) # pylint: disable=protected-access return metrics
var metrics_names
-
Returns the model's display labels for all outputs.
Note:
metrics_names
are available only after akeras.Model
has been trained/evaluated on actual data.Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> model.metrics_names []
>>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> model.metrics_names ['loss', 'mae']
>>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> model.metrics_names ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc']
Expand source code
@property def metrics_names(self): """Returns the model's display labels for all outputs. Note: `metrics_names` are available only after a `keras.Model` has been trained/evaluated on actual data. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> model.metrics_names [] >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> model.fit(x, y) >>> model.metrics_names ['loss', 'mae'] >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> d = tf.keras.layers.Dense(2, name='out') >>> output_1 = d(inputs) >>> output_2 = d(inputs) >>> model = tf.keras.models.Model( ... inputs=inputs, outputs=[output_1, output_2]) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) >>> model.fit(x, (y, y)) >>> model.metrics_names ['loss', 'out_loss', 'out_1_loss', 'out_mae', 'out_acc', 'out_1_mae', 'out_1_acc'] """ # This property includes all output names including `loss` and per-output # losses for backward compatibility. return [m.name for m in self.metrics]
var run_eagerly
-
Settable attribute indicating whether the model should run eagerly.
Running eagerly means that your model will be run step by step, like Python code. Your model might run slower, but it should become easier for you to debug it by stepping into individual layer calls.
By default, we will attempt to compile your model to a static graph to deliver the best execution performance.
Returns
Boolean, whether the model should run eagerly.
Expand source code
@property def run_eagerly(self): """Settable attribute indicating whether the model should run eagerly. Running eagerly means that your model will be run step by step, like Python code. Your model might run slower, but it should become easier for you to debug it by stepping into individual layer calls. By default, we will attempt to compile your model to a static graph to deliver the best execution performance. Returns: Boolean, whether the model should run eagerly. """ if self.dynamic and self._run_eagerly is False: # pylint:disable=g-bool-id-comparison # TODO(fchollet): consider using py_func to enable this. raise ValueError('Your model contains layers that can only be ' 'successfully run in eager execution (layers ' 'constructed with `dynamic=True`). ' 'You cannot set `run_eagerly=False`.') if self._cluster_coordinator and self._run_eagerly: raise ValueError('When using `Model` with `ParameterServerStrategy`, ' '`run_eagerly` is not supported.') # Run eagerly logic, by priority: # (1) Dynamic models must be run eagerly. # (2) Explicitly setting run_eagerly causes a Model to be run eagerly. # (3) Not explicitly setting run_eagerly defaults to TF's global setting. return (self.dynamic or self._run_eagerly or (tf.config.functions_run_eagerly() and self._run_eagerly is None))
var state_updates
-
Deprecated, do NOT use!
Returns the
updates
from all layers that are stateful.This is useful for separating training updates and state updates, e.g. when we need to update a layer's internal state during prediction.
Returns
A list of update ops.
Expand source code
@property @doc_controls.do_not_generate_docs def state_updates(self): """Deprecated, do NOT use! Returns the `updates` from all layers that are stateful. This is useful for separating training updates and state updates, e.g. when we need to update a layer's internal state during prediction. Returns: A list of update ops. """ warnings.warn('`Model.state_updates` will be removed in a future version. ' 'This property should not be used in TensorFlow 2.0, ' 'as `updates` are applied automatically.') state_updates = [] for layer in self.layers: if getattr(layer, 'stateful', False): if hasattr(layer, 'updates'): state_updates += layer.updates return state_updates
var weights
-
Returns the list of all layer variables/weights.
Note: This will not track the weights of nested
tf.Modules
that are not themselves Keras layers.Returns
A list of variables.
Expand source code
@property def weights(self): """Returns the list of all layer variables/weights. Note: This will not track the weights of nested `tf.Modules` that are not themselves Keras layers. Returns: A list of variables. """ return self._dedup_weights(self._undeduplicated_weights)
Methods
def build(self, input_shape)
-
Builds the model based on input shapes received.
This is to be used for subclassed models, which do not know at instantiation time what their inputs look like.
This method only exists for users who want to call
model.build()
in a standalone way (as a substitute for calling the model on real data to build it). It will never be called by the framework (and thus it will never throw unexpected errors in an unrelated workflow).Args: input_shape: Single tuple, TensorShape, or list/dict of shapes, where shapes are tuples, integers, or TensorShapes.
Raises
ValueError: 1. In case of invalid user-provided data (not of type tuple, list, TensorShape, or dict). 2. If the model requires call arguments that are agnostic to the input shapes (positional or kwarg in call signature). 3. If not all layers were properly built. 4. If float type inputs are not supported within the layers.
In each of these cases, the user should build their model by calling it on real tensor data.
Expand source code
@generic_utils.default def build(self, input_shape): """Builds the model based on input shapes received. This is to be used for subclassed models, which do not know at instantiation time what their inputs look like. This method only exists for users who want to call `model.build()` in a standalone way (as a substitute for calling the model on real data to build it). It will never be called by the framework (and thus it will never throw unexpected errors in an unrelated workflow). Args: input_shape: Single tuple, TensorShape, or list/dict of shapes, where shapes are tuples, integers, or TensorShapes. Raises: ValueError: 1. In case of invalid user-provided data (not of type tuple, list, TensorShape, or dict). 2. If the model requires call arguments that are agnostic to the input shapes (positional or kwarg in call signature). 3. If not all layers were properly built. 4. If float type inputs are not supported within the layers. In each of these cases, the user should build their model by calling it on real tensor data. """ if self._is_graph_network: super(Model, self).build(input_shape) return if input_shape is None: raise ValueError('Input shape must be defined when calling build on a ' 'model subclass network.') valid_types = (tuple, list, tf.TensorShape, dict) if not isinstance(input_shape, valid_types): raise ValueError('Specified input shape is not one of the valid types. ' 'Please specify a batch input shape of type tuple or ' 'list of input shapes. User provided ' 'input type: {}'.format(type(input_shape))) if input_shape and not self.inputs: # We create placeholders for the `None`s in the shape and build the model # in a Graph. Since tf.Variable is compatible with both eager execution # and graph building, the variables created after building the model in # a Graph are still valid when executing eagerly. if tf.executing_eagerly(): graph = tf.__internal__.FuncGraph('build_graph') else: graph = backend.get_graph() with graph.as_default(): if (isinstance(input_shape, list) and all(d is None or isinstance(d, int) for d in input_shape)): input_shape = tuple(input_shape) if isinstance(input_shape, list): x = [base_layer_utils.generate_placeholders_from_shape(shape) for shape in input_shape] elif isinstance(input_shape, dict): x = { k: base_layer_utils.generate_placeholders_from_shape(shape) for k, shape in input_shape.items() } else: x = base_layer_utils.generate_placeholders_from_shape(input_shape) kwargs = {} call_signature = self._call_full_argspec call_args = call_signature.args # Exclude `self`, `inputs`, and any argument with a default value. if len(call_args) > 2: if call_signature.defaults: call_args = call_args[2:-len(call_signature.defaults)] else: call_args = call_args[2:] for arg in call_args: if arg == 'training': # Case where `training` is a positional arg with no default. kwargs['training'] = False else: # Has invalid call signature with unknown positional arguments. raise ValueError( 'Currently, you cannot build your model if it has ' 'positional or keyword arguments that are not ' 'inputs to the model, but are required for its ' '`call` method. Instead, in order to instantiate ' 'and build your model, `call` your model on real ' 'tensor data with all expected call arguments.') elif len(call_args) < 2: # Signature without `inputs`. raise ValueError('You can only call `build` on a model if its `call` ' 'method accepts an `inputs` argument.') try: self.call(x, **kwargs) except (tf.errors.InvalidArgumentError, TypeError): raise ValueError('You cannot build your model by calling `build` ' 'if your layers do not support float type inputs. ' 'Instead, in order to instantiate and build your ' 'model, `call` your model on real tensor data (of ' 'the correct dtype).') super(Model, self).build(input_shape)
def call(self, inputs, training=None, mask=None)
-
Calls the model on new inputs.
In this case
call
just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs).Note: This method should not be called directly. It is only meant to be overridden when subclassing
tf.keras.Model
. To call a model on an input, always use the__call__
method, i.e.model(inputs)
, which relies on the underlyingcall
method.Args
inputs
- Input tensor, or dict/list/tuple of input tensors.
training
- Boolean or boolean scalar tensor, indicating whether to run
the
Network
in training mode or inference mode. mask
- A mask or list of masks. A mask can be either a tensor or None (no mask).
Returns
A tensor if there is a single output, or a list of tensors if there are more than one outputs.
Expand source code
@doc_controls.doc_in_current_and_subclasses def call(self, inputs, training=None, mask=None): """Calls the model on new inputs. In this case `call` just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs). Note: This method should not be called directly. It is only meant to be overridden when subclassing `tf.keras.Model`. To call a model on an input, always use the `__call__` method, i.e. `model(inputs)`, which relies on the underlying `call` method. Args: inputs: Input tensor, or dict/list/tuple of input tensors. training: Boolean or boolean scalar tensor, indicating whether to run the `Network` in training mode or inference mode. mask: A mask or list of masks. A mask can be either a tensor or None (no mask). Returns: A tensor if there is a single output, or a list of tensors if there are more than one outputs. """ raise NotImplementedError('When subclassing the `Model` class, you should ' 'implement a `call` method.')
def compile(self, optimizer='rmsprop', loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, steps_per_execution=None, **kwargs)
-
Configures the model for training.
Example:
model.compile(optimizer=tf.keras.optimizer.Adam(learning_rate=1e-3), loss=tf.keras.losses.BinaryCrossentropy(), metrics=[tf.keras.metrics.BinaryAccuracy(), tf.keras.metrics.FalseNegatives()])
Args
optimizer
- String (name of optimizer) or optimizer instance. See
tf.keras.optimizers
. loss
- Loss function. Maybe be a string (name of loss function), or
a
tf.keras.losses.Loss
instance. Seetf.keras.losses
. A loss function is any callable with the signatureloss = fn(y_true, y_pred)<code>, where </code>y_true
are the ground truth values, andy_pred
are the model's predictions.y_true
should have shape(batch_size, d0, .. dN)
(except in the case of sparse loss functions such as sparse categorical crossentropy which expects integer arrays of shape(batch_size, d0, .. dN-1)
).y_pred
should have shape(batch_size, d0, .. dN)
. The loss function should return a float tensor. If a customLoss
instance is used and reduction is set toNone
, return value has shape(batch_size, d0, .. dN-1)
i.e. per-sample or per-timestep loss values; otherwise, it is a scalar. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses, unlessloss_weights
is specified. metrics
- List of metrics to be evaluated by the model during training
and testing. Each of this can be a string (name of a built-in
function), function or a
tf.keras.metrics.Metric
instance. Seetf.keras.metrics
. Typically you will usemetrics=['accuracy']
. A function is any callable with the signatureresult = fn(y_true, y_pred)
. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such asmetrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}
. You can also pass a list to specify a metric or a list of metrics for each output, such asmetrics=[['accuracy'], ['accuracy', 'mse']]
ormetrics=['accuracy', ['accuracy', 'mse']]
. When you pass the strings 'accuracy' or 'acc', we convert this to one oftf.keras.metrics.BinaryAccuracy
,tf.keras.metrics.CategoricalAccuracy
,tf.keras.metrics.SparseCategoricalAccuracy
based on the loss function used and the model output shape. We do a similar conversion for the strings 'crossentropy' and 'ce' as well. loss_weights
- Optional list or dictionary specifying scalar coefficients
(Python floats) to weight the loss contributions of different model
outputs. The loss value that will be minimized by the model will then
be the weighted sum of all individual losses, weighted by the
loss_weights
coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients. weighted_metrics
- List of metrics to be evaluated and weighted by
sample_weight
orclass_weight
during training and testing. run_eagerly
- Bool. Defaults to
False
. IfTrue
, thisModel
's logic will not be wrapped in atf.function
. Recommended to leave this asNone
unless yourModel
cannot be run inside atf.function
.run_eagerly=True
is not supported when usingtf.distribute.experimental.ParameterServerStrategy
. steps_per_execution
- Int. Defaults to 1. The number of batches to
run during each
tf.function
call. Running multiple batches inside a singletf.function
call can greatly improve performance on TPUs or small models with a large Python overhead. At most, one full epoch will be run each execution. If a number larger than the size of the epoch is passed, the execution will be truncated to the size of the epoch. Note that ifsteps_per_execution
is set toN
,Callback.on_batch_begin
andCallback.on_batch_end
methods will only be called everyN
batches (i.e. before/after eachtf.function
execution). **kwargs
- Arguments supported for backwards compatibility only.
Raises
ValueError
- In case of invalid arguments for
optimizer
,loss
ormetrics
.
Expand source code
def compile(self, optimizer='rmsprop', loss=None, metrics=None, loss_weights=None, weighted_metrics=None, run_eagerly=None, steps_per_execution=None, **kwargs): """Configures the model for training. Example: ```python model.compile(optimizer=tf.keras.optimizer.Adam(learning_rate=1e-3), loss=tf.keras.losses.BinaryCrossentropy(), metrics=[tf.keras.metrics.BinaryAccuracy(), tf.keras.metrics.FalseNegatives()]) ``` Args: optimizer: String (name of optimizer) or optimizer instance. See `tf.keras.optimizers`. loss: Loss function. Maybe be a string (name of loss function), or a `tf.keras.losses.Loss` instance. See `tf.keras.losses`. A loss function is any callable with the signature `loss = fn(y_true, y_pred)`, where `y_true` are the ground truth values, and `y_pred` are the model's predictions. `y_true` should have shape `(batch_size, d0, .. dN)` (except in the case of sparse loss functions such as sparse categorical crossentropy which expects integer arrays of shape `(batch_size, d0, .. dN-1)`). `y_pred` should have shape `(batch_size, d0, .. dN)`. The loss function should return a float tensor. If a custom `Loss` instance is used and reduction is set to `None`, return value has shape `(batch_size, d0, .. dN-1)` i.e. per-sample or per-timestep loss values; otherwise, it is a scalar. If the model has multiple outputs, you can use a different loss on each output by passing a dictionary or a list of losses. The loss value that will be minimized by the model will then be the sum of all individual losses, unless `loss_weights` is specified. metrics: List of metrics to be evaluated by the model during training and testing. Each of this can be a string (name of a built-in function), function or a `tf.keras.metrics.Metric` instance. See `tf.keras.metrics`. Typically you will use `metrics=['accuracy']`. A function is any callable with the signature `result = fn(y_true, y_pred)`. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as `metrics={'output_a': 'accuracy', 'output_b': ['accuracy', 'mse']}`. You can also pass a list to specify a metric or a list of metrics for each output, such as `metrics=[['accuracy'], ['accuracy', 'mse']]` or `metrics=['accuracy', ['accuracy', 'mse']]`. When you pass the strings 'accuracy' or 'acc', we convert this to one of `tf.keras.metrics.BinaryAccuracy`, `tf.keras.metrics.CategoricalAccuracy`, `tf.keras.metrics.SparseCategoricalAccuracy` based on the loss function used and the model output shape. We do a similar conversion for the strings 'crossentropy' and 'ce' as well. loss_weights: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the *weighted sum* of all individual losses, weighted by the `loss_weights` coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients. weighted_metrics: List of metrics to be evaluated and weighted by `sample_weight` or `class_weight` during training and testing. run_eagerly: Bool. Defaults to `False`. If `True`, this `Model`'s logic will not be wrapped in a `tf.function`. Recommended to leave this as `None` unless your `Model` cannot be run inside a `tf.function`. `run_eagerly=True` is not supported when using `tf.distribute.experimental.ParameterServerStrategy`. steps_per_execution: Int. Defaults to 1. The number of batches to run during each `tf.function` call. Running multiple batches inside a single `tf.function` call can greatly improve performance on TPUs or small models with a large Python overhead. At most, one full epoch will be run each execution. If a number larger than the size of the epoch is passed, the execution will be truncated to the size of the epoch. Note that if `steps_per_execution` is set to `N`, `Callback.on_batch_begin` and `Callback.on_batch_end` methods will only be called every `N` batches (i.e. before/after each `tf.function` execution). **kwargs: Arguments supported for backwards compatibility only. Raises: ValueError: In case of invalid arguments for `optimizer`, `loss` or `metrics`. """ base_layer.keras_api_gauge.get_cell('compile').set(True) with self.distribute_strategy.scope(): if 'experimental_steps_per_execution' in kwargs: logging.warning('The argument `steps_per_execution` is no longer ' 'experimental. Pass `steps_per_execution` instead of ' '`experimental_steps_per_execution`.') if not steps_per_execution: steps_per_execution = kwargs.pop('experimental_steps_per_execution') # When compiling from an already-serialized model, we do not want to # reapply some processing steps (e.g. metric renaming for multi-output # models, which have prefixes added for each corresponding output name). from_serialized = kwargs.pop('from_serialized', False) self._validate_compile(optimizer, metrics, **kwargs) self._run_eagerly = run_eagerly self.optimizer = self._get_optimizer(optimizer) self.compiled_loss = compile_utils.LossesContainer( loss, loss_weights, output_names=self.output_names) self.compiled_metrics = compile_utils.MetricsContainer( metrics, weighted_metrics, output_names=self.output_names, from_serialized=from_serialized) self._configure_steps_per_execution(steps_per_execution or 1) # Initializes attrs that are reset each time `compile` is called. self._reset_compile_cache() self._is_compiled = True self.loss = loss or {} # Backwards compat.
def evaluate(self, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, return_dict=False, **kwargs)
-
Returns the loss value & metrics values for the model in test mode.
Computation is done in batches (see the
batch_size
arg.)Args
x
- Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A
tf.data
dataset. Should return a tuple of either(inputs, targets)
or(inputs, targets, sample_weights)
. - A generator orkeras.utils.Sequence
returning(inputs, targets)
or(inputs, targets, sample_weights)
. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in theUnpacking behavior for iterator-like inputs<code> section of </code>Model.fit
. y
- Target data. Like the input data
x
, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent withx
(you cannot have Numpy inputs and tensor targets, or inversely). Ifx
is a dataset, generator orkeras.utils.Sequence
instance,y
should not be specified (since targets will be obtained from the iterator/dataset). batch_size
- Integer or
None
. Number of samples per batch of computation. If unspecified,batch_size
will default to 32. Do not specify thebatch_size
if your data is in the form of a dataset, generators, orkeras.utils.Sequence
instances (since they generate batches). verbose
- 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar.
sample_weight
- Optional Numpy array of weights for the test samples,
used for weighting the loss function. You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples), or in the case of
temporal data, you can pass a 2D array with shape
(samples, sequence_length)
, to apply a different weight to every timestep of every sample. This argument is not supported whenx
is a dataset, instead pass sample weights as the third element ofx
. steps
- Integer or
None
. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value ofNone
. If x is atf.data
dataset andsteps
is None, 'evaluate' will run until the dataset is exhausted. This argument is not supported with array inputs. callbacks
- List of
Callback
instances. List of callbacks to apply during evaluation. See callbacks. max_queue_size
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue. If unspecified,max_queue_size
will default to 10. workers
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum number of processes to spin up when using process-based threading. If unspecified,workers
will default to 1. use_multiprocessing
- Boolean. Used for generator or
keras.utils.Sequence
input only. IfTrue
, use process-based threading. If unspecified,use_multiprocessing
will default toFalse
. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. return_dict
- If
True
, loss and metric results are returned as a dict, with each key being the name of the metric. IfFalse
, they are returned as a list. **kwargs
- Unused at this time.
See the discussion of
Unpacking behavior for iterator-like inputs
forModel.fit()
.Model.evaluate()
is not yet supported withtf.distribute.experimental.ParameterServerStrategy
.Returns
Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute
model.metrics_names
will give you the display labels for the scalar outputs.Raises
RuntimeError
- If
model.evaluate
is wrapped intf.function
. ValueError
- in case of invalid arguments.
Expand source code
def evaluate(self, x=None, y=None, batch_size=None, verbose=1, sample_weight=None, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, return_dict=False, **kwargs): """Returns the loss value & metrics values for the model in test mode. Computation is done in batches (see the `batch_size` arg.) Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. - A `tf.data` dataset. Should return a tuple of either `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the `Unpacking behavior for iterator-like inputs` section of `Model.fit`. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). If `x` is a dataset, generator or `keras.utils.Sequence` instance, `y` should not be specified (since targets will be obtained from the iterator/dataset). batch_size: Integer or `None`. Number of samples per batch of computation. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of a dataset, generators, or `keras.utils.Sequence` instances (since they generate batches). verbose: 0 or 1. Verbosity mode. 0 = silent, 1 = progress bar. sample_weight: Optional Numpy array of weights for the test samples, used for weighting the loss function. You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape `(samples, sequence_length)`, to apply a different weight to every timestep of every sample. This argument is not supported when `x` is a dataset, instead pass sample weights as the third element of `x`. steps: Integer or `None`. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of `None`. If x is a `tf.data` dataset and `steps` is None, 'evaluate' will run until the dataset is exhausted. This argument is not supported with array inputs. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during evaluation. See [callbacks](/api_docs/python/tf/keras/callbacks). max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. **kwargs: Unused at this time. See the discussion of `Unpacking behavior for iterator-like inputs` for `Model.fit`. `Model.evaluate` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. Returns: Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.evaluate` is wrapped in `tf.function`. ValueError: in case of invalid arguments. """ base_layer.keras_api_gauge.get_cell('evaluate').set(True) version_utils.disallow_legacy_graph('Model', 'evaluate') self._assert_compile_was_called() self._check_call_args('evaluate') _disallow_inside_tf_function('evaluate') use_cached_eval_dataset = kwargs.pop('_use_cached_eval_dataset', False) if kwargs: raise TypeError('Invalid keyword arguments: %s' % (kwargs,)) if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access self._cluster_coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( self.distribute_strategy) with self.distribute_strategy.scope(): # Use cached evaluation data only when it's called in `Model.fit` if (use_cached_eval_dataset and getattr(self, '_eval_data_handler', None) is not None): data_handler = self._eval_data_handler else: # Creates a `tf.data.Dataset` and handles batch and epoch iteration. data_handler = data_adapter.get_data_handler( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=1, steps=data_handler.inferred_steps) logs = {} self.test_function = self.make_test_function() self._test_counter.assign(0) callbacks.on_test_begin() for _, iterator in data_handler.enumerate_epochs(): # Single epoch. self.reset_metrics() with data_handler.catch_stop_iteration(): for step in data_handler.steps(): with tf.profiler.experimental.Trace('test', step_num=step, _r=1): callbacks.on_test_batch_begin(step) tmp_logs = self.test_function(iterator) if data_handler.should_sync: context.async_wait() logs = tmp_logs # No error, now safe to assign to logs. end_step = step + data_handler.step_increment callbacks.on_test_batch_end(end_step, logs) logs = tf_utils.sync_to_numpy_or_python_type(logs) callbacks.on_test_end(logs=logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names)
def evaluate_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0)
-
Evaluates the model on a data generator.
Deprecated
Model.evaluate()
now supports generators, so there is no longer any need to use this endpoint.Expand source code
@doc_controls.do_not_generate_docs def evaluate_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0): """Evaluates the model on a data generator. DEPRECATED: `Model.evaluate` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.evaluate_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.evaluate`, which supports generators.') self._check_call_args('evaluate_generator') return self.evaluate( generator, steps=steps, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, verbose=verbose, callbacks=callbacks)
def fit(self, x=None, y=None, batch_size=None, epochs=1, verbose='auto', callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False)
-
Trains the model for a fixed number of epochs (iterations on a dataset).
Args
x
- Input data. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A dict mapping input names to the corresponding array/tensors,
if the model has named inputs.
- A
tf.data
dataset. Should return a tuple of either(inputs, targets)
or(inputs, targets, sample_weights)
. - A generator orkeras.utils.Sequence
returning(inputs, targets)
or(inputs, targets, sample_weights)
. - Atf.keras.utils.experimental.DatasetCreator
, which wraps a callable that takes a single argument of typetf.distribute.InputContext
, and returns atf.data.Dataset
.DatasetCreator
should be used when users prefer to specify the per-replica batching and sharding logic for theDataset
. Seetf.keras.utils.experimental.DatasetCreator
doc for more information. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given below. If usingtf.distribute.experimental.ParameterServerStrategy
, onlyDatasetCreator
type is supported forx
. y
- Target data. Like the input data
x
, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent withx
(you cannot have Numpy inputs and tensor targets, or inversely). Ifx
is a dataset, generator, orkeras.utils.Sequence
instance,y
should not be specified (since targets will be obtained fromx
). batch_size
- Integer or
None
. Number of samples per gradient update. If unspecified,batch_size
will default to 32. Do not specify thebatch_size
if your data is in the form of datasets, generators, orkeras.utils.Sequence
instances (since they generate batches). epochs
- Integer. Number of epochs to train the model.
An epoch is an iteration over the entire
x
andy
data provided. Note that in conjunction withinitial_epoch
,epochs
is to be understood as "final epoch". The model is not trained for a number of iterations given byepochs
, but merely until the epoch of indexepochs
is reached. verbose
- 'auto', 0, 1, or 2. Verbosity mode.
0 = silent, 1 = progress bar, 2 = one line per epoch.
'auto' defaults to 1 for most cases, but 2 when used with
ParameterServerStrategy
. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks
- List of
Callback
instances. List of callbacks to apply during training. Seetf.keras.callbacks
. Notetf.keras.callbacks.ProgbarLogger
andtf.keras.callbacks.History
callbacks are created automatically and need not be passed intomodel.fit
.tf.keras.callbacks.ProgbarLogger
is created or not based onverbose
argument tomodel.fit
. Callbacks with batch-level calls are currently unsupported withtf.distribute.experimental.ParameterServerStrategy
, and users are advised to implement epoch-level calls instead with an appropriatesteps_per_epoch
value. validation_split
- Float between 0 and 1.
Fraction of the training data to be used as validation data.
The model will set apart this fraction of the training data,
will not train on it, and will evaluate
the loss and any model metrics
on this data at the end of each epoch.
The validation data is selected from the last samples
in the
x
andy
data provided, before shuffling. This argument is not supported whenx
is a dataset, generator orkeras.utils.Sequence
instance.validation_split
is not yet supported withtf.distribute.experimental.ParameterServerStrategy
. validation_data
- Data on which to evaluate
the loss and any model metrics at the end of each epoch.
The model will not be trained on this data. Thus, note the fact
that the validation loss of data provided using
validation_split
orvalidation_data
is not affected by regularization layers like noise and dropout.validation_data
will overridevalidation_split
.validation_data
could be: - A tuple(x_val, y_val)
of Numpy arrays or tensors. - A tuple(x_val, y_val, val_sample_weights)
of NumPy arrays. - Atf.data.Dataset
. - A Python generator orkeras.utils.Sequence
returning(inputs, targets)
or(inputs, targets, sample_weights)
.validation_data
is not yet supported withtf.distribute.experimental.ParameterServerStrategy
. shuffle
- Boolean (whether to shuffle the training data
before each epoch) or str (for 'batch'). This argument is ignored
when
x
is a generator or an object of tf.data.Dataset. 'batch' is a special option for dealing with the limitations of HDF5 data; it shuffles in batch-sized chunks. Has no effect whensteps_per_epoch
is notNone
. class_weight
- Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class.
sample_weight
- Optional Numpy array of weights for
the training samples, used for weighting the loss function
(during training only). You can either pass a flat (1D)
Numpy array with the same length as the input samples
(1:1 mapping between weights and samples),
or in the case of temporal data,
you can pass a 2D array with shape
(samples, sequence_length)
, to apply a different weight to every timestep of every sample. This argument is not supported whenx
is a dataset, generator, orkeras.utils.Sequence
instance, instead provide the sample_weights as the third element ofx
. initial_epoch
- Integer. Epoch at which to start training (useful for resuming a previous training run).
steps_per_epoch
- Integer or
None
. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the defaultNone
is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is atf.data
dataset, and 'steps_per_epoch' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify thesteps_per_epoch
argument. Ifsteps_per_epoch=-1
the training will run indefinitely with an infinitely repeating dataset. This argument is not supported with array inputs. When usingtf.distribute.experimental.ParameterServerStrategy
: *steps_per_epoch=None
is not supported. validation_steps
- Only relevant if
validation_data
is provided and is atf.data
dataset. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If 'validation_steps' is None, validation will run until thevalidation_data
dataset is exhausted. In the case of an infinitely repeated dataset, it will run into an infinite loop. If 'validation_steps' is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time. validation_batch_size
- Integer or
None
. Number of samples per validation batch. If unspecified, will default tobatch_size
. Do not specify thevalidation_batch_size
if your data is in the form of datasets, generators, orkeras.utils.Sequence
instances (since they generate batches). validation_freq
- Only relevant if validation data is provided. Integer
or
collections.abc.Container
instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g.validation_freq=2
runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g.validation_freq=[1, 2, 10]
runs validation at the end of the 1st, 2nd, and 10th epochs. max_queue_size
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue. If unspecified,max_queue_size
will default to 10. workers
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum number of processes to spin up when using process-based threading. If unspecified,workers
will default to 1. use_multiprocessing
- Boolean. Used for generator or
keras.utils.Sequence
input only. IfTrue
, use process-based threading. If unspecified,use_multiprocessing
will default toFalse
. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.
Unpacking behavior for iterator-like inputs: A common pattern is to pass a tf.data.Dataset, generator, or tf.keras.utils.Sequence to the
x
argument of fit, which will in fact yield not only features (x) but optionally targets (y) and sample weights. Keras requires that the output of such iterator-likes be unambiguous. The iterator should return a tuple of length 1, 2, or 3, where the optional second and third elements will be used for y and sample_weight respectively. Any other type provided will be wrapped in a length one tuple, effectively treating everything as 'x'. When yielding dicts, they should still adhere to the top-level tuple structure. e.g.({"x0": x0, "x1": x1}, y)
. Keras will not attempt to separate features, targets, and weights from the keys of a single dict. A notable unsupported data type is the namedtuple. The reason is that it behaves like both an ordered datatype (tuple) and a mapping datatype (dict). So given a namedtuple of the form:namedtuple("example_tuple", ["y", "x"])
it is ambiguous whether to reverse the order of the elements when interpreting the value. Even worse is a tuple of the form:namedtuple("other_tuple", ["x", "y", "z"])
where it is unclear if the tuple was intended to be unpacked into x, y, and sample_weight or passed through as a single element tox
. As a result the data processing code will simply raise a ValueError if it encounters a namedtuple. (Along with instructions to remedy the issue.)Returns
A
History
object. ItsHistory.history
attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable).Raises
RuntimeError
-
- If the model was never compiled or,
- If
model.fit
is wrapped intf.function
.
ValueError
- In case of mismatch between the provided input data and what the model expects or when the input data is empty.
Expand source code
def fit(self, x=None, y=None, batch_size=None, epochs=1, verbose='auto', callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None, validation_batch_size=None, validation_freq=1, max_queue_size=10, workers=1, use_multiprocessing=False): """Trains the model for a fixed number of epochs (iterations on a dataset). Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. - A `tf.data` dataset. Should return a tuple of either `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. - A `tf.keras.utils.experimental.DatasetCreator`, which wraps a callable that takes a single argument of type `tf.distribute.InputContext`, and returns a `tf.data.Dataset`. `DatasetCreator` should be used when users prefer to specify the per-replica batching and sharding logic for the `Dataset`. See `tf.keras.utils.experimental.DatasetCreator` doc for more information. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given below. If using `tf.distribute.experimental.ParameterServerStrategy`, only `DatasetCreator` type is supported for `x`. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). If `x` is a dataset, generator, or `keras.utils.Sequence` instance, `y` should not be specified (since targets will be obtained from `x`). batch_size: Integer or `None`. Number of samples per gradient update. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of datasets, generators, or `keras.utils.Sequence` instances (since they generate batches). epochs: Integer. Number of epochs to train the model. An epoch is an iteration over the entire `x` and `y` data provided. Note that in conjunction with `initial_epoch`, `epochs` is to be understood as "final epoch". The model is not trained for a number of iterations given by `epochs`, but merely until the epoch of index `epochs` is reached. verbose: 'auto', 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. 'auto' defaults to 1 for most cases, but 2 when used with `ParameterServerStrategy`. Note that the progress bar is not particularly useful when logged to a file, so verbose=2 is recommended when not running interactively (eg, in a production environment). callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during training. See `tf.keras.callbacks`. Note `tf.keras.callbacks.ProgbarLogger` and `tf.keras.callbacks.History` callbacks are created automatically and need not be passed into `model.fit`. `tf.keras.callbacks.ProgbarLogger` is created or not based on `verbose` argument to `model.fit`. Callbacks with batch-level calls are currently unsupported with `tf.distribute.experimental.ParameterServerStrategy`, and users are advised to implement epoch-level calls instead with an appropriate `steps_per_epoch` value. validation_split: Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the `x` and `y` data provided, before shuffling. This argument is not supported when `x` is a dataset, generator or `keras.utils.Sequence` instance. `validation_split` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. validation_data: Data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. Thus, note the fact that the validation loss of data provided using `validation_split` or `validation_data` is not affected by regularization layers like noise and dropout. `validation_data` will override `validation_split`. `validation_data` could be: - A tuple `(x_val, y_val)` of Numpy arrays or tensors. - A tuple `(x_val, y_val, val_sample_weights)` of NumPy arrays. - A `tf.data.Dataset`. - A Python generator or `keras.utils.Sequence` returning `(inputs, targets)` or `(inputs, targets, sample_weights)`. `validation_data` is not yet supported with `tf.distribute.experimental.ParameterServerStrategy`. shuffle: Boolean (whether to shuffle the training data before each epoch) or str (for 'batch'). This argument is ignored when `x` is a generator or an object of tf.data.Dataset. 'batch' is a special option for dealing with the limitations of HDF5 data; it shuffles in batch-sized chunks. Has no effect when `steps_per_epoch` is not `None`. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. sample_weight: Optional Numpy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) Numpy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape `(samples, sequence_length)`, to apply a different weight to every timestep of every sample. This argument is not supported when `x` is a dataset, generator, or `keras.utils.Sequence` instance, instead provide the sample_weights as the third element of `x`. initial_epoch: Integer. Epoch at which to start training (useful for resuming a previous training run). steps_per_epoch: Integer or `None`. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default `None` is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If x is a `tf.data` dataset, and 'steps_per_epoch' is None, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the `steps_per_epoch` argument. If `steps_per_epoch=-1` the training will run indefinitely with an infinitely repeating dataset. This argument is not supported with array inputs. When using `tf.distribute.experimental.ParameterServerStrategy`: * `steps_per_epoch=None` is not supported. validation_steps: Only relevant if `validation_data` is provided and is a `tf.data` dataset. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If 'validation_steps' is None, validation will run until the `validation_data` dataset is exhausted. In the case of an infinitely repeated dataset, it will run into an infinite loop. If 'validation_steps' is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time. validation_batch_size: Integer or `None`. Number of samples per validation batch. If unspecified, will default to `batch_size`. Do not specify the `validation_batch_size` if your data is in the form of datasets, generators, or `keras.utils.Sequence` instances (since they generate batches). validation_freq: Only relevant if validation data is provided. Integer or `collections.abc.Container` instance (e.g. list, tuple, etc.). If an integer, specifies how many training epochs to run before a new validation run is performed, e.g. `validation_freq=2` runs validation every 2 epochs. If a Container, specifies the epochs on which to run validation, e.g. `validation_freq=[1, 2, 10]` runs validation at the end of the 1st, 2nd, and 10th epochs. max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. Unpacking behavior for iterator-like inputs: A common pattern is to pass a tf.data.Dataset, generator, or tf.keras.utils.Sequence to the `x` argument of fit, which will in fact yield not only features (x) but optionally targets (y) and sample weights. Keras requires that the output of such iterator-likes be unambiguous. The iterator should return a tuple of length 1, 2, or 3, where the optional second and third elements will be used for y and sample_weight respectively. Any other type provided will be wrapped in a length one tuple, effectively treating everything as 'x'. When yielding dicts, they should still adhere to the top-level tuple structure. e.g. `({"x0": x0, "x1": x1}, y)`. Keras will not attempt to separate features, targets, and weights from the keys of a single dict. A notable unsupported data type is the namedtuple. The reason is that it behaves like both an ordered datatype (tuple) and a mapping datatype (dict). So given a namedtuple of the form: `namedtuple("example_tuple", ["y", "x"])` it is ambiguous whether to reverse the order of the elements when interpreting the value. Even worse is a tuple of the form: `namedtuple("other_tuple", ["x", "y", "z"])` where it is unclear if the tuple was intended to be unpacked into x, y, and sample_weight or passed through as a single element to `x`. As a result the data processing code will simply raise a ValueError if it encounters a namedtuple. (Along with instructions to remedy the issue.) Returns: A `History` object. Its `History.history` attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable). Raises: RuntimeError: 1. If the model was never compiled or, 2. If `model.fit` is wrapped in `tf.function`. ValueError: In case of mismatch between the provided input data and what the model expects or when the input data is empty. """ base_layer.keras_api_gauge.get_cell('fit').set(True) # Legacy graph support is contained in `training_v1.Model`. version_utils.disallow_legacy_graph('Model', 'fit') self._assert_compile_was_called() self._check_call_args('fit') _disallow_inside_tf_function('fit') if verbose == 'auto': if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access verbose = 2 # Default to epoch-level logging for PSStrategy. else: verbose = 1 # Default to batch-level logging otherwise. if validation_split: # Create the validation data using the training data. Only supported for # `Tensor` and `NumPy` input. (x, y, sample_weight), validation_data = ( data_adapter.train_validation_split( (x, y, sample_weight), validation_split=validation_split)) if validation_data: val_x, val_y, val_sample_weight = ( data_adapter.unpack_x_y_sample_weight(validation_data)) if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access self._cluster_coordinator = tf.distribute.experimental.coordinator.ClusterCoordinator( self.distribute_strategy) with self.distribute_strategy.scope(), \ training_utils.RespectCompiledTrainableState(self): # Creates a `tf.data.Dataset` and handles batch and epoch iteration. data_handler = data_adapter.get_data_handler( x=x, y=y, sample_weight=sample_weight, batch_size=batch_size, steps_per_epoch=steps_per_epoch, initial_epoch=initial_epoch, epochs=epochs, shuffle=shuffle, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=epochs, steps=data_handler.inferred_steps) self.stop_training = False self.train_function = self.make_train_function() self._train_counter.assign(0) callbacks.on_train_begin() training_logs = None # Handle fault-tolerance for multi-worker. # TODO(omalleyt): Fix the ordering issues that mean this has to # happen after `callbacks.on_train_begin`. data_handler._initial_epoch = ( # pylint: disable=protected-access self._maybe_load_initial_epoch_from_ckpt(initial_epoch)) logs = None for epoch, iterator in data_handler.enumerate_epochs(): self.reset_metrics() callbacks.on_epoch_begin(epoch) with data_handler.catch_stop_iteration(): for step in data_handler.steps(): with tf.profiler.experimental.Trace( 'train', epoch_num=epoch, step_num=step, batch_size=batch_size, _r=1): callbacks.on_train_batch_begin(step) tmp_logs = self.train_function(iterator) if data_handler.should_sync: context.async_wait() logs = tmp_logs # No error, now safe to assign to logs. end_step = step + data_handler.step_increment callbacks.on_train_batch_end(end_step, logs) if self.stop_training: break logs = tf_utils.sync_to_numpy_or_python_type(logs) if logs is None: raise ValueError('Expect x to be a non-empty array or dataset.') epoch_logs = copy.copy(logs) # Run validation. if validation_data and self._should_eval(epoch, validation_freq): # Create data_handler for evaluation and cache it. if getattr(self, '_eval_data_handler', None) is None: self._eval_data_handler = data_adapter.get_data_handler( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps_per_epoch=validation_steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) val_logs = self.evaluate( x=val_x, y=val_y, sample_weight=val_sample_weight, batch_size=validation_batch_size or batch_size, steps=validation_steps, callbacks=callbacks, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, return_dict=True, _use_cached_eval_dataset=True) val_logs = {'val_' + name: val for name, val in val_logs.items()} epoch_logs.update(val_logs) callbacks.on_epoch_end(epoch, epoch_logs) training_logs = epoch_logs if self.stop_training: break # If eval data_hanlder exists, delete it after all epochs are done. if getattr(self, '_eval_data_handler', None) is not None: del self._eval_data_handler callbacks.on_train_end(logs=training_logs) return self.history
def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0)
-
Fits the model on data yielded batch-by-batch by a Python generator.
Deprecated
Model.fit()
now supports generators, so there is no longer any need to use this endpoint.Expand source code
@doc_controls.do_not_generate_docs def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None, validation_data=None, validation_steps=None, validation_freq=1, class_weight=None, max_queue_size=10, workers=1, use_multiprocessing=False, shuffle=True, initial_epoch=0): """Fits the model on data yielded batch-by-batch by a Python generator. DEPRECATED: `Model.fit` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.fit_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.fit`, which supports generators.') return self.fit( generator, steps_per_epoch=steps_per_epoch, epochs=epochs, verbose=verbose, callbacks=callbacks, validation_data=validation_data, validation_steps=validation_steps, validation_freq=validation_freq, class_weight=class_weight, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, shuffle=shuffle, initial_epoch=initial_epoch)
def get_layer(self, name=None, index=None)
-
Retrieves a layer based on either its name (unique) or index.
If
name
andindex
are both provided,index
will take precedence. Indices are based on order of horizontal graph traversal (bottom-up).Args
name
- String, name of layer.
index
- Integer, index of layer.
Returns
A layer instance.
Raises
ValueError
- In case of invalid layer name or index.
Expand source code
def get_layer(self, name=None, index=None): """Retrieves a layer based on either its name (unique) or index. If `name` and `index` are both provided, `index` will take precedence. Indices are based on order of horizontal graph traversal (bottom-up). Args: name: String, name of layer. index: Integer, index of layer. Returns: A layer instance. Raises: ValueError: In case of invalid layer name or index. """ # TODO(fchollet): We could build a dictionary based on layer names # since they are constant, but we have not done that yet. if index is not None and name is not None: raise ValueError('Provide only a layer name or a layer index.') if index is not None: if len(self.layers) <= index: raise ValueError('Was asked to retrieve layer at index ' + str(index) + ' but model only has ' + str(len(self.layers)) + ' layers.') else: return self.layers[index] if name is not None: for layer in self.layers: if layer.name == name: return layer raise ValueError('No such layer: ' + name + '.') raise ValueError('Provide either a layer name or layer index.')
def get_weights(self)
-
Retrieves the weights of the model.
Returns
A flat list of Numpy arrays.
Expand source code
def get_weights(self): """Retrieves the weights of the model. Returns: A flat list of Numpy arrays. """ with self.distribute_strategy.scope(): return super(Model, self).get_weights()
def load_weights(self, filepath, by_name=False, skip_mismatch=False, options=None)
-
Loads all layer weights, either from a TensorFlow or an HDF5 weight file.
If
by_name
is False weights are loaded based on the network's topology. This means the architecture should be the same as when the weights were saved. Note that layers that don't have weights are not taken into account in the topological ordering, so adding or removing layers is fine as long as they don't have weights.If
by_name
is True, weights are loaded into layers only if they share the same name. This is useful for fine-tuning or transfer-learning models where some of the layers have changed.Only topological loading (
by_name=False
) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting fromtf.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 theModel
's constructor.Args
filepath
- String, path to the weights file to load. For weight files in
TensorFlow format, this is the file prefix (the same as was passed
to
save_weights
). This can also be a path to a SavedModel saved frommodel.save
. by_name
- Boolean, whether to load weights by name or by topological order. Only topological loading is supported for weight files in TensorFlow format.
skip_mismatch
- Boolean, whether to skip loading of layers where there is
a mismatch in the number of weights, or a mismatch in the shape of
the weight (only valid when
by_name=True
). options
- Optional
tf.train.CheckpointOptions
object that specifies options for loading weights.
Returns
When loading a weight file in TensorFlow format, returns the same status object as
tf.train.Checkpoint.restore
. When graph building, restore ops are run automatically as soon as the network is built (on first call for user-defined classes inheriting fromModel
, immediately if it is already built).When loading weights in HDF5 format, returns
None
.Raises
ImportError
- If h5py is not available and the weight file is in HDF5 format.
ValueError
- If
skip_mismatch
is set toTrue
whenby_name
isFalse
.
Expand source code
def load_weights(self, filepath, by_name=False, skip_mismatch=False, options=None): """Loads all layer weights, either from a TensorFlow or an HDF5 weight file. If `by_name` is False weights are loaded based on the network's topology. This means the architecture should be the same as when the weights were saved. Note that layers that don't have weights are not taken into account in the topological ordering, so adding or removing layers is fine as long as they don't have weights. If `by_name` is True, weights are loaded into layers only if they share the same name. This is useful for fine-tuning or transfer-learning models where some of the layers have changed. Only topological loading (`by_name=False`) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from `tf.keras.Model`: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which layers are assigned in the `Model`'s constructor. Args: filepath: String, path to the weights file to load. For weight files in TensorFlow format, this is the file prefix (the same as was passed to `save_weights`). This can also be a path to a SavedModel saved from `model.save`. by_name: Boolean, whether to load weights by name or by topological order. Only topological loading is supported for weight files in TensorFlow format. skip_mismatch: Boolean, whether to skip loading of layers where there is a mismatch in the number of weights, or a mismatch in the shape of the weight (only valid when `by_name=True`). options: Optional `tf.train.CheckpointOptions` object that specifies options for loading weights. Returns: When loading a weight file in TensorFlow format, returns the same status object as `tf.train.Checkpoint.restore`. When graph building, restore ops are run automatically as soon as the network is built (on first call for user-defined classes inheriting from `Model`, immediately if it is already built). When loading weights in HDF5 format, returns `None`. Raises: ImportError: If h5py is not available and the weight file is in HDF5 format. ValueError: If `skip_mismatch` is set to `True` when `by_name` is `False`. """ if backend.is_tpu_strategy(self._distribution_strategy): if (self._distribution_strategy.extended.steps_per_run > 1 and (not saving_utils.is_hdf5_filepath(filepath))): raise ValueError('Load weights is not yet supported with TPUStrategy ' 'with steps_per_run greater than 1.') if skip_mismatch and not by_name: raise ValueError( 'When calling model.load_weights, skip_mismatch can only be set to ' 'True when by_name is True.') filepath, save_format = _detect_save_format(filepath) if save_format == 'tf': status = self._trackable_saver.restore(filepath, options) if by_name: raise NotImplementedError( 'Weights may only be loaded based on topology into Models when ' 'loading TensorFlow-formatted weights (got by_name=True to ' 'load_weights).') if not tf.executing_eagerly(): session = backend.get_session() # Restore existing variables (if any) immediately, and set up a # streaming restore for any variables created in the future. tf.__internal__.tracking.streaming_restore(status=status, session=session) status.assert_nontrivial_match() else: status = None if h5py is None: raise ImportError( '`load_weights` requires h5py when loading weights from HDF5.') if not self._is_graph_network and not self.built: raise ValueError( 'Unable to load weights saved in HDF5 format into a subclassed ' 'Model which has not created its variables yet. Call the Model ' 'first, then load the weights.') self._assert_weights_created() with h5py.File(filepath, 'r') as f: if 'layer_names' not in f.attrs and 'model_weights' in f: f = f['model_weights'] if by_name: hdf5_format.load_weights_from_hdf5_group_by_name( f, self.layers, skip_mismatch=skip_mismatch) else: hdf5_format.load_weights_from_hdf5_group(f, self.layers) # Perform any layer defined finalization of the layer state. for layer in self.layers: layer.finalize_state() return status
def make_predict_function(self, force=False)
-
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()
andModel.predict_on_batch()
.Typically, this method directly controls
tf.function
andtf.distribute.Strategy
settings, and delegates the actual evaluation logic toModel.predict_step()
.This function is cached the first time
Model.predict()
orModel.predict_on_batch()
is called. The cache is cleared wheneverModel.compile()
is called. You can skip the cache and generate again the function withforce=True
.Args
force
- Whether to regenerate the predict function and skip the cached function if available.
Returns
Function. The function created by this method should accept a
tf.data.Iterator
, and return the outputs of theModel
.Expand source code
def make_predict_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the predict function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return the outputs of the `Model`. """ if self.predict_function is not None and not force: return self.predict_function def step_function(model, iterator): """Runs a single evaluation step.""" def run_step(data): outputs = model.predict_step(data) # Ensure counter is updated only if `test_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._predict_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='concat') return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def predict_function(iterator): """Runs an evaluation execution with one step.""" return step_function(self, iterator) else: def predict_function(iterator): """Runs an evaluation execution with multiple steps.""" outputs = step_function(self, iterator) for _ in tf.range(self._steps_per_execution - 1): tf.autograph.experimental.set_loop_options( shape_invariants=[( t, tf_utils.get_tensor_spec(t, dynamic_batch=True).shape) for t in tf.nest.flatten(outputs)]) step_outputs = step_function(self, iterator) outputs = tf.nest.map_structure(lambda t1, t2: concat([t1, t2]), outputs, step_outputs) return outputs if not self.run_eagerly: predict_function = tf.function( predict_function, experimental_relax_shapes=True) self.predict_function = predict_function return self.predict_function
def make_test_function(self, force=False)
-
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()
andModel.test_on_batch()
.Typically, this method directly controls
tf.function
andtf.distribute.Strategy
settings, and delegates the actual evaluation logic toModel.test_step()
.This function is cached the first time
Model.evaluate()
orModel.test_on_batch()
is called. The cache is cleared wheneverModel.compile()
is called. You can skip the cache and generate again the function withforce=True
.Args
force
- Whether to regenerate the test function and skip the cached function if available.
Returns
Function. The function created by this method should accept a
tf.data.Iterator
, and return adict
containing values that will be passed totf.keras.Callbacks.on_test_batch_end
.Expand source code
def make_test_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the test function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return a `dict` containing values that will be passed to `tf.keras.Callbacks.on_test_batch_end`. """ if self.test_function is not None and not force: return self.test_function def step_function(model, iterator): """Runs a single evaluation step.""" def run_step(data): outputs = model.test_step(data) # Ensure counter is updated only if `test_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._test_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='first') return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def test_function(iterator): """Runs an evaluation execution with one step.""" return step_function(self, iterator) else: def test_function(iterator): """Runs an evaluation execution with multiple steps.""" for _ in tf.range(self._steps_per_execution): outputs = step_function(self, iterator) return outputs if not self.run_eagerly: test_function = tf.function( test_function, experimental_relax_shapes=True) self.test_function = test_function if self._cluster_coordinator: self.test_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda test_function, args=(iterator,)) return self.test_function
def make_train_function(self, force=False)
-
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()
andModel.train_on_batch()
.Typically, this method directly controls
tf.function
andtf.distribute.Strategy
settings, and delegates the actual training logic toModel.train_step()
.This function is cached the first time
Model.fit()
orModel.train_on_batch()
is called. The cache is cleared wheneverModel.compile()
is called. You can skip the cache and generate again the function withforce=True
.Args
force
- Whether to regenerate the train function and skip the cached function if available.
Returns
Function. The function created by this method should accept a
tf.data.Iterator
, and return adict
containing values that will be passed totf.keras.Callbacks.on_train_batch_end
, such as{'loss': 0.2, 'accuracy': 0.7}
.Expand source code
def make_train_function(self, force=False): """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. You can skip the cache and generate again the function with `force=True`. Args: force: Whether to regenerate the train function and skip the cached function if available. Returns: Function. The function created by this method should accept a `tf.data.Iterator`, and return a `dict` containing values that will be passed to `tf.keras.Callbacks.on_train_batch_end`, such as `{'loss': 0.2, 'accuracy': 0.7}`. """ if self.train_function is not None and not force: return self.train_function def step_function(model, iterator): """Runs a single training step.""" def run_step(data): outputs = model.train_step(data) # Ensure counter is updated only if `train_step` succeeds. with tf.control_dependencies(_minimum_control_deps(outputs)): model._train_counter.assign_add(1) # pylint: disable=protected-access return outputs data = next(iterator) outputs = model.distribute_strategy.run(run_step, args=(data,)) outputs = reduce_per_replica( outputs, self.distribute_strategy, reduction='first') write_scalar_summaries(outputs, step=model._train_counter) # pylint: disable=protected-access return outputs if (self._steps_per_execution is None or self._steps_per_execution.numpy().item() == 1): def train_function(iterator): """Runs a training execution with one step.""" return step_function(self, iterator) else: def train_function(iterator): """Runs a training execution with multiple steps.""" for _ in tf.range(self._steps_per_execution): outputs = step_function(self, iterator) return outputs if not self.run_eagerly: train_function = tf.function( train_function, experimental_relax_shapes=True) self.train_tf_function = train_function self.train_function = train_function if self._cluster_coordinator: self.train_function = lambda iterator: self._cluster_coordinator.schedule( # pylint: disable=g-long-lambda train_function, args=(iterator,)) return self.train_function
def predict(self, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False)
-
Generates output predictions for the input samples.
Computation is done in batches. This method is designed for performance in large scale inputs. For small amount of inputs that fit in one batch, directly using
__call__
is recommended for faster execution, e.g.,model(x)
, ormodel(x, training=False)
if you have layers such astf.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.Args
x
- Input samples. It could be:
- A Numpy array (or array-like), or a list of arrays
(in case the model has multiple inputs).
- A TensorFlow tensor, or a list of tensors
(in case the model has multiple inputs).
- A
tf.data
dataset. - A generator orkeras.utils.Sequence
instance. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in theUnpacking behavior for iterator-like inputs<code> section of </code>Model.fit
. batch_size
- Integer or
None
. Number of samples per batch. If unspecified,batch_size
will default to 32. Do not specify thebatch_size
if your data is in the form of dataset, generators, orkeras.utils.Sequence
instances (since they generate batches). verbose
- Verbosity mode, 0 or 1.
steps
- Total number of steps (batches of samples)
before declaring the prediction round finished.
Ignored with the default value of
None
. If x is atf.data
dataset andsteps
is None,predict
will run until the input dataset is exhausted. callbacks
- List of
Callback
instances. List of callbacks to apply during prediction. See callbacks. max_queue_size
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum size for the generator queue. If unspecified,max_queue_size
will default to 10. workers
- Integer. Used for generator or
keras.utils.Sequence
input only. Maximum number of processes to spin up when using process-based threading. If unspecified,workers
will default to 1. use_multiprocessing
- Boolean. Used for generator or
keras.utils.Sequence
input only. IfTrue
, use process-based threading. If unspecified,use_multiprocessing
will default toFalse
. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes.
See the discussion of
Unpacking behavior for iterator-like inputs
forModel.fit()
. Note that Model.predict uses the same interpretation rules asModel.fit()
andModel.evaluate()
, so inputs must be unambiguous for all three methods.Returns
Numpy array(s) of predictions.
Raises
RuntimeError
- If
model.predict
is wrapped intf.function
. ValueError
- In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.
Expand source code
def predict(self, x, batch_size=None, verbose=0, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False): """Generates output predictions for the input samples. Computation is done in batches. This method is designed for performance in large scale inputs. For small amount of inputs that fit in one batch, directly using `__call__` is recommended for faster execution, e.g., `model(x)`, or `model(x, training=False)` if you have layers such as `tf.keras.layers.BatchNormalization` that behaves differently during inference. Also, note the fact that test loss is not affected by regularization layers like noise and dropout. Args: x: Input samples. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A `tf.data` dataset. - A generator or `keras.utils.Sequence` instance. A more detailed description of unpacking behavior for iterator types (Dataset, generator, Sequence) is given in the `Unpacking behavior for iterator-like inputs` section of `Model.fit`. batch_size: Integer or `None`. Number of samples per batch. If unspecified, `batch_size` will default to 32. Do not specify the `batch_size` if your data is in the form of dataset, generators, or `keras.utils.Sequence` instances (since they generate batches). verbose: Verbosity mode, 0 or 1. steps: Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of `None`. If x is a `tf.data` dataset and `steps` is None, `predict` will run until the input dataset is exhausted. callbacks: List of `keras.callbacks.Callback` instances. List of callbacks to apply during prediction. See [callbacks](/api_docs/python/tf/keras/callbacks). max_queue_size: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum size for the generator queue. If unspecified, `max_queue_size` will default to 10. workers: Integer. Used for generator or `keras.utils.Sequence` input only. Maximum number of processes to spin up when using process-based threading. If unspecified, `workers` will default to 1. use_multiprocessing: Boolean. Used for generator or `keras.utils.Sequence` input only. If `True`, use process-based threading. If unspecified, `use_multiprocessing` will default to `False`. Note that because this implementation relies on multiprocessing, you should not pass non-picklable arguments to the generator as they can't be passed easily to children processes. See the discussion of `Unpacking behavior for iterator-like inputs` for `Model.fit`. Note that Model.predict uses the same interpretation rules as `Model.fit` and `Model.evaluate`, so inputs must be unambiguous for all three methods. Returns: Numpy array(s) of predictions. Raises: RuntimeError: If `model.predict` is wrapped in `tf.function`. ValueError: In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size. """ base_layer.keras_api_gauge.get_cell('predict').set(True) version_utils.disallow_legacy_graph('Model', 'predict') self._check_call_args('predict') _disallow_inside_tf_function('predict') # TODO(yashkatariya): Cache model on the coordinator for faster prediction. # If running under PSS, then swap it with OneDeviceStrategy so that # execution will run on the coordinator. original_pss_strategy = None if self.distribute_strategy._should_use_with_coordinator: # pylint: disable=protected-access original_pss_strategy = self.distribute_strategy self._distribution_strategy = None # Cluster coordinator is set by `.fit()` and `.evaluate()` which is not # needed in `.predict()` because all the predictions happen on the # coordinator/locally. if self._cluster_coordinator: self._cluster_coordinator = None outputs = None with self.distribute_strategy.scope(): # Creates a `tf.data.Dataset` and handles batch and epoch iteration. dataset_types = (tf.compat.v1.data.Dataset, tf.data.Dataset) if (self._in_multi_worker_mode() or _is_tpu_multi_host( self.distribute_strategy)) and isinstance(x, dataset_types): try: options = tf.data.Options() data_option = tf.data.experimental.AutoShardPolicy.DATA options.experimental_distribute.auto_shard_policy = data_option x = x.with_options(options) except ValueError: warnings.warn('Using Model.predict with ' 'MultiWorkerDistributionStrategy or TPUStrategy and ' 'AutoShardPolicy.FILE might lead to out-of-order result' '. Consider setting it to AutoShardPolicy.DATA.') data_handler = data_adapter.get_data_handler( x=x, batch_size=batch_size, steps_per_epoch=steps, initial_epoch=0, epochs=1, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, model=self, steps_per_execution=self._steps_per_execution) # Container that configures and calls `tf.keras.Callback`s. if not isinstance(callbacks, callbacks_module.CallbackList): callbacks = callbacks_module.CallbackList( callbacks, add_history=True, add_progbar=verbose != 0, model=self, verbose=verbose, epochs=1, steps=data_handler.inferred_steps) self.predict_function = self.make_predict_function() self._predict_counter.assign(0) callbacks.on_predict_begin() batch_outputs = None for _, iterator in data_handler.enumerate_epochs(): # Single epoch. with data_handler.catch_stop_iteration(): for step in data_handler.steps(): callbacks.on_predict_batch_begin(step) tmp_batch_outputs = self.predict_function(iterator) if data_handler.should_sync: context.async_wait() batch_outputs = tmp_batch_outputs # No error, now safe to assign. if outputs is None: outputs = tf.nest.map_structure(lambda batch_output: [batch_output], batch_outputs) else: tf.__internal__.nest.map_structure_up_to( batch_outputs, lambda output, batch_output: output.append(batch_output), outputs, batch_outputs) end_step = step + data_handler.step_increment callbacks.on_predict_batch_end(end_step, {'outputs': batch_outputs}) if batch_outputs is None: raise ValueError('Expect x to be a non-empty array or dataset.') callbacks.on_predict_end() all_outputs = tf.__internal__.nest.map_structure_up_to(batch_outputs, concat, outputs) # If originally PSS strategy was used, then replace it back since predict # is running under `OneDeviceStrategy` after the swap and once its done # we need to replace it back to PSS again. if original_pss_strategy is not None: self._distribution_strategy = original_pss_strategy return tf_utils.sync_to_numpy_or_python_type(all_outputs)
def predict_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0)
-
Generates predictions for the input samples from a data generator.
Deprecated
Model.predict()
now supports generators, so there is no longer any need to use this endpoint.Expand source code
@doc_controls.do_not_generate_docs def predict_generator(self, generator, steps=None, callbacks=None, max_queue_size=10, workers=1, use_multiprocessing=False, verbose=0): """Generates predictions for the input samples from a data generator. DEPRECATED: `Model.predict` now supports generators, so there is no longer any need to use this endpoint. """ warnings.warn('`Model.predict_generator` is deprecated and ' 'will be removed in a future version. ' 'Please use `Model.predict`, which supports generators.') return self.predict( generator, steps=steps, max_queue_size=max_queue_size, workers=workers, use_multiprocessing=use_multiprocessing, verbose=verbose, callbacks=callbacks)
def predict_on_batch(self, x)
-
Returns predictions for a single batch of samples.
Args
x
- Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs).
Returns
Numpy array(s) of predictions.
Raises
RuntimeError
- If
model.predict_on_batch
is wrapped intf.function
. ValueError
- In case of mismatch between given number of inputs and expectations of the model.
Expand source code
def predict_on_batch(self, x): """Returns predictions for a single batch of samples. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). Returns: Numpy array(s) of predictions. Raises: RuntimeError: If `model.predict_on_batch` is wrapped in `tf.function`. ValueError: In case of mismatch between given number of inputs and expectations of the model. """ self._check_call_args('predict_on_batch') _disallow_inside_tf_function('predict_on_batch') with self.distribute_strategy.scope(): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x) self.predict_function = self.make_predict_function() outputs = self.predict_function(iterator) return tf_utils.sync_to_numpy_or_python_type(outputs)
def predict_step(self, data)
-
The logic for one inference step.
This method can be overridden to support custom inference logic. This method is called by
Model.make_predict_function()
.This method should contain the mathematical logic for one step of inference. This typically includes the forward pass.
Configuration details for how this logic is run (e.g.
tf.function
andtf.distribute.Strategy
settings), should be left toModel.make_predict_function()
, which can also be overridden.Args
data
- A nested structure of
Tensor
s.
Returns
The result of one inference step, typically the output of calling the
Model
on data.Expand source code
def predict_step(self, data): """The logic for one inference step. This method can be overridden to support custom inference logic. This method is called by `Model.make_predict_function`. This method should contain the mathematical logic for one step of inference. This typically includes the forward pass. Configuration details for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_predict_function`, which can also be overridden. Args: data: A nested structure of `Tensor`s. Returns: The result of one inference step, typically the output of calling the `Model` on data. """ data = data_adapter.expand_1d(data) x, _, _ = data_adapter.unpack_x_y_sample_weight(data) return self(x, training=False)
def reset_metrics(self)
-
Resets the state of all the metrics in the model.
Examples:
>>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"])
>>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> _ = model.fit(x, y, verbose=0) >>> assert all(float(m.result()) for m in model.metrics)
>>> model.reset_metrics() >>> assert all(float(m.result()) == 0 for m in model.metrics)
Expand source code
def reset_metrics(self): """Resets the state of all the metrics in the model. Examples: >>> inputs = tf.keras.layers.Input(shape=(3,)) >>> outputs = tf.keras.layers.Dense(2)(inputs) >>> model = tf.keras.models.Model(inputs=inputs, outputs=outputs) >>> model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) >>> x = np.random.random((2, 3)) >>> y = np.random.randint(0, 2, (2, 2)) >>> _ = model.fit(x, y, verbose=0) >>> assert all(float(m.result()) for m in model.metrics) >>> model.reset_metrics() >>> assert all(float(m.result()) == 0 for m in model.metrics) """ for m in self.metrics: m.reset_state()
def reset_states(self)
-
Expand source code
def reset_states(self): for layer in self.layers: if hasattr(layer, 'reset_states') and getattr(layer, 'stateful', False): layer.reset_states()
def save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True)
-
Saves the model to Tensorflow SavedModel or a single HDF5 file.
Please see
tf.keras.models.save_model
or the Serialization and Saving guide for details.Args
filepath
- String, PathLike, path to SavedModel or H5 file to save the model.
overwrite
- Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
include_optimizer
- If True, save optimizer's state together.
save_format
- Either
'tf'
or'h5'
, indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. signatures
- Signatures to save with the SavedModel. Applicable to the
'tf' format only. Please see the
signatures
argument intf.saved_model.save
for details. options
- (only applies to SavedModel format)
tf.saved_model.SaveOptions
object that specifies options for saving to SavedModel. save_traces
- (only applies to SavedModel format) When enabled, the
SavedModel will store the function traces for each layer. This
can be disabled, so that only the configs of each layer are stored.
Defaults to
True
. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement aget_config()
method.
Example:
from keras.models import load_model model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a compiled model # identical to the previous one model = load_model('my_model.h5')
Expand source code
def save(self, filepath, overwrite=True, include_optimizer=True, save_format=None, signatures=None, options=None, save_traces=True): # pylint: disable=line-too-long """Saves the model to Tensorflow SavedModel or a single HDF5 file. Please see `tf.keras.models.save_model` or the [Serialization and Saving guide](https://keras.io/guides/serialization_and_saving/) for details. Args: filepath: String, PathLike, path to SavedModel or H5 file to save the model. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. include_optimizer: If True, save optimizer's state together. save_format: Either `'tf'` or `'h5'`, indicating whether to save the model to Tensorflow SavedModel or HDF5. Defaults to 'tf' in TF 2.X, and 'h5' in TF 1.X. signatures: Signatures to save with the SavedModel. Applicable to the 'tf' format only. Please see the `signatures` argument in `tf.saved_model.save` for details. options: (only applies to SavedModel format) `tf.saved_model.SaveOptions` object that specifies options for saving to SavedModel. save_traces: (only applies to SavedModel format) When enabled, the SavedModel will store the function traces for each layer. This can be disabled, so that only the configs of each layer are stored. Defaults to `True`. Disabling this will decrease serialization time and reduce file size, but it requires that all custom layers/models implement a `get_config()` method. Example: ```python from keras.models import load_model model.save('my_model.h5') # creates a HDF5 file 'my_model.h5' del model # deletes the existing model # returns a compiled model # identical to the previous one model = load_model('my_model.h5') ``` """ # pylint: enable=line-too-long save.save_model(self, filepath, overwrite, include_optimizer, save_format, signatures, options, save_traces)
def save_spec(self, dynamic_batch=True)
-
Returns the
tf.TensorSpec
of call inputs as a tuple(args, kwargs)
.This value is automatically defined after calling the model for the first time. Afterwards, you can use it when exporting the model for serving:
model = tf.keras.Model(...) @tf.function def serve(*args, **kwargs): outputs = model(*args, **kwargs) # Apply postprocessing steps, or add additional outputs. ... return outputs # arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this example, is # an empty dict since functional models do not use keyword arguments. arg_specs, kwarg_specs = model.save_spec() model.save(path, signatures={ 'serving_default': serve.get_concrete_function(*arg_specs, **kwarg_specs) })
Args
dynamic_batch
- Whether to set the batch sizes of all the returned
tf.TensorSpec
toNone
. (Note that when defining functional or Sequential models withtf.keras.Input([...], batch_size=X)
, the batch size will always be preserved). Defaults toTrue
.
Returns
If the model inputs are defined, returns a tuple
(args, kwargs)
. All elements inargs
andkwargs
aretf.TensorSpec
. If the model inputs are not defined, returnsNone
. The model inputs are automatically set when calling the model,model.fit
,model.evaluate
ormodel.predict
.Expand source code
def save_spec(self, dynamic_batch=True): """Returns the `tf.TensorSpec` of call inputs as a tuple `(args, kwargs)`. This value is automatically defined after calling the model for the first time. Afterwards, you can use it when exporting the model for serving: ```python model = tf.keras.Model(...) @tf.function def serve(*args, **kwargs): outputs = model(*args, **kwargs) # Apply postprocessing steps, or add additional outputs. ... return outputs # arg_specs is `[tf.TensorSpec(...), ...]`. kwarg_specs, in this example, is # an empty dict since functional models do not use keyword arguments. arg_specs, kwarg_specs = model.save_spec() model.save(path, signatures={ 'serving_default': serve.get_concrete_function(*arg_specs, **kwarg_specs) }) ``` Args: dynamic_batch: Whether to set the batch sizes of all the returned `tf.TensorSpec` to `None`. (Note that when defining functional or Sequential models with `tf.keras.Input([...], batch_size=X)`, the batch size will always be preserved). Defaults to `True`. Returns: If the model inputs are defined, returns a tuple `(args, kwargs)`. All elements in `args` and `kwargs` are `tf.TensorSpec`. If the model inputs are not defined, returns `None`. The model inputs are automatically set when calling the model, `model.fit`, `model.evaluate` or `model.predict`. """ return self._get_save_spec(dynamic_batch, inputs_only=False)
def save_weights(self, filepath, overwrite=True, save_format=None, options=None)
-
Saves all layer weights.
Either saves in HDF5 or in TensorFlow format based on the
save_format
argument.When saving in HDF5 format, the weight file has: -
layer_names
(attribute), a list of strings (ordered names of model layers). - For every layer, agroup
namedlayer.name
- For every such layer group, a group attributeweight_names
, a list of strings (ordered names of weights tensor of the layer). - For every weight in the layer, a dataset storing the weight value, named after the weight tensor.When saving in TensorFlow format, all objects referenced by the network are saved in the same format as
tf.train.Checkpoint
, including anyLayer
instances orOptimizer
instances assigned to object attributes. For networks constructed from inputs and outputs usingtf.keras.Model(inputs, outputs)<code>, </code>Layer
instances used by the network are tracked/saved automatically. For user-defined classes which inherit fromtf.keras.Model
,Layer
instances must be assigned to object attributes, typically in the constructor. See the documentation oftf.train.Checkpoint
andtf.keras.Model
for details.While the formats are the same, do not mix
save_weights
andtf.train.Checkpoint
. Checkpoints saved byModel.save_weights()
should be loaded usingModel.load_weights()
. Checkpoints saved usingtf.train.Checkpoint.save
should be restored using the correspondingtf.train.Checkpoint.restore
. Prefertf.train.Checkpoint
oversave_weights
for training checkpoints.The TensorFlow format matches objects and variables by starting at a root object,
self
forsave_weights
, and greedily matching attribute names. ForModel.save()
this is theModel
, and forCheckpoint.save
this is theCheckpoint
even if theCheckpoint
has a model attached. This means saving atf.keras.Model
usingsave_weights
and loading into atf.train.Checkpoint
with aModel
attached (or vice versa) will not match theModel
's variables. See the guide to training checkpoints for details on the TensorFlow format.Args
filepath
- String or PathLike, path to the file to save the weights to. When saving in TensorFlow format, this is the prefix used for checkpoint files (multiple files are generated). Note that the '.h5' suffix causes weights to be saved in HDF5 format.
overwrite
- Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
save_format
- Either 'tf' or 'h5'. A
filepath
ending in '.h5' or '.keras' will default to HDF5 ifsave_format
isNone
. OtherwiseNone
defaults to 'tf'. options
- Optional
tf.train.CheckpointOptions
object that specifies options for saving weights.
Raises
ImportError
- If h5py is not available when attempting to save in HDF5 format.
ValueError
- For invalid/unknown format arguments.
Expand source code
def save_weights(self, filepath, overwrite=True, save_format=None, options=None): """Saves all layer weights. Either saves in HDF5 or in TensorFlow format based on the `save_format` argument. When saving in HDF5 format, the weight file has: - `layer_names` (attribute), a list of strings (ordered names of model layers). - For every layer, a `group` named `layer.name` - For every such layer group, a group attribute `weight_names`, a list of strings (ordered names of weights tensor of the layer). - For every weight in the layer, a dataset storing the weight value, named after the weight tensor. When saving in TensorFlow format, all objects referenced by the network are saved in the same format as `tf.train.Checkpoint`, including any `Layer` instances or `Optimizer` instances assigned to object attributes. For networks constructed from inputs and outputs using `tf.keras.Model(inputs, outputs)`, `Layer` instances used by the network are tracked/saved automatically. For user-defined classes which inherit from `tf.keras.Model`, `Layer` instances must be assigned to object attributes, typically in the constructor. See the documentation of `tf.train.Checkpoint` and `tf.keras.Model` for details. While the formats are the same, do not mix `save_weights` and `tf.train.Checkpoint`. Checkpoints saved by `Model.save_weights` should be loaded using `Model.load_weights`. Checkpoints saved using `tf.train.Checkpoint.save` should be restored using the corresponding `tf.train.Checkpoint.restore`. Prefer `tf.train.Checkpoint` over `save_weights` for training checkpoints. The TensorFlow format matches objects and variables by starting at a root object, `self` for `save_weights`, and greedily matching attribute names. For `Model.save` this is the `Model`, and for `Checkpoint.save` this is the `Checkpoint` even if the `Checkpoint` has a model attached. This means saving a `tf.keras.Model` using `save_weights` and loading into a `tf.train.Checkpoint` with a `Model` attached (or vice versa) will not match the `Model`'s variables. See the [guide to training checkpoints](https://www.tensorflow.org/guide/checkpoint) for details on the TensorFlow format. Args: filepath: String or PathLike, path to the file to save the weights to. When saving in TensorFlow format, this is the prefix used for checkpoint files (multiple files are generated). Note that the '.h5' suffix causes weights to be saved in HDF5 format. overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt. save_format: Either 'tf' or 'h5'. A `filepath` ending in '.h5' or '.keras' will default to HDF5 if `save_format` is `None`. Otherwise `None` defaults to 'tf'. options: Optional `tf.train.CheckpointOptions` object that specifies options for saving weights. Raises: ImportError: If h5py is not available when attempting to save in HDF5 format. ValueError: For invalid/unknown format arguments. """ self._assert_weights_created() filepath = path_to_string(filepath) filepath_is_h5 = saving_utils.is_hdf5_filepath(filepath) if save_format is None: if filepath_is_h5: save_format = 'h5' else: save_format = 'tf' else: user_format = save_format.lower().strip() if user_format in ('tensorflow', 'tf'): save_format = 'tf' elif user_format in ('hdf5', 'h5', 'keras'): save_format = 'h5' else: raise ValueError( 'Unknown format "%s". Was expecting one of {"tf", "h5"}.' % ( save_format,)) if save_format == 'tf' and filepath_is_h5: raise ValueError( ('save_weights got save_format="tf"/"tensorflow", but the ' 'filepath ("%s") looks like an HDF5 file. Omit the ".h5"/".keras" ' 'when saving in TensorFlow format.') % filepath) if save_format == 'h5' and h5py is None: raise ImportError( '`save_weights` requires h5py when saving in hdf5.') if save_format == 'tf': check_filepath = filepath + '.index' else: check_filepath = filepath # If file exists and should not be overwritten: if not overwrite and os.path.isfile(check_filepath): proceed = ask_to_proceed_with_overwrite(check_filepath) if not proceed: return if save_format == 'h5': with h5py.File(filepath, 'w') as f: hdf5_format.save_weights_to_hdf5_group(f, self.layers) else: if tf.executing_eagerly(): session = None else: session = backend.get_session() self._trackable_saver.save(filepath, session=session, options=options) # Record this checkpoint so it's visible from tf.train.latest_checkpoint. tf.__internal__.train.update_checkpoint_state( save_dir=os.path.dirname(filepath), model_checkpoint_path=filepath, save_relative_paths=True, all_model_checkpoint_paths=[filepath])
def summary(self, line_length=None, positions=None, print_fn=None)
-
Prints a string summary of the network.
Args
line_length
- Total length of printed lines (e.g. set this to adapt the display to different terminal window sizes).
positions
- Relative or absolute positions of log elements
in each line. If not provided,
defaults to
[.33, .55, .67, 1.]
. print_fn
- Print function to use. Defaults to
print
. It will be called on each line of the summary. You can set it to a custom function in order to capture the string summary.
Raises
ValueError
- if
summary()
is called before the model is built.
Expand source code
def summary(self, line_length=None, positions=None, print_fn=None): """Prints a string summary of the network. Args: line_length: Total length of printed lines (e.g. set this to adapt the display to different terminal window sizes). positions: Relative or absolute positions of log elements in each line. If not provided, defaults to `[.33, .55, .67, 1.]`. print_fn: Print function to use. Defaults to `print`. It will be called on each line of the summary. You can set it to a custom function in order to capture the string summary. Raises: ValueError: if `summary()` is called before the model is built. """ if not self.built: raise ValueError('This model has not yet been built. ' 'Build the model first by calling `build()` or calling ' '`fit()` with some data, or specify ' 'an `input_shape` argument in the first layer(s) for ' 'automatic build.') layer_utils.print_summary(self, line_length=line_length, positions=positions, print_fn=print_fn)
def test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True, return_dict=False)
-
Test the model on a single batch of samples.
Args
x
- Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
y
- Target data. Like the input data
x
, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent withx
(you cannot have Numpy inputs and tensor targets, or inversely). sample_weight
- Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample.
reset_metrics
- If
True
, the metrics returned will be only for this batch. IfFalse
, the metrics will be statefully accumulated across batches. return_dict
- If
True
, loss and metric results are returned as a dict, with each key being the name of the metric. IfFalse
, they are returned as a list.
Returns
Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute
model.metrics_names
will give you the display labels for the scalar outputs.Raises
RuntimeError
- If
model.test_on_batch
is wrapped intf.function
. ValueError
- In case of invalid user-provided arguments.
Expand source code
def test_on_batch(self, x, y=None, sample_weight=None, reset_metrics=True, return_dict=False): """Test the model on a single batch of samples. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). sample_weight: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. reset_metrics: If `True`, the metrics returned will be only for this batch. If `False`, the metrics will be statefully accumulated across batches. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. Returns: Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.test_on_batch` is wrapped in `tf.function`. ValueError: In case of invalid user-provided arguments. """ self._assert_compile_was_called() self._check_call_args('test_on_batch') _disallow_inside_tf_function('test_on_batch') with self.distribute_strategy.scope(): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, y, sample_weight) self.test_function = self.make_test_function() logs = self.test_function(iterator) if reset_metrics: self.reset_metrics() logs = tf_utils.sync_to_numpy_or_python_type(logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names)
def test_step(self, data)
-
The logic for one evaluation step.
This method can be overridden to support custom evaluation logic. This method is called by
Model.make_test_function()
.This function should contain the mathematical logic for one step of evaluation. This typically includes the forward pass, loss calculation, and metrics updates.
Configuration details for how this logic is run (e.g.
tf.function
andtf.distribute.Strategy
settings), should be left toModel.make_test_function()
, which can also be overridden.Args
data
- A nested structure of
Tensor
s.
Returns
A
dict
containing values that will be passed totf.keras.callbacks.CallbackList.on_train_batch_end
. Typically, the values of theModel
's metrics are returned.Expand source code
def test_step(self, data): """The logic for one evaluation step. This method can be overridden to support custom evaluation logic. This method is called by `Model.make_test_function`. This function should contain the mathematical logic for one step of evaluation. This typically includes the forward pass, loss calculation, and metrics updates. Configuration details for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_test_function`, which can also be overridden. Args: data: A nested structure of `Tensor`s. Returns: A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned. """ data = data_adapter.expand_1d(data) x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) y_pred = self(x, training=False) # Updates stateful loss metrics. self.compiled_loss( y, y_pred, sample_weight, regularization_losses=self.losses) self.compiled_metrics.update_state(y, y_pred, sample_weight) # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if isinstance(result, dict): return_metrics.update(result) else: return_metrics[metric.name] = result return return_metrics
def to_json(self, **kwargs)
-
Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use
keras.models.model_from_json(json_string, custom_objects={})
.Args
**kwargs
- Additional keyword arguments
to be passed to
json.dumps()
.
Returns
A JSON string.
Expand source code
def to_json(self, **kwargs): """Returns a JSON string containing the network configuration. To load a network from a JSON save file, use `keras.models.model_from_json(json_string, custom_objects={})`. Args: **kwargs: Additional keyword arguments to be passed to `json.dumps()`. Returns: A JSON string. """ model_config = self._updated_config() return json.dumps( model_config, default=json_utils.get_json_type, **kwargs)
def to_yaml(self, **kwargs)
-
Returns a yaml string containing the network configuration.
Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError.
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.Args
**kwargs
- Additional keyword arguments
to be passed to
yaml.dump()
.
Returns
A YAML string.
Raises
RuntimeError
- announces that the method poses a security risk
(Use the safer
safe_load
function instead ofunsafe_load
when possible)
Expand source code
def to_yaml(self, **kwargs): """Returns a yaml string containing the network configuration. Note: Since TF 2.6, this method is no longer supported and will raise a RuntimeError. 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. Args: **kwargs: Additional keyword arguments to be passed to `yaml.dump()`. Returns: A YAML string. Raises: RuntimeError: announces that the method poses a security risk (Use the safer `safe_load` function instead of `unsafe_load` when possible) """ raise RuntimeError( 'Method `model.to_yaml()` has been removed due to security risk of ' 'arbitrary code execution. Please use `model.to_json()` instead.' )
def train_on_batch(self, x, y=None, sample_weight=None, class_weight=None, reset_metrics=True, return_dict=False)
-
Runs a single gradient update on a single batch of data.
Args
x
- Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs.
y
- Target data. Like the input data
x
, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent withx
(you cannot have Numpy inputs and tensor targets, or inversely). sample_weight
- Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample.
class_weight
- Optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class.
reset_metrics
- If
True
, the metrics returned will be only for this batch. IfFalse
, the metrics will be statefully accumulated across batches. return_dict
- If
True
, loss and metric results are returned as a dict, with each key being the name of the metric. IfFalse
, they are returned as a list.
Returns
Scalar training loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute
model.metrics_names
will give you the display labels for the scalar outputs.Raises
RuntimeError
- If
model.train_on_batch
is wrapped intf.function
. ValueError
- In case of invalid user-provided arguments.
Expand source code
def train_on_batch(self, x, y=None, sample_weight=None, class_weight=None, reset_metrics=True, return_dict=False): """Runs a single gradient update on a single batch of data. Args: x: Input data. It could be: - A Numpy array (or array-like), or a list of arrays (in case the model has multiple inputs). - A TensorFlow tensor, or a list of tensors (in case the model has multiple inputs). - A dict mapping input names to the corresponding array/tensors, if the model has named inputs. y: Target data. Like the input data `x`, it could be either Numpy array(s) or TensorFlow tensor(s). It should be consistent with `x` (you cannot have Numpy inputs and tensor targets, or inversely). sample_weight: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape (samples, sequence_length), to apply a different weight to every timestep of every sample. class_weight: Optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. reset_metrics: If `True`, the metrics returned will be only for this batch. If `False`, the metrics will be statefully accumulated across batches. return_dict: If `True`, loss and metric results are returned as a dict, with each key being the name of the metric. If `False`, they are returned as a list. Returns: Scalar training loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute `model.metrics_names` will give you the display labels for the scalar outputs. Raises: RuntimeError: If `model.train_on_batch` is wrapped in `tf.function`. ValueError: In case of invalid user-provided arguments. """ self._assert_compile_was_called() self._check_call_args('train_on_batch') _disallow_inside_tf_function('train_on_batch') with self.distribute_strategy.scope(), \ training_utils.RespectCompiledTrainableState(self): iterator = data_adapter.single_batch_iterator(self.distribute_strategy, x, y, sample_weight, class_weight) self.train_function = self.make_train_function() logs = self.train_function(iterator) if reset_metrics: self.reset_metrics() logs = tf_utils.sync_to_numpy_or_python_type(logs) if return_dict: return logs else: return flatten_metrics_in_order(logs, self.metrics_names)
def train_step(self, data)
-
The logic for one training step.
This method can be overridden to support custom training logic. For concrete examples of how to override this method see Customizing what happends in fit. 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
andtf.distribute.Strategy
settings), should be left toModel.make_train_function()
, which can also be overridden.Args
data
- A nested structure of
Tensor
s.
Returns
A
dict
containing values that will be passed totf.keras.callbacks.CallbackList.on_train_batch_end
. Typically, the values of theModel
's metrics are returned. Example:{'loss': 0.2, 'accuracy': 0.7}
.Expand source code
def train_step(self, data): """The logic for one training step. This method can be overridden to support custom training logic. For concrete examples of how to override this method see [Customizing what happends in fit](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). 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. Args: data: A nested structure of `Tensor`s. Returns: A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned. Example: `{'loss': 0.2, 'accuracy': 0.7}`. """ # These are the only transformations `Model.fit` applies to user-input # data when a `tf.data.Dataset` is provided. data = data_adapter.expand_1d(data) x, y, sample_weight = data_adapter.unpack_x_y_sample_weight(data) # Run forward pass. with tf.GradientTape() as tape: y_pred = self(x, training=True) loss = self.compiled_loss( y, y_pred, sample_weight, regularization_losses=self.losses) # Run backwards pass. self.optimizer.minimize(loss, self.trainable_variables, tape=tape) self.compiled_metrics.update_state(y, y_pred, sample_weight) # Collect metrics to return return_metrics = {} for metric in self.metrics: result = metric.result() if isinstance(result, dict): return_metrics.update(result) else: return_metrics[metric.name] = result return return_metrics
Inherited members
Layer
:activity_regularizer
add_loss
add_metric
add_update
add_variable
add_weight
apply
compute_dtype
compute_mask
compute_output_shape
compute_output_signature
count_params
dtype
dtype_policy
dynamic
finalize_state
from_config
get_config
get_input_at
get_input_mask_at
get_input_shape_at
get_losses_for
get_output_at
get_output_mask_at
get_output_shape_at
get_updates_for
inbound_nodes
input
input_mask
input_shape
input_spec
losses
name
non_trainable_variables
non_trainable_weights
outbound_nodes
output
output_mask
output_shape
set_weights
supports_masking
trainable_variables
trainable_weights
variable_dtype
variables
class Sequential (layers=None, name=None)
-
Sequential
groups a linear stack of layers into atf.keras.Model
.Sequential
provides training and inference features on this model.Examples:
>>> # Optionally, the first layer can receive an <code>input\_shape</code> argument: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) >>> # Afterwards, we do automatic shape inference: >>> model.add(tf.keras.layers.Dense(4))
>>> # This is identical to the following: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.Input(shape=(16,))) >>> model.add(tf.keras.layers.Dense(8))
>>> # Note that you can also omit the <code>input\_shape</code> argument. >>> # In that case the model doesn't have any weights until the first call >>> # to a training/evaluation method (since it isn't yet built): >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8)) >>> model.add(tf.keras.layers.Dense(4)) >>> # model.weights not created yet
>>> # Whereas if you specify the input shape, the model gets built >>> # continuously as you are adding layers: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) >>> model.add(tf.keras.layers.Dense(4)) >>> len(model.weights) 4
>>> # When using the delayed-build pattern (no input shape specified), you can >>> # choose to manually build your model by calling >>> # <code>build(batch\_input\_shape)</code>: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8)) >>> model.add(tf.keras.layers.Dense(4)) >>> model.build((None, 16)) >>> len(model.weights) 4
# Note that when using the delayed-build pattern (no input shape specified), # the model gets built the first time you call `fit`, `eval`, or `predict`, # or the first time you call the model on some input data. model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(8)) model.add(tf.keras.layers.Dense(1)) model.compile(optimizer='sgd', loss='mse') # This builds the model for the first time: model.fit(x, y, batch_size=32, epochs=10)
Creates a
Sequential
model instance.Args
layers
- Optional list of layers to add to the model.
name
- Optional name for the model.
Expand source code
class Sequential(functional.Functional): """`Sequential` groups a linear stack of layers into a `tf.keras.Model`. `Sequential` provides training and inference features on this model. Examples: >>> # Optionally, the first layer can receive an `input_shape` argument: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) >>> # Afterwards, we do automatic shape inference: >>> model.add(tf.keras.layers.Dense(4)) >>> # This is identical to the following: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.Input(shape=(16,))) >>> model.add(tf.keras.layers.Dense(8)) >>> # Note that you can also omit the `input_shape` argument. >>> # In that case the model doesn't have any weights until the first call >>> # to a training/evaluation method (since it isn't yet built): >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8)) >>> model.add(tf.keras.layers.Dense(4)) >>> # model.weights not created yet >>> # Whereas if you specify the input shape, the model gets built >>> # continuously as you are adding layers: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8, input_shape=(16,))) >>> model.add(tf.keras.layers.Dense(4)) >>> len(model.weights) 4 >>> # When using the delayed-build pattern (no input shape specified), you can >>> # choose to manually build your model by calling >>> # `build(batch_input_shape)`: >>> model = tf.keras.Sequential() >>> model.add(tf.keras.layers.Dense(8)) >>> model.add(tf.keras.layers.Dense(4)) >>> model.build((None, 16)) >>> len(model.weights) 4 ```python # Note that when using the delayed-build pattern (no input shape specified), # the model gets built the first time you call `fit`, `eval`, or `predict`, # or the first time you call the model on some input data. model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(8)) model.add(tf.keras.layers.Dense(1)) model.compile(optimizer='sgd', loss='mse') # This builds the model for the first time: model.fit(x, y, batch_size=32, epochs=10) ``` """ @tf.__internal__.tracking.no_automatic_dependency_tracking def __init__(self, layers=None, name=None): """Creates a `Sequential` model instance. Args: layers: Optional list of layers to add to the model. name: Optional name for the model. """ # Skip the init in FunctionalModel since model doesn't have input/output yet super(functional.Functional, self).__init__( # pylint: disable=bad-super-call name=name, autocast=False) base_layer.keras_api_gauge.get_cell('Sequential').set(True) self.supports_masking = True self._compute_output_and_mask_jointly = True self._auto_track_sub_layers = False self._inferred_input_shape = None self._has_explicit_input_shape = False self._input_dtype = None self._layer_call_argspecs = {} self._created_nodes = set() # Flag that indicate whether the sequential network topology has been # created. It is false when there isn't any layer, or the layers doesn't # have input shape. self._graph_initialized = False # Unfortunately some Sequential models using custom layers or FeatureColumn # layers have multiple inputs. This is fundamentally incompatible with # most of the Sequential API, and we have to disable a number of features # for such models. self._use_legacy_deferred_behavior = False # Add to the model any layers passed to the constructor. if layers: if not isinstance(layers, (list, tuple)): layers = [layers] for layer in layers: self.add(layer) @property def layers(self): # Historically, `sequential.layers` only returns layers that were added # via `add`, and omits the auto-generated `InputLayer` that comes at the # bottom of the stack. # `Trackable` manages the `_layers` attributes and does filtering # over it. layers = super(Sequential, self).layers if layers and isinstance(layers[0], input_layer.InputLayer): return layers[1:] return layers[:] @tf.__internal__.tracking.no_automatic_dependency_tracking def add(self, layer): """Adds a layer instance on top of the layer stack. Args: layer: layer instance. Raises: TypeError: If `layer` is not a layer instance. ValueError: In case the `layer` argument does not know its input shape. ValueError: In case the `layer` argument has multiple output tensors, or is already connected somewhere else (forbidden in `Sequential` models). """ # If we are passed a Keras tensor created by keras.Input(), we can extract # the input layer from its keras history and use that without any loss of # generality. if hasattr(layer, '_keras_history'): origin_layer = layer._keras_history[0] if isinstance(origin_layer, input_layer.InputLayer): layer = origin_layer if isinstance(layer, tf.Module): if not isinstance(layer, base_layer.Layer): layer = functional.ModuleWrapper(layer) else: raise TypeError('The added layer must be ' 'an instance of class Layer. ' 'Found: ' + str(layer)) tf_utils.assert_no_legacy_layers([layer]) if not self._is_layer_name_unique(layer): raise ValueError('All layers added to a Sequential model ' 'should have unique names. Name "%s" is already the name' ' of a layer in this model. Update the `name` argument ' 'to pass a unique name.' % (layer.name,)) self.built = False set_inputs = False self._maybe_create_attribute('_self_tracked_trackables', []) if not self._self_tracked_trackables: if isinstance(layer, input_layer.InputLayer): # Case where the user passes an Input or InputLayer layer via `add`. set_inputs = True else: batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer) if batch_shape: # Instantiate an input layer. x = input_layer.Input( batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input') # This will build the current layer # and create the node connecting the current layer # to the input layer we just created. layer(x) set_inputs = True if set_inputs: outputs = tf.nest.flatten(layer._inbound_nodes[-1].outputs) if len(outputs) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) self.outputs = outputs self.inputs = layer_utils.get_source_inputs(self.outputs[0]) self.built = True self._has_explicit_input_shape = True elif self.outputs: # If the model is being built continuously on top of an input layer: # refresh its output. output_tensor = layer(self.outputs[0]) if len(tf.nest.flatten(output_tensor)) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) self.outputs = [output_tensor] self.built = True if set_inputs or self._graph_initialized: self._init_graph_network(self.inputs, self.outputs) self._graph_initialized = True else: self._self_tracked_trackables.append(layer) self._handle_deferred_layer_dependencies([layer]) self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call) @tf.__internal__.tracking.no_automatic_dependency_tracking def pop(self): """Removes the last layer in the model. Raises: TypeError: if there are no layers in the model. """ if not self.layers: raise TypeError('There are no layers in the model.') layer = self._self_tracked_trackables.pop() self._layer_call_argspecs.pop(layer) if not self.layers: self.outputs = None self.inputs = None self.built = False self._inferred_input_shape = None self._has_explicit_input_shape = False self._graph_initialized = False elif self._graph_initialized: self.layers[-1]._outbound_nodes = [] self.outputs = [self.layers[-1].output] self._init_graph_network(self.inputs, self.outputs) self.built = True @tf.__internal__.tracking.no_automatic_dependency_tracking def _build_graph_network_for_inferred_shape(self, input_shape, input_dtype=None): if input_shape is None or not self.layers: return if not tf.__internal__.tf2.enabled() or not tf.compat.v1.executing_eagerly_outside_functions(): # This behavior is disabled in V1 or when eager execution is disabled. return if (not self._has_explicit_input_shape and not self._use_legacy_deferred_behavior): # Determine whether the input shape is novel, i.e. whether the model # should be rebuilt. input_shape = tuple(input_shape) if self._inferred_input_shape is None: new_shape = input_shape else: new_shape = relax_input_shape(self._inferred_input_shape, input_shape) if (new_shape is not None and new_shape != self._inferred_input_shape): # A novel shape has been received: we need to rebuild the model. # In case we are inside a graph function, we step out of it. with tf.init_scope(): inputs = input_layer.Input( batch_shape=new_shape, dtype=input_dtype, name=self.layers[0].name + '_input') layer_input = inputs created_nodes = set() for layer in self.layers: # Clear nodes previously created via this method. This prevents # node accumulation and ensures that e.g. `layer.output` is # always connected to `model.inputs` # (this is important e.g. for the feature extraction use case). # We don't just do `layer._inbound_nodes = []` in order # not to break shared layers added to Sequential models (which is # technically illegal as per the `add()` docstring, # but wasn't previously disabled). clear_previously_created_nodes(layer, self._created_nodes) try: # Create Functional API connection by calling the current layer layer_output = layer(layer_input) except: # pylint:disable=bare-except # Functional API calls may fail for a number of reasons: # 1) The layer may be buggy. In this case it will be easier for # the user to debug if we fail on the first call on concrete data, # instead of our own call on a symbolic input. # 2) The layer is dynamic (graph-incompatible) and hasn't # overridden `compute_output_shape`. In this case, it is # impossible to build a graph network. # 3) The layer is otherwise incompatible with the Functional API # (e.g. this is the case for some probabilistic layers that rely # on hacks and that do not return tensors). # In all these cases, we should avoid creating a graph network # (or we simply can't). self._use_legacy_deferred_behavior = True return if len(tf.nest.flatten(layer_output)) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) # Keep track of nodes just created above track_nodes_created_by_last_call(layer, created_nodes) layer_input = layer_output outputs = layer_output self._created_nodes = created_nodes try: # Initialize a graph Network. This call will never fail for # a stack of valid Keras layers. # However some users have layers that are fundamentally incompatible # with the Functional API, which do not return tensors. In this # case, we fall back to the legacy deferred behavior. # TODO(fchollet): consider raising here, as we should not be # supporting such layers. self._init_graph_network(inputs, outputs) self._graph_initialized = True except: # pylint:disable=bare-except self._use_legacy_deferred_behavior = True self._inferred_input_shape = new_shape @generic_utils.default def build(self, input_shape=None): if self._graph_initialized: self._init_graph_network(self.inputs, self.outputs) else: if input_shape is None: raise ValueError('You must provide an `input_shape` argument.') self._build_graph_network_for_inferred_shape(input_shape) if not self.built: input_shape = tuple(input_shape) self._build_input_shape = input_shape super(Sequential, self).build(input_shape) self.built = True def call(self, inputs, training=None, mask=None): # pylint: disable=redefined-outer-name # If applicable, update the static input shape of the model. if not self._has_explicit_input_shape: if not tf.is_tensor(inputs) and not isinstance( inputs, tf.Tensor): # This is a Sequential with mutiple inputs. This is technically an # invalid use case of Sequential, but we tolerate it for backwards # compatibility. self._use_legacy_deferred_behavior = True self._build_input_shape = tf.nest.map_structure(_get_shape_tuple, inputs) if tf.__internal__.tf2.enabled(): logging.warning('Layers in a Sequential model should only have a ' 'single input tensor, but we receive a %s input: %s' '\nConsider rewriting this model with the Functional ' 'API.' % (type(inputs), inputs)) else: self._build_graph_network_for_inferred_shape(inputs.shape, inputs.dtype) if self._graph_initialized: if not self.built: self._init_graph_network(self.inputs, self.outputs) return super(Sequential, self).call(inputs, training=training, mask=mask) outputs = inputs # handle the corner case where self.layers is empty for layer in self.layers: # During each iteration, `inputs` are the inputs to `layer`, and `outputs` # are the outputs of `layer` applied to `inputs`. At the end of each # iteration `inputs` is set to `outputs` to prepare for the next layer. kwargs = {} argspec = self._layer_call_argspecs[layer].args if 'mask' in argspec: kwargs['mask'] = mask if 'training' in argspec: kwargs['training'] = training outputs = layer(inputs, **kwargs) if len(tf.nest.flatten(outputs)) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) # `outputs` will be the inputs to the next layer. inputs = outputs mask = getattr(outputs, '_keras_mask', None) return outputs def compute_output_shape(self, input_shape): shape = input_shape for layer in self.layers: shape = layer.compute_output_shape(shape) return shape def compute_mask(self, inputs, mask): # TODO(omalleyt): b/123540974 This function is not really safe to call # by itself because it will duplicate any updates and losses in graph # mode by `call`ing the Layers again. outputs = self.call(inputs, mask=mask) # pylint: disable=unexpected-keyword-arg return getattr(outputs, '_keras_mask', None) def get_config(self): layer_configs = [] for layer in super(Sequential, self).layers: # `super().layers` include the InputLayer if available (it is filtered out # of `self.layers`). Note that `self._self_tracked_trackables` is managed # by the tracking infrastructure and should not be used. layer_configs.append(generic_utils.serialize_keras_object(layer)) config = { 'name': self.name, 'layers': copy.deepcopy(layer_configs) } if not self._is_graph_network and self._build_input_shape is not None: config['build_input_shape'] = self._build_input_shape return config @classmethod def from_config(cls, config, custom_objects=None): if 'name' in config: name = config['name'] build_input_shape = config.get('build_input_shape') layer_configs = config['layers'] else: name = None build_input_shape = None layer_configs = config model = cls(name=name) for layer_config in layer_configs: layer = layer_module.deserialize(layer_config, custom_objects=custom_objects) model.add(layer) if (not model.inputs and build_input_shape and isinstance(build_input_shape, (tuple, list))): model.build(build_input_shape) return model @property def input_spec(self): if hasattr(self, '_manual_input_spec'): return self._manual_input_spec if self.layers and hasattr(self.layers[0], 'input_spec'): return self.layers[0].input_spec return None @input_spec.setter def input_spec(self, value): self._manual_input_spec = value @property def _trackable_saved_model_saver(self): return model_serialization.SequentialSavedModelSaver(self) def _is_layer_name_unique(self, layer): for ref_layer in self.layers: if layer.name == ref_layer.name and ref_layer is not layer: return False return True def _assert_weights_created(self): if self._graph_initialized: return # When the graph has not been initialized, use the Model's implementation to # to check if the weights has been created. super(functional.Functional, self)._assert_weights_created() # pylint: disable=bad-super-call
Ancestors
- Functional
- Model
- Layer
- tensorflow.python.module.module.Module
- tensorflow.python.training.tracking.tracking.AutoTrackable
- tensorflow.python.training.tracking.base.Trackable
- LayerVersionSelector
- ModelVersionSelector
Subclasses
Instance variables
var layers
-
Expand source code
@property def layers(self): # Historically, `sequential.layers` only returns layers that were added # via `add`, and omits the auto-generated `InputLayer` that comes at the # bottom of the stack. # `Trackable` manages the `_layers` attributes and does filtering # over it. layers = super(Sequential, self).layers if layers and isinstance(layers[0], input_layer.InputLayer): return layers[1:] return layers[:]
Methods
def add(self, layer)
-
Adds a layer instance on top of the layer stack.
Args
layer
- layer instance.
Raises
TypeError
- If
layer
is not a layer instance. ValueError
- In case the
layer
argument does not know its input shape. ValueError
- In case the
layer
argument has multiple output tensors, or is already connected somewhere else (forbidden inSequential
models).
Expand source code
@tf.__internal__.tracking.no_automatic_dependency_tracking def add(self, layer): """Adds a layer instance on top of the layer stack. Args: layer: layer instance. Raises: TypeError: If `layer` is not a layer instance. ValueError: In case the `layer` argument does not know its input shape. ValueError: In case the `layer` argument has multiple output tensors, or is already connected somewhere else (forbidden in `Sequential` models). """ # If we are passed a Keras tensor created by keras.Input(), we can extract # the input layer from its keras history and use that without any loss of # generality. if hasattr(layer, '_keras_history'): origin_layer = layer._keras_history[0] if isinstance(origin_layer, input_layer.InputLayer): layer = origin_layer if isinstance(layer, tf.Module): if not isinstance(layer, base_layer.Layer): layer = functional.ModuleWrapper(layer) else: raise TypeError('The added layer must be ' 'an instance of class Layer. ' 'Found: ' + str(layer)) tf_utils.assert_no_legacy_layers([layer]) if not self._is_layer_name_unique(layer): raise ValueError('All layers added to a Sequential model ' 'should have unique names. Name "%s" is already the name' ' of a layer in this model. Update the `name` argument ' 'to pass a unique name.' % (layer.name,)) self.built = False set_inputs = False self._maybe_create_attribute('_self_tracked_trackables', []) if not self._self_tracked_trackables: if isinstance(layer, input_layer.InputLayer): # Case where the user passes an Input or InputLayer layer via `add`. set_inputs = True else: batch_shape, dtype = training_utils.get_input_shape_and_dtype(layer) if batch_shape: # Instantiate an input layer. x = input_layer.Input( batch_shape=batch_shape, dtype=dtype, name=layer.name + '_input') # This will build the current layer # and create the node connecting the current layer # to the input layer we just created. layer(x) set_inputs = True if set_inputs: outputs = tf.nest.flatten(layer._inbound_nodes[-1].outputs) if len(outputs) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) self.outputs = outputs self.inputs = layer_utils.get_source_inputs(self.outputs[0]) self.built = True self._has_explicit_input_shape = True elif self.outputs: # If the model is being built continuously on top of an input layer: # refresh its output. output_tensor = layer(self.outputs[0]) if len(tf.nest.flatten(output_tensor)) != 1: raise ValueError(SINGLE_LAYER_OUTPUT_ERROR_MSG) self.outputs = [output_tensor] self.built = True if set_inputs or self._graph_initialized: self._init_graph_network(self.inputs, self.outputs) self._graph_initialized = True else: self._self_tracked_trackables.append(layer) self._handle_deferred_layer_dependencies([layer]) self._layer_call_argspecs[layer] = tf_inspect.getfullargspec(layer.call)
def pop(self)
-
Removes the last layer in the model.
Raises
TypeError
- if there are no layers in the model.
Expand source code
@tf.__internal__.tracking.no_automatic_dependency_tracking def pop(self): """Removes the last layer in the model. Raises: TypeError: if there are no layers in the model. """ if not self.layers: raise TypeError('There are no layers in the model.') layer = self._self_tracked_trackables.pop() self._layer_call_argspecs.pop(layer) if not self.layers: self.outputs = None self.inputs = None self.built = False self._inferred_input_shape = None self._has_explicit_input_shape = False self._graph_initialized = False elif self._graph_initialized: self.layers[-1]._outbound_nodes = [] self.outputs = [self.layers[-1].output] self._init_graph_network(self.inputs, self.outputs) self.built = True
Inherited members
Functional
:activity_regularizer
add_loss
add_metric
add_update
add_variable
add_weight
apply
build
call
compile
compute_dtype
compute_mask
compute_output_shape
compute_output_signature
count_params
distribute_strategy
dtype
dtype_policy
dynamic
evaluate
evaluate_generator
finalize_state
fit
fit_generator
from_config
get_config
get_input_at
get_input_mask_at
get_input_shape_at
get_layer
get_losses_for
get_output_at
get_output_mask_at
get_output_shape_at
get_updates_for
get_weights
inbound_nodes
input
input_mask
input_shape
input_spec
load_weights
losses
make_predict_function
make_test_function
make_train_function
metrics
metrics_names
name
non_trainable_variables
non_trainable_weights
outbound_nodes
output
output_mask
output_shape
predict
predict_generator
predict_on_batch
predict_step
reset_metrics
run_eagerly
save
save_spec
save_weights
set_weights
state_updates
summary
supports_masking
test_on_batch
test_step
to_json
to_yaml
train_on_batch
train_step
trainable_variables
trainable_weights
variable_dtype
variables
weights