A regressor for TensorFlow DNN models.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using mean squared error.
Estimators can be used while eager execution is enabled. Note that input_fn and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that input_fn code using tf.data generally works in both graph and eager modes.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


Estimator class to train and evaluate TensorFlow models.
The Estimator object wraps a model which is specified by a model_fn, which, given inputs and a number of other parameters, returns the ops necessary to perform training, evaluation, or predictions.
All outputs (checkpoints, event files, etc.) are written to model_dir, or a subdirectory thereof. If model_dir is not set, a temporary directory is used.
The config argument can be passed tf.estimator.RunConfig object containing information about the execution environment. It is passed on to the model_fn, if the model_fn has a parameter named "config" (and input functions in the same manner). If the config parameter is not passed, it is instantiated by the Estimator. Not passing config means that defaults useful for local execution are used. Estimator makes config available to the model (for instance, to allow specialization based on the number of workers available), and also uses some of its fields to control internals, especially regarding checkpointing.
The params argument contains hyperparameters. It is passed to the model_fn, if the model_fn has a parameter named "params", and to the input functions in the same manner. Estimator only passes params along, it does not inspect it. The structure of params is therefore entirely up to the developer.
None of Estimator's methods can be overridden in subclasses (its constructor enforces this). Subclasses should use model_fn to configure the base class, and may add methods implementing specialized functionality.
See estimators for more information.
To warm-start an Estimator:
For more details on warm-start configuration, see tf.estimator.WarmStartSettings.
Calling methods of Estimator will work while eager execution is enabled. However, the model_fn and input_fn is not executed eagerly, Estimator will switch to graph mode before calling all user-provided functions (incl. hooks), so their code has to be compatible with graph mode execution. Note that input_fn code using tf.data generally works in both graph and eager modes.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


Public API for tf.estimator.experimental namespace.
class InMemoryEvaluatorHook: Hook to run evaluation in training without a checkpoint.
class KMeans: An Estimator for K-Means clustering.
class LinearSDCA: Stochastic Dual Coordinate Ascent helper for linear estimators.
build_raw_supervised_input_receiver_fn(...): Build a supervised_input_receiver_fn for raw features and labels.
call_logit_fn(...): Calls logit_fn (experimental).
dnn_logit_fn_builder(...): Function builder for a dnn logit_fn.
linear_logit_fn_builder(...): Function builder for a linear logit_fn.
make_early_stopping_hook(...): Creates early-stopping hook.
make_stop_at_checkpoint_step_hook(...): Creates a proper StopAtCheckpointStepHook based on chief status.
stop_if_higher_hook(...): Creates hook to stop if the given metric is higher than the threshold.
stop_if_lower_hook(...): Creates hook to stop if the given metric is lower than the threshold.
stop_if_no_decrease_hook(...): Creates hook to stop if metric does not decrease within given max steps.
stop_if_no_increase_hook(...): Creates hook to stop if metric does not increase within given max steps.


An Estimator for K-Means clustering.
Inherits From: Estimator
The SavedModel saved by the export_saved_model method does not include the cluster centers. However, the cluster centers may be retrieved by the latest checkpoint saved during training. Specifically,
is equivalent to
View source
Returns the cluster centers.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Finds the index of the closest cluster center to each input point.
View source
Returns the sum of squared distances to nearest clusters.
Note that this function is different from the corresponding one in sklearn which returns the negative sum.
View source
Trains a model given training data input_fn.
View source
Transforms each input point to its distances to all cluster centers.
Note that if distance_metric=KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE, this function returns the squared Euclidean distance while the corresponding sklearn function returns the Euclidean distance.


All public utility methods for exporting Estimator to SavedModel.
This file includes functions and constants from core (model_utils) and export.py
class ClassificationOutput: Represents the output of a classification head.
class ExportOutput: Represents an output of a model that can be served.
class PredictOutput: Represents the output of a generic prediction head.
class RegressionOutput: Represents the output of a regression head.
class ServingInputReceiver: A return type for a serving_input_receiver_fn.
class TensorServingInputReceiver: A return type for a serving_input_receiver_fn.
build_parsing_serving_input_receiver_fn(...): Build a serving_input_receiver_fn expecting fed tf.Examples.
build_raw_serving_input_receiver_fn(...): Build a serving_input_receiver_fn expecting feature Tensors.


Utility methods to create simple input_fns.
numpy_input_fn(...): Returns input function that would feed dict of numpy arrays into the model.
pandas_input_fn(...): Returns input function that would feed Pandas DataFrame into the model.


Returns input function that would feed dict of numpy arrays into the model.
This returns a function outputting features and targets based on the dict of numpy arrays. The dict features has the same keys as the x. The dict targets has the same keys as the y if y is a dict.


Returns input function that would feed Pandas DataFrame into the model.


Linear classifier model.
Inherits From: Estimator
Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification.
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using softmax cross entropy.
Estimators can be used while eager execution is enabled. Note that input_fn and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that input_fn code using tf.data generally works in both graph and eager modes.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow linear models with user-specified head.
Inherits From: Estimator
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss and predicted output are determined by the specified head.
Estimators can be used while eager execution is enabled. Note that input_fn and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that input_fn code using tf.data generally works in both graph and eager modes.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


An estimator for TensorFlow Linear regression problems.
Inherits From: Estimator
Train a linear regression model to predict label value given observation of feature values.
Input of train and evaluate should have following features, otherwise there will be a KeyError:
Loss is calculated by using mean squared error.
Estimators can be used while eager execution is enabled. Note that input_fn and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that input_fn code using tf.data generally works in both graph and eager modes.
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


Generates parsing spec for tf.parse_example to be used with regressors.
If users keep data in tf.Example format, they need to call tf.parse_example with a proper feature spec. There are two main things that this utility helps:
Example output of parsing spec:
Example usage with a regressor:


Public API for tf.estimator.tpu namespace.
experimental module: Public API for tf.estimator.tpu.experimental namespace.
class InputPipelineConfig: Please see the definition of these values in TPUConfig.
class RunConfig: RunConfig with TPU support.
class TPUConfig: TPU related configuration required by TPUEstimator.
class TPUEstimator: Estimator with TPU support.
class TPUEstimatorSpec: Ops and objects returned from a model_fn and passed to TPUEstimator.


Public API for tf.estimator.tpu.experimental namespace.
class EmbeddingConfigSpec: Class to keep track of the specification for TPU embeddings.


Class to keep track of the specification for TPU embeddings.
Pass this class to tf.estimator.tpu.TPUEstimator via the embedding_config_spec parameter. At minimum you need to specify feature_columns and optimization_parameters. The feature columns passed should be created with some combination of tf.tpu.experimental.embedding_column and tf.tpu.experimental.shared_embedding_columns.
TPU embeddings do not support arbitrary Tensorflow optimizers and the main optimizer you use for your model will be ignored for the embedding table variables. Instead TPU embeddigns support a fixed set of predefined optimizers that you can select from and set the parameters of. These include adagrad, adam and stochastic gradient descent. Each supported optimizer has a Parameters class in the tf.tpu.experimental namespace.


Please see the definition of these values in TPUConfig.


RunConfig with TPU support.
Inherits From: RunConfig
If device_fn is not None, it overrides the default device function used in Estimator. Otherwise the default one is used.
All global ids in the training cluster are assigned from an increasing sequence of consecutive integers. The first id is 0.
Nodes with task type worker can have id 0, 1, 2. Nodes with task type ps can have id, 0, 1. So, task_id is not unique, but the pair (task_type, task_id) can uniquely determine a node in the cluster.
Global id, i.e., this field, is tracking the index of the node among ALL nodes in the cluster. It is uniquely assigned. For example, for the cluster spec given above, the global ids are assigned as:
View source
Returns a new instance of RunConfig replacing specified properties.
Only the properties in the following list are allowed to be replaced:
In addition, either save_checkpoints_steps or save_checkpoints_secs can be set (should not be both).


TPU related configuration required by TPUEstimator.


Estimator with TPU support.
Inherits From: Estimator
TPUEstimator also supports training on CPU and GPU. You don't need to define a separate tf.estimator.Estimator.
TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks.
TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the input_fn and model_fn. Users should specify global batch size in constructor, and then get the batch size for each shard in input_fn and model_fn by params['batch_size'].
For training, model_fn gets per-core batch size; input_fn may get per-core or per-host batch size depending on per_host_input_for_training in TPUConfig (See docstring for TPUConfig for details).
For evaluation and prediction, model_fn gets per-core batch size and input_fn get per-host batch size.
model_fn should return TPUEstimatorSpec, which expects the eval_metrics for TPU evaluation. If eval_on_tpu is False, the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply.
TPUEstimatorSpec.eval_metrics is a tuple of metric_fn and tensors, where tensors could be a list of any nested structure of Tensors (See TPUEstimatorSpec for details). metric_fn takes the tensors and returns a dict from metric string name to the result of calling a metric function, namely a (metric_tensor, update_op) tuple.
One can set use_tpu to False for testing. All training, evaluation, and predict will be executed on CPU. input_fn and model_fn will receive train_batch_size or eval_batch_size unmodified as params['batch_size'].
TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode.
input_fn for evaluation should NOT raise an end-of-input exception (OutOfRangeError or StopIteration). And all evaluation steps and all batches should have the same size.
Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU .predict, i.e., creating a new TPUEstimator instance with use_tpu=False, might be more convenient.
TPU prediction only works on a single host (one TPU worker).
input_fn must return a Dataset instance rather than features. In fact, .train() and .evaluate() also support Dataset as return value.
export_saved_model exports 2 metagraphs, one with saved_model.SERVING, and another with saved_model.SERVING and saved_model.TPU tags. At serving time, these tags are used to select the appropriate metagraph to load.
Before running the graph on TPU, the TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please use session.run(tpu.initialize_system()).
There are two versions of the API: 1 or 2.
In V1, the exported CPU graph is model_fn as it is. The exported TPU graph wraps tpu.rewrite() and TPUPartitionedCallOp around model_fn so model_fn is on TPU by default. To place ops on CPU, tpu.outside_compilation(host_call, logits) can be used.
In V2, export_saved_model() sets up params['use_tpu'] flag to let the user know if the code is exporting to TPU (or not). When params['use_tpu'] is True, users need to call tpu.rewrite(), TPUPartitionedCallOp and/or batch_function(). Alternatively use inference_on_tpu() which is a convenience wrapper of the three.
TIP: V2 is recommended as it is more flexible (eg: batching, etc).
View source
Shows the directory name where evaluation metrics are dumped.
View source
Evaluates the model given evaluation data input_fn.
For each step, calls input_fn, which returns one batch of data. Evaluates until:
View source
Exports a SavedModel with tf.MetaGraphDefs for each requested mode.
For each mode passed in via the input_receiver_fn_map, this method builds a new graph by calling the input_receiver_fn to obtain feature and label Tensors. Next, this method calls the Estimator's model_fn in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the SavedModel (order of preference: tf.estimator.ModeKeys.TRAIN, tf.estimator.ModeKeys.EVAL, then tf.estimator.ModeKeys.PREDICT), such that up to three tf.MetaGraphDefs are saved with a single set of variables in a single SavedModel directory.
For the variables and tf.MetaGraphDefs, a timestamped export directory below export_dir_base, and writes a SavedModel into it containing the tf.MetaGraphDef for the given mode and its associated signatures.
For prediction, the exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
For training and evaluation, the train_op is stored in an extra collection, and loss, metrics, and predictions are included in a SignatureDef for the mode in question.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Exports inference graph as a SavedModel into the given dir.
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
The experimental_mode parameter can be used to export a single train/eval/predict graph as a SavedModel. See experimental_export_all_saved_models for full docs.
View source
Exports inference graph as a SavedModel into the given dir. (deprecated)
For a detailed guide, see SavedModel from Estimators.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensors, and then calling this Estimator's model_fn to generate the model graph based on those features. It restores the given checkpoint (or, lacking that, the most recent checkpoint) into this graph in a fresh session. Finally it creates a timestamped export directory below the given export_dir_base, and writes a SavedModel into it containing a single tf.MetaGraphDef saved from this session.
The exported MetaGraphDef will provide one SignatureDef for each element of the export_outputs dict returned from the model_fn, named using the same keys. One of these keys is always tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding tf.estimator.export.ExportOutputs, and the inputs are always the input receivers provided by the serving_input_receiver_fn.
Extra assets may be written into the SavedModel via the assets_extra argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}.
View source
Returns list of all variable names in this model.
View source
Returns value of the variable given by name.
View source
Finds the filename of the latest saved checkpoint file in model_dir.
View source
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: issue/20506
View source
Trains a model given training data input_fn.


Ops and objects returned from a model_fn and passed to TPUEstimator.
See EstimatorSpec for mode, predictions, loss, train_op, and export_outputs.
For evaluation, eval_metricsis a tuple of metric_fn and tensors, where metric_fn runs on CPU to generate metrics and tensors represents the Tensors transferred from TPU system to CPU host and passed to metric_fn. To be precise, TPU evaluation expects a slightly different signature from the tf.estimator.Estimator. While EstimatorSpec.eval_metric_ops expects a dict, TPUEstimatorSpec.eval_metrics is a tuple of metric_fn and tensors. The tensors could be a list of Tensors or dict of names to Tensors. The tensors usually specify the model logits, which are transferred back from TPU system to CPU host. All tensors must have be batch-major, i.e., the batch size is the first dimension. Once all tensors are available at CPU host from all shards, they are concatenated (on CPU) and passed as positional arguments to the metric_fn if tensors is list or keyword arguments if tensors is a dict. metric_fn takes the tensors and returns a dict from metric string name to the result of calling a metric function, namely a (metric_tensor, update_op) tuple. See TPUEstimator for MNIST example how to specify the eval_metrics.
scaffold_fn is a function running on CPU to generate the Scaffold. This function should not capture any Tensors in model_fn.
host_call is a tuple of a function and a list or dictionary of tensors to pass to that function and returns a list of Tensors. host_call currently works for train() and evaluate(). The Tensors returned by the function is executed on the CPU on every step, so there is communication overhead when sending tensors from TPU to CPU. To reduce the overhead, try reducing the size of the tensors. The tensors are concatenated along their major (batch) dimension, and so must be >= rank 1. The host_call is useful for writing summaries with tf.contrib.summary.create_file_writer.
View source
Creates an equivalent EstimatorSpec used by CPU train/eval.


A ProtocolMessage
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.summary.Event


Checks whether the current thread has eager execution enabled.
Eager execution is typically enabled via tf.compat.v1.enable_eager_execution, but may also be enabled within the context of a Python function via tf.contrib.eager.py_func.
When eager execution is enabled, returns True in most cases. However, this API might return False in the following use cases.
Inside tf.function:
Inside tf.function after tf.config.run_functions_eagerly(True) is called:
Inside a transformation function for tf.dataset:


Returns True if executing eagerly, even if inside a graph function.
This function will check the outermost context for the program and see if it is in eager mode. It is useful comparing to tf.executing_eagerly(), which checks the current context and will return False within a tf.function body. It can be used to build library that behave differently in eager runtime and v1 session runtime (deprecated).


Returns a tensor with a length 1 axis inserted at index axis. (deprecated arguments)
Given a tensor input, this operation inserts a dimension of length 1 at the dimension index axis of input's shape. The dimension index follows Python indexing rules: It's zero-based, a negative index it is counted backward from the end.
This operation is useful to:
If you have a single image of shape [height, width, channels]:
You can add an outer batch axis by passing axis=0:
The new axis location matches Python list.insert(axis, 1):
Following standard Python indexing rules, a negative axis counts from the end so axis=-1 adds an inner most dimension:
This operation requires that axis is a valid index for input.shape, following Python indexing rules:
This operation is related to:


Public API for tf.experimental namespace.
class Optional: Represents a value that may or may not be present.
async_clear_error(...): Clear pending operations and error statuses in async execution.
async_scope(...): Context manager for grouping async operations.
function_executor_type(...): Context manager for setting the executor of eager defined functions.
output_all_intermediates(...): Whether to output all intermediates from functional control flow ops.
register_filesystem_plugin(...): Loads a TensorFlow FileSystem plugin.


Whether to output all intermediates from functional control flow ops.
The "default" behavior to is to output all intermediates when using v2 control flow inside Keras models in graph mode (possibly inside Estimators). This is needed to support taking gradients of v2 control flow. In graph mode, Keras can sometimes freeze the forward graph before the gradient computation which does not work for v2 control flow since it requires updating the forward ops to output the needed intermediates. We work around this by proactively outputting the needed intermediates when building the forward pass itself. Ideally any such extra tensors should be pruned out at runtime. However, if for any reason this doesn't work for you or if you have an inference-only model you can turn this behavior off using tf.compat.v1.experimental.output_all_intermediates(False).
If with the default behavior you are still seeing errors of the form "Connecting to invalid output X of source node Y which has Z outputs" try setting tf.compat.v1.experimental.output_all_intermediates(True) and please file an issue at https://github.com/tensorflow/tensorflow/issues.


Extract patches from images and put them in the "depth" output dimension.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.image.extract_image_patches


Public API for tf.feature_column namespace.
bucketized_column(...): Represents discretized dense input bucketed by boundaries.
categorical_column_with_hash_bucket(...): Represents sparse feature where ids are set by hashing.
categorical_column_with_identity(...): A CategoricalColumn that returns identity values.
categorical_column_with_vocabulary_file(...): A CategoricalColumn with a vocabulary file.
categorical_column_with_vocabulary_list(...): A CategoricalColumn with in-memory vocabulary.
crossed_column(...): Returns a column for performing crosses of categorical features.
embedding_column(...): DenseColumn that converts from sparse, categorical input.
indicator_column(...): Represents multi-hot representation of given categorical column.
input_layer(...): Returns a dense Tensor as input layer based on given feature_columns.
linear_model(...): Returns a linear prediction Tensor based on given feature_columns.
make_parse_example_spec(...): Creates parsing spec dictionary from input feature_columns.
numeric_column(...): Represents real valued or numerical features.
sequence_categorical_column_with_hash_bucket(...): A sequence of categorical terms where ids are set by hashing.
sequence_categorical_column_with_identity(...): Returns a feature column that represents sequences of integers.
sequence_categorical_column_with_vocabulary_file(...): A sequence of categorical terms where ids use a vocabulary file.
sequence_categorical_column_with_vocabulary_list(...): A sequence of categorical terms where ids use an in-memory list.
sequence_numeric_column(...): Returns a feature column that represents sequences of numeric data.
shared_embedding_columns(...): List of dense columns that convert from sparse, categorical input.
weighted_categorical_column(...): Applies weight values to a CategoricalColumn.


A CategoricalColumn with a vocabulary file.
Use this when your inputs are in string or integer format, and you have a vocabulary file that maps each value to an integer ID. By default, out-of-vocabulary values are ignored. Use either (but not both) of num_oov_buckets and default_value to specify how to include out-of-vocabulary values.
For input dictionary features, features[key] is either Tensor or SparseTensor. If Tensor, missing values can be represented by -1 for int and '' for string, which will be dropped by this feature column.
Example with num_oov_buckets: File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state abbreviation. All inputs with values in that file are assigned an ID 0-49, corresponding to its line number. All other values are hashed and assigned an ID 50-54.
Example with default_value: File '/us/states.txt' contains 51 lines - the first line is 'XX', and the other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' in input, and other values missing from the file, will be assigned ID 0. All others are assigned the corresponding line number 1-50.
And to make an embedding with either:


Returns a dense Tensor as input layer based on given feature_columns.
Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column oriented data should be converted to a single Tensor.


Returns a linear prediction Tensor based on given feature_columns.
This function generates a weighted sum based on output dimension units. Weighted sum refers to logits in classification problems. It refers to the prediction itself for linear regression problems.
Note on supported columns: linear_model treats categorical columns as indicator_columns. To be specific, assume the input as SparseTensor looks like:
linear_model assigns weights for the presence of "a", "b", "c' implicitly, just like indicator_column, while input_layer explicitly requires wrapping each of categorical columns with an embedding_column or an indicator_column.
The sparse_combiner argument works as follows For example, for two features represented as the categorical columns:
with sparse_combiner as "mean", the linear model outputs consequently are:
where y_i is the output, b is the bias, and w_x is the weight assigned to the presence of x in the input features.


Creates parsing spec dictionary from input feature_columns.
The returned dictionary can be used as arg 'features' in tf.io.parse_example.
For the above example, make_parse_example_spec would return the dict:


List of dense columns that convert from sparse, categorical input.
This is similar to embedding_column, except that it produces a list of embedding columns that share the same embedding weights.
Use this when your inputs are sparse and of the same type (e.g. watched and impression video IDs that share the same vocabulary), and you want to convert them to a dense representation (e.g., to feed to a DNN).
Inputs must be a list of categorical columns created by any of the categorical_column_* function. They must all be of the same type and have the same arguments except key. E.g. they can be categorical_column_with_vocabulary_file with the same vocabulary_file. Some or all columns could also be weighted_categorical_column.
Here is an example embedding of two features for a DNNClassifier model:
Here is an example using shared_embedding_columns with model_fn:


A Reader that outputs fixed-length records from a file.
Inherits From: ReaderBase
See ReaderBase for supported methods.
Readers are not compatible with eager execution. Instead, please use tf.data to get data into your model.
View source
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
View source
Returns the number of work units this reader has finished processing.
View source
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
View source
Returns up to num_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num_records even before the last batch.
View source
Restore a reader to its initial clean state.
View source
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
View source
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.


Partitioner to specify a fixed number of shards along given axis.


Import router for absl.flags. See https://github.com/abseil/abseil-py
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags
tf_decorator module: Base TFDecorator class and utility functions for working with decorators.
class ArgumentParser: Base class used to parse and convert arguments.
class ArgumentSerializer: Base class for generating string representations of a flag value.
class BaseListParser: Base class for a parser of lists of strings.
class BooleanFlag: Basic boolean flag.
class BooleanParser: Parser of boolean values.
class CantOpenFlagFileError: Raised when flagfile fails to open.
class CsvListSerializer: Base class for generating string representations of a flag value.
class DuplicateFlagError: Raised if there is a flag naming conflict.
class EnumClassFlag: Basic enum flag; its value is an enum class's member.
class EnumClassParser: Parser of an Enum class member.
class EnumFlag: Basic enum flag; its value can be any string from list of enum_values.
class EnumParser: Parser of a string enum value (a string value from a given set).
class Error: The base class for all flags errors.
class Flag: Information about a command-line flag.
class FlagHolder: Holds a defined flag.
class FlagNameConflictsWithMethodError: Raised when a flag name conflicts with FlagValues methods.
class FlagValues: Registry of 'Flag' objects.
class FloatParser: Parser of floating point values.
class IllegalFlagValueError: Raised when the flag command line argument is illegal.
class IntegerParser: Parser of an integer value.
class ListParser: Parser for a comma-separated list of strings.
class ListSerializer: Base class for generating string representations of a flag value.
class MultiEnumClassFlag: A multi_enum_class flag.
class MultiFlag: A flag that can appear multiple time on the command-line.
class UnparsedFlagAccessError: Raised when accessing the flag value from unparsed FlagValues.
class UnrecognizedFlagError: Raised when a flag is unrecognized.
class ValidationError: Raised when flag validator constraint is not satisfied.
class WhitespaceSeparatedListParser: Parser for a whitespace-separated list of strings.
DEFINE(...): Registers a generic Flag object.
DEFINE_alias(...): Defines an alias flag for an existing one.
DEFINE_bool(...): Registers a boolean flag.
DEFINE_boolean(...): Registers a boolean flag.
DEFINE_enum(...): Registers a flag whose value can be any string from enum_values.
DEFINE_enum_class(...): Registers a flag whose value can be the name of enum members.
DEFINE_flag(...): Registers a 'Flag' object with a 'FlagValues' object.
DEFINE_float(...): Registers a flag whose value must be a float.
DEFINE_integer(...): Registers a flag whose value must be an integer.
DEFINE_list(...): Registers a flag whose value is a comma-separated list of strings.
DEFINE_multi(...): Registers a generic MultiFlag that parses its args with a given parser.
DEFINE_multi_enum(...): Registers a flag whose value can be a list strings from enum_values.
DEFINE_multi_enum_class(...): Registers a flag whose value can be a list of enum members.
DEFINE_multi_float(...): Registers a flag whose value can be a list of arbitrary floats.
DEFINE_multi_integer(...): Registers a flag whose value can be a list of arbitrary integers.
DEFINE_multi_string(...): Registers a flag whose value can be a list of any strings.
DEFINE_spaceseplist(...): Registers a flag whose value is a whitespace-separated list of strings.
DEFINE_string(...): Registers a flag whose value can be any string.
FLAGS(...): Registry of 'Flag' objects.
adopt_module_key_flags(...): Declares that all flags key to a module are key to the current module.
declare_key_flag(...): Declares one flag as key to the current module.
disclaim_key_flags(...): Declares that the current module will not define any more key flags.
doc_to_help(...): Takes a doc string and reformats it as help.
flag_dict_to_args(...): Convert a dict of values into process call parameters.
get_help_width(...): Returns the integer width of help lines that is used in TextWrap.
mark_bool_flags_as_mutual_exclusive(...): Ensures that only one flag among flag_names is True.
mark_flag_as_required(...): Ensures that flag is not None during program execution.
mark_flags_as_mutual_exclusive(...): Ensures that only one flag among flag_names is not None.
mark_flags_as_required(...): Ensures that flags are not None during program execution.
multi_flags_validator(...): A function decorator for defining a multi-flag validator.
register_multi_flags_validator(...): Adds a constraint to multiple flags.
register_validator(...): Adds a constraint, which will be enforced during program execution.
text_wrap(...): Wraps a given text to a maximum line length and returns it.
validator(...): A function decorator for defining a flag validator.


Declares that all flags key to a module are key to the current module.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.adopt_module_key_flags


Base class used to parse and convert arguments.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.ArgumentParser
The parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal.
Subclasses should also define a syntactic_help string which may be presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only.
Returns a string representing the type of the flag.
Parses the string argument and returns the native value.
By default it returns its argument unmodified.


Base class for generating string representations of a flag value.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.ArgumentSerializer
Returns a serialized string of the value.


Base class for a parser of lists of strings.
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.BaseListParser
To extend, inherit from this class; from the subclass init, call
where token is a character used to tokenize, and name is a description of the separator.
See base class.
See base class.


Basic boolean flag.
Inherits From: Flag
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.BooleanFlag
Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name.
For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox.
Returns a str that describes the type of the flag.
Parses string and sets flag value.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


Parser of boolean values.
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.BooleanParser
See base class.
See base class.


Raised when flagfile fails to open.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.CantOpenFlagFileError
E.g. the file doesn't exist, or has wrong permissions.


Base class for generating string representations of a flag value.
Inherits From: ArgumentSerializer
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.CsvListSerializer
Serializes a list as a CSV string or unicode.


Declares one flag as key to the current module.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.declare_key_flag
Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --helpfull).
flags.declare_key_flag('flag_1')


Registers a generic Flag object.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE
Auxiliary function: clients should use the specialized DEFINE_ function instead.


Defines an alias flag for an existing one.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_alias


Registers a boolean flag.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_bool, tf.compat.v1.app.flags.DEFINE_boolean, tf.compat.v1.flags.DEFINE_boolean
Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line.


Registers a flag whose value can be any string from enum_values.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_enum
Instead of a string enum, prefer DEFINE_enum_class, which allows defining enums from an enum.Enum class.


Registers a flag whose value can be the name of enum members.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_enum_class


Registers a 'Flag' object with a 'FlagValues' object.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_flag
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE_xxx functions, such as DEFINE_string or DEFINE_integer. But developers who need to create Flag objects themselves should use this function to register their flags.


Registers a flag whose value must be a float.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_float
If lower_bound or upper_bound are set, then this flag must be within the given range.


Registers a flag whose value must be an integer.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_integer
If lower_bound, or upper_bound are set, then this flag must be within the given range.


Registers a flag whose value is a comma-separated list of strings.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_list
The flag value is parsed with a CSV parser.


Registers a generic MultiFlag that parses its args with a given parser.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags.


Registers a flag whose value can be a list strings from enum_values.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi_enum
Use the flag on the command line multiple times to place multiple enum values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings.


Registers a flag whose value can be a list of enum members.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi_enum_class
Use the flag on the command line multiple times to place multiple enum values into the list.


Registers a flag whose value can be a list of arbitrary floats.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi_float
Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats.


Registers a flag whose value can be a list of arbitrary integers.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi_integer
Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers.


Registers a flag whose value can be a list of any strings.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_multi_string
Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings.


Registers a flag whose value is a whitespace-separated list of strings.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_spaceseplist
Any whitespace can be used as a separator.


Registers a flag whose value can be any string.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DEFINE_string


Declares that the current module will not define any more key flags.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.disclaim_key_flags
Normally, the module that calls the DEFINE_xxx functions claims the flag to be its key flag. This is undesirable for modules that define additional DEFINE_yyy functions with its own flag parsers and serializers, since that module will accidentally claim flags defined by DEFINE_yyy as its key flags. After calling this function, the module disclaims flag definitions thereafter, so the key flags will be correctly attributed to the caller of DEFINE_yyy.
After calling this function, the module will not be able to define any more flags. This function will affect all FlagValues objects.


Takes a doc string and reformats it as help.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.doc_to_help


Raised if there is a flag naming conflict.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.DuplicateFlagError
Creates a DuplicateFlagError by providing flag name and values.


Basic enum flag; its value is an enum class's member.
Inherits From: Flag
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.EnumClassFlag
Returns a str that describes the type of the flag.
Parses string and sets flag value.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


Parser of an Enum class member.
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.EnumClassParser
See base class.
Determines validity of argument and returns the correct element of enum.


Basic enum flag; its value can be any string from list of enum_values.
Inherits From: Flag
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.EnumFlag
Returns a str that describes the type of the flag.
Parses string and sets flag value.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


Parser of a string enum value (a string value from a given set).
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.EnumParser
See base class.
Determines validity of argument and returns the correct element of enum.


The base class for all flags errors.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.Error


Information about a command-line flag.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.Flag
'Flag' objects define the following fields: .name - the name for this flag; .default - the default value for this flag; .default_unparsed - the unparsed default value for this flag. .default_as_str - default value as repr'd string, e.g., "'true'" (or None); .value - the most recent parsed value of this flag; set by parse(); .help - a help string or None if no help is available; .short_name - the single letter alias for this flag (or None); .boolean - if 'true', this flag does not accept arguments; .present - true if this flag was parsed from command line flags; .parser - an ArgumentParser object; .serializer - an ArgumentSerializer object; .allow_override - the flag may be redefined without raising an error, and newly defined flag overrides the old one. .allow_override_cpp - use the flag from C++ if available; the flag definition is replaced by the C++ flag after init; .allow_hide_cpp - use the Python flag despite having a C++ flag with the same name (ignore the C++ flag); .using_default_value - the flag value has not been set by user; .allow_overwrite - the flag may be parsed more than once without raising an error, the last set value will be used; .allow_using_method_names - whether this flag can be defined even if it has a name that conflicts with a FlagValues method.
The only public method of a 'Flag' object is parse(), but it is typically only called by a 'FlagValues' object. The parse() method is a thin wrapper around the 'ArgumentParser' parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, an Error is raised.
parse() is also called during init to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the main module neglects to parse the command line arguments. The .present attribute is cleared after init parsing. If the default value is set to None, then the init parsing step is skipped and the .value attribute is initialized to None.
Returns a str that describes the type of the flag.
Parses string and sets flag value.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


Holds a defined flag.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.FlagHolder
This facilitates a cleaner api around global state. Instead of
it encourages code like
since the name of the flag appears only once in the source code.
If _ensure_non_none_value is True, then return value is not None.
Return self==value.


Raised when a flag name conflicts with FlagValues methods.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.FlagNameConflictsWithMethodError


Registry of 'Flag' objects.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.FLAGS
A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: flags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via setitem: FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through getattr. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag' objects through the call method. Unparsed arguments, including argv0 are returned. argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use of the dictionary-like operator, getitem: x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects.


Registry of 'Flag' objects.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.FlagValues
A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: flags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via setitem: FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through getattr. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag' objects through the call method. Unparsed arguments, including argv0 are returned. argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use of the dictionary-like operator, getitem: x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects.
Appends flags registered in another FlagValues instance.
Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
Return the name of the module defining this flag, or default.
Return the ID of the module defining this flag, or default.
Returns a dictionary that maps flag names to flag values.
Returns the dictionary of module_name -> list of defined flags.
Returns the dictionary of module_id -> list of defined flags.
Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag assignment is separated by a newline.
Returns the value of a flag (if not None) or a default value.
Returns the list of flags defined by a module.
Returns a help string for all known flags.
Returns the list of key flags for a module.
Returns whether flags were parsed.
Returns the dictionary of module_name -> list of key flags.
Describes the key flags of the main module.
Explicitly marks flags as parsed.
Use this when the caller knows that this FlagValues has been parsed as if a call() invocation has happened. This is only a public method for use by things like appcommands which do additional command like parsing.
Describes the key flags of a module.
Processes command line args, but also allow args to be read from file.
This function is called by FLAGS(argv). It scans the input list for a flag that looks like: --flagfile=. Then it opens , reads all valid key and value pairs and inserts them into the input list in exactly the place where the --flagfile arg is found.
Note that your application's flags are still defined the usual way using absl.flags DEFINE_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input): --> For duplicate flags, the last one we hit should "win". --> Since flags that appear later win, a flagfile's settings can be "weak" if the --flagfile comes at the beginning of the argument sequence, and it can be "strong" if the --flagfile comes at the end. --> A further "--flagfile=" CAN be nested in a flagfile. It will be expanded in exactly the spot where it is found. --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines should be ignored.
Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we can later sort the flags by module.
Records the module that defines a specific flag.
Specifies that a flag is a key flag for a module.
Remove flags that were previously appended from another FlagValues.
Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value.
Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See http://docs.python.org/library/getopt.html#getopt.gnu_getopt
Unparses all flags to the point before any FLAGS(argv) was called.
Verifies whether all flags pass validation.
Outputs flag documentation in XML format.
Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned.
Returns True if name is a value (flag) in the dict.
Returns the Flag object for the flag --name.


Convert a dict of values into process call parameters.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.flag_dict_to_args
This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module.


Parser of floating point values.
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.FloatParser
Parsed value may be bounded to a given upper and lower bound.
Returns the float value of argument.
See base class.
Returns whether the value is outside the bounds or not.
See base class.


Returns the integer width of help lines that is used in TextWrap.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.get_help_width


Raised when the flag command line argument is illegal.
Inherits From: Error
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.IllegalFlagValueError


Parser of an integer value.
Inherits From: ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.IntegerParser
Parsed value may be bounded to a given upper and lower bound.
Returns the int value of argument.
See base class.
Returns whether the value is outside the bounds or not.
See base class.


Parser for a comma-separated list of strings.
Inherits From: BaseListParser, ArgumentParser
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.ListParser
See base class.
Parses argument as comma-separated list of strings.


Base class for generating string representations of a flag value.
Inherits From: ArgumentSerializer
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.ListSerializer
See base class.


Ensures that only one flag among flag_names is True.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.mark_bool_flags_as_mutual_exclusive


Ensures that only one flag among flag_names is not None.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.mark_flags_as_mutual_exclusive
Important note: This validator checks if flag values are None, and it does not distinguish between default and explicit values. Therefore, this validator does not make sense when applied to flags with default values other than None, including other false values (e.g. False, 0, '', []). That includes multi flags with a default value of [] instead of None.


Ensures that flags are not None during program execution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.mark_flags_as_required
If your module might be imported by others, and you only wish to make the flag required when the module is directly executed, call this method like this:
if name == 'main': flags.mark_flags_as_required(['flag1', 'flag2', 'flag3']) app.run()


Ensures that flag is not None during program execution.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.mark_flag_as_required
Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on.
If your module might be imported by others, and you only wish to make the flag required when the module is directly executed, call this method like this:
if name == 'main': flags.mark_flag_as_required('your_flag_name') app.run()


A multi_enum_class flag.
Inherits From: MultiFlag, Flag
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.MultiEnumClassFlag
See the doc for MultiFlag for most behaviors of this class. In addition, this class knows how to handle enum.Enum instances as values for this flag type.
See base class.
Parses one or more arguments with the installed parser.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


A flag that can appear multiple time on the command-line.
Inherits From: Flag
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.MultiFlag
The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line.
See the doc for Flag for most behavior of this class. Only differences in behavior are described here:
The default value may be either a single value or an iterable of values. A single value is transformed into a single-item list of that value.
The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value
See base class.
Parses one or more arguments with the installed parser.
Serializes the flag.
Return self==value.
Return a >= b. Computed by @total_ordering from (not a < b).
Return a > b. Computed by @total_ordering from (not a < b) and (a != b).
Return a <= b. Computed by @total_ordering from (a < b) or (a == b).
Return self<value.


A function decorator for defining a multi-flag validator.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.multi_flags_validator
Registers the decorated function as a validator for flag_names, e.g.
@flags.multi_flags_validator(['foo', 'bar']) def _CheckFooBar(flags_dict): ...
See register_multi_flags_validator() for the specification of checker function.


Adds a constraint to multiple flags.
Compat aliases for migration
See Migration guide for more details.
tf.compat.v1.app.flags.register_multi_flags_validator
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value.