tf.estimator.DNNRegressor     View source on GitHub    A regressor for TensorFlow DNN models. Inherits From: Estimator, Estimator
tf.estimator.DNNRegressor(
    hidden_units, feature_columns, model_dir=None, label_dimension=1,
    weight_column=None, optimizer='Adagrad', activation_fn=tf.nn.relu,
    dropout=None, config=None, warm_start_from=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, batch_norm=False
)
 Example: categorical_feature_a = categorical_column_with_hash_bucket(...)
categorical_feature_b = categorical_column_with_hash_bucket(...)

categorical_feature_a_emb = embedding_column(
    categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
    categorical_column=categorical_feature_b, ...)

estimator = tf.estimator.DNNRegressor(
    feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
    hidden_units=[1024, 512, 256])

# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = tf.estimator.DNNRegressor(
    feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
    hidden_units=[1024, 512, 256],
    optimizer=tf.compat.v1.train.ProximalAdagradOptimizer(
      learning_rate=0.1,
      l1_regularization_strength=0.001
    ))

# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.DNNRegressor(
    feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
    hidden_units=[1024, 512, 256],
    optimizer=lambda: tf.keras.optimizers.Adam(
        learning_rate=tf.compat.v1.train.exponential_decay(
            learning_rate=0.1,
            global_step=tf.compat.v1.train.get_global_step(),
            decay_steps=10000,
            decay_rate=0.96))

# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.DNNRegressor(
    feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
    hidden_units=[1024, 512, 256],
    warm_start_from="/path/to/checkpoint/dir")

# Input builders
def input_fn_train:
  # Returns tf.data.Dataset of (x, y) tuple where y represents label's class
  # index.
  pass
def input_fn_eval:
  # Returns tf.data.Dataset of (x, y) tuple where y represents label's class
  # index.
  pass
def input_fn_predict:
  # Returns tf.data.Dataset of (x, None) tuple.
  pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if weight_column is not None, a feature with key=weight_column whose value is a Tensor. for each column in feature_columns:  if column is a CategoricalColumn, a feature with key=column.name whose value is a SparseTensor. if column is a WeightedCategoricalColumn, two features: the first with key the id column name, the second with key the weight column name. Both features' value must be a SparseTensor. if column is a DenseColumn, a feature with key=column.name whose value is a Tensor.
  Loss is calculated by using mean squared error.

 Args
  hidden_units   Iterable of number hidden units per layer. All layers are fully connected. Ex. [64, 32] means first layer has 64 nodes and second one has 32.
  feature_columns   An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from FeatureColumn.
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  label_dimension   Number of regression targets per example. This is the size of the last dimension of the labels and logits Tensor objects (typically, these have shape [batch_size, label_dimension]).
  weight_column   A string or a NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. If it is a string, it is used as a key to fetch weight tensor from the features. If it is a NumericColumn, raw tensor is fetched by key weight_column.key, then weight_column.normalizer_fn is applied on it to get weight tensor.
  optimizer   An instance of tf.keras.optimizers.* used to train the model. Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', SGD'), or callable. Defaults to Adagrad optimizer.
  activation_fn   Activation function applied to each layer. If None, will use tf.nn.relu.
  dropout   When not None, the probability we will drop out a given coordinate.
  config   RunConfig object to configure the runtime settings.
  warm_start_from   A string filepath to a checkpoint to warm-start from, or a WarmStartSettings object to fully configure warm-starting. If the string filepath is provided instead of a WarmStartSettings, then all weights are warm-started, and it is assumed that vocabularies and Tensor names are unchanged.
  loss_reduction   One of tf.losses.Reduction except NONE. Describes how to reduce training loss over batch. Defaults to SUM_OVER_BATCH_SIZE.
  batch_norm   Whether to use batch normalization after each hidden layer.    Eager Compatibility 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.

 Attributes
  config

  export_savedmodel

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
eval_dir(
    name=None
)
 Shows the directory name where evaluation metrics are dumped.

 Args
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A string which is the path of directory contains evaluation metrics.
 evaluate View source
evaluate(
    input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
 Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until:
steps batches are processed, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 Args
  input_fn   A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  steps   Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
  checkpoint_path   Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint.
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean.

 Raises
  ValueError   If steps <= 0.    experimental_export_all_saved_models View source
experimental_export_all_saved_models(
    export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
    checkpoint_path=None
)
 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 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.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.Estimator     View source on GitHub    Estimator class to train and evaluate TensorFlow models. Inherits From: Estimator
tf.estimator.Estimator(
    model_fn, model_dir=None, config=None, params=None, warm_start_from=None
)
 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: estimator = tf.estimator.DNNClassifier(
    feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
    hidden_units=[1024, 512, 256],
    warm_start_from="/path/to/checkpoint/dir")
 For more details on warm-start configuration, see tf.estimator.WarmStartSettings.

 Args
  model_fn   Model function. Follows the signature:
features -- This is the first item returned from the input_fn passed to train, evaluate, and predict. This should be a single tf.Tensor or dict of same.
labels -- This is the second item returned from the input_fn passed to train, evaluate, and predict. This should be a single tf.Tensor or dict of same (for multi-head models). If mode is tf.estimator.ModeKeys.PREDICT, labels=None will be passed. If the model_fn's signature does not accept mode, the model_fn must still be able to handle labels=None.
mode -- Optional. Specifies if this is training, evaluation or prediction. See tf.estimator.ModeKeys. params -- Optional dict of hyperparameters. Will receive what is passed to Estimator in params parameter. This allows to configure Estimators from hyper parameter tuning.
config -- Optional estimator.RunConfig object. Will receive what is passed to Estimator as its config parameter, or a default value. Allows setting up things in your model_fn based on configuration such as num_ps_replicas, or model_dir. Returns -- tf.estimator.EstimatorSpec

  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If PathLike object, the path will be resolved. If None, the model_dir in config will be used if set. If both are set, they must be same. If both are None, a temporary directory will be used.
  config   estimator.RunConfig configuration object.
  params   dict of hyper parameters that will be passed into model_fn. Keys are names of parameters, values are basic python types.
  warm_start_from   Optional string filepath to a checkpoint or SavedModel to warm-start from, or a tf.estimator.WarmStartSettings object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a tf.estimator.WarmStartSettings, then all variables are warm-started, and it is assumed that vocabularies and tf.Tensor names are unchanged.

 Raises
  ValueError   parameters of model_fn don't match params.
  ValueError   if this is called via a subclass and if that class overrides a member of Estimator.    Eager Compatibility 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.

 Attributes
  config

  export_savedmodel

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
eval_dir(
    name=None
)
 Shows the directory name where evaluation metrics are dumped.

 Args
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A string which is the path of directory contains evaluation metrics.
 evaluate View source
evaluate(
    input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
 Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until:
steps batches are processed, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 Args
  input_fn   A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  steps   Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
  checkpoint_path   Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint.
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean.

 Raises
  ValueError   If steps <= 0.    experimental_export_all_saved_models View source
experimental_export_all_saved_models(
    export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
    checkpoint_path=None
)
 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 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.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.EstimatorSpec     View source on GitHub    Ops and objects returned from a model_fn and passed to an Estimator.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.EstimatorSpec
tf.estimator.EstimatorSpec(
    mode, predictions=None, loss=None, train_op=None, eval_metric_ops=None,
    export_outputs=None, training_chief_hooks=None, training_hooks=None,
    scaffold=None, evaluation_hooks=None, prediction_hooks=None
)
 EstimatorSpec fully defines the model to be run by an Estimator.

 Args
  mode   A ModeKeys. Specifies if this is training, evaluation or prediction.
  predictions   Predictions Tensor or dict of Tensor.
  loss   Training loss Tensor. Must be either scalar, or with shape [1].
  train_op   Op for the training step.
  eval_metric_ops   Dict of metric results keyed by name. The values of the dict can be one of the following: (1) instance of Metric class. (2) Results of calling a metric function, namely a (metric_tensor, update_op) tuple. metric_tensor should be evaluated without any impact on state (typically is a pure computation results based on variables.). For example, it should not trigger the update_op or requires any input fetching.
  export_outputs   Describes the output signatures to be exported to SavedModel and used during serving. A dict {name: output} where:  name: An arbitrary name for this output. output: an ExportOutput object such as ClassificationOutput, RegressionOutput, or PredictOutput. Single-headed models only need to specify one entry in this dictionary. Multi-headed models should specify one entry for each head, one of which must be named using tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY. If no entry is provided, a default PredictOutput mapping to predictions will be created.

  training_chief_hooks   Iterable of tf.train.SessionRunHook objects to run on the chief worker during training.
  training_hooks   Iterable of tf.train.SessionRunHook objects to run on all workers during training.
  scaffold   A tf.train.Scaffold object that can be used to set initialization, saver, and more to be used in training.
  evaluation_hooks   Iterable of tf.train.SessionRunHook objects to run during evaluation.
  prediction_hooks   Iterable of tf.train.SessionRunHook objects to run during predictions.

 Raises
  ValueError   If validation fails.
  TypeError   If any of the arguments is not the expected type.

 Attributes
  mode

  predictions

  loss

  train_op

  eval_metric_ops

  export_outputs

  training_chief_hooks

  training_hooks

  scaffold

  evaluation_hooks

  prediction_hooks


tf.estimator.EvalSpec     View source on GitHub    Configuration for the "eval" part for the train_and_evaluate call.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.EvalSpec
tf.estimator.EvalSpec(
    input_fn, steps=100, name=None, hooks=None, exporters=None,
    start_delay_secs=120, throttle_secs=600
)
 EvalSpec combines details of evaluation of the trained model as well as its export. Evaluation consists of computing metrics to judge the performance of the trained model. Export writes out the trained model on to external storage.

 Args
  input_fn   A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following:  A 'tf.data.Dataset' object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor.

  steps   Int. Positive number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception. See Estimator.evaluate for details.
  name   String. Name of the evaluation if user needs to run multiple evaluations on different data sets. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.
  hooks   Iterable of tf.train.SessionRunHook objects to run during evaluation.
  exporters   Iterable of Exporters, or a single one, or None. exporters will be invoked after each evaluation.
  start_delay_secs   Int. Start evaluating after waiting for this many seconds.
  throttle_secs   Int. Do not re-evaluate unless the last evaluation was started at least this many seconds ago. Of course, evaluation does not occur if no new checkpoints are available, hence, this is the minimum.

 Raises
  ValueError   If any of the input arguments is invalid.
  TypeError   If any of the arguments is not of the expected type.

 Attributes
  input_fn

  steps

  name

  hooks

  exporters

  start_delay_secs

  throttle_secs


Module: tf.estimator.experimental Public API for tf.estimator.experimental namespace. Classes class InMemoryEvaluatorHook: Hook to run evaluation in training without a checkpoint. class LinearSDCA: Stochastic Dual Coordinate Ascent helper for linear estimators. class RNNClassifier: A classifier for TensorFlow RNN models. class RNNEstimator: An Estimator for TensorFlow RNN models with user-specified head. Functions build_raw_supervised_input_receiver_fn(...): Build a supervised_input_receiver_fn for raw features and labels. call_logit_fn(...): Calls logit_fn (experimental). 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.


tf.estimator.experimental.build_raw_supervised_input_receiver_fn Build a supervised_input_receiver_fn for raw features and labels.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.build_raw_supervised_input_receiver_fn
tf.estimator.experimental.build_raw_supervised_input_receiver_fn(
    features, labels, default_batch_size=None
)
 This function wraps tensor placeholders in a supervised_receiver_fn with the expectation that the features and labels appear precisely as the model_fn expects them. Features and labels can therefore be dicts of tensors, or raw tensors.

 Args
  features   a dict of string to Tensor or Tensor.
  labels   a dict of string to Tensor or Tensor.
  default_batch_size   the number of query examples expected per batch. Leave unset for variable batch size (recommended).

 Returns   A supervised_input_receiver_fn.

 Raises
  ValueError   if features and labels have overlapping keys.


tf.estimator.experimental.call_logit_fn     View source on GitHub    Calls logit_fn (experimental).  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.call_logit_fn
tf.estimator.experimental.call_logit_fn(
    logit_fn, features, mode, params, config
)
 THIS FUNCTION IS EXPERIMENTAL. Keras layers/models are the recommended APIs for logit and model composition. A utility function that calls the provided logit_fn with the relevant subset of provided arguments. Similar to tf.estimator._call_model_fn().

 Args
  logit_fn   A logit_fn as defined above.
  features   The features dict.
  mode   TRAIN / EVAL / PREDICT ModeKeys.
  params   The hyperparameter dict.
  config   The configuration object.

 Returns   A logit Tensor, the output of logit_fn.

 Raises
  ValueError   if logit_fn does not return a Tensor or a dictionary mapping strings to Tensors.


tf.estimator.experimental.InMemoryEvaluatorHook     View source on GitHub    Hook to run evaluation in training without a checkpoint. Inherits From: SessionRunHook  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.InMemoryEvaluatorHook
tf.estimator.experimental.InMemoryEvaluatorHook(
    estimator, input_fn, steps=None, hooks=None, name=None, every_n_iter=100
)
 Example: def train_input_fn():
  ...
  return train_dataset

def eval_input_fn():
  ...
  return eval_dataset

estimator = tf.estimator.DNNClassifier(...)

evaluator = tf.estimator.experimental.InMemoryEvaluatorHook(
    estimator, eval_input_fn)
estimator.train(train_input_fn, hooks=[evaluator])
 Current limitations of this approach are:  It doesn't support multi-node distributed mode. It doesn't support saveable objects other than variables (such as boosted tree support) It doesn't support custom saver logic (such as ExponentialMovingAverage support)

 Args
  estimator   A tf.estimator.Estimator instance to call evaluate.
  input_fn   Equivalent to the input_fn arg to estimator.evaluate. A function that constructs the input data for evaluation. See Creating input functions for more information. The function should construct and return one of the following:  A 'tf.data.Dataset' object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  steps   Equivalent to the steps arg to estimator.evaluate. Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  hooks   Equivalent to the hooks arg to estimator.evaluate. List of SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
  name   Equivalent to the name arg to estimator.evaluate. Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.
  every_n_iter   int, runs the evaluator once every N training iteration.

 Raises
  ValueError   if every_n_iter is non-positive or it's not a single machine training    Methods after_create_session View source
after_create_session(
    session, coord
)
 Does first run which shows the eval metrics before training. after_run View source
after_run(
    run_context, run_values
)
 Runs evaluator. before_run View source
before_run(
    run_context
)
 Called before each call to run(). You can return from this call a SessionRunArgs object indicating ops or tensors to add to the upcoming run() call. These ops/tensors will be run together with the ops/tensors originally passed to the original run() call. The run args you return can also contain feeds to be added to the run() call. The run_context argument is a SessionRunContext that provides information about the upcoming run() call: the originally requested op/tensors, the TensorFlow Session. At this point graph is finalized and you can not add ops.

 Args
  run_context   A SessionRunContext object.

 Returns   None or a SessionRunArgs object.
 begin View source
begin()
 Build eval graph and restoring op. end View source
end(
    session
)
 Runs evaluator for final model.


tf.estimator.experimental.LinearSDCA     View source on GitHub    Stochastic Dual Coordinate Ascent helper for linear estimators.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.LinearSDCA
tf.estimator.experimental.LinearSDCA(
    example_id_column, num_loss_partitions=1, num_table_shards=None,
    symmetric_l1_regularization=0.0, symmetric_l2_regularization=1.0, adaptive=False
)
 Objects of this class are intended to be provided as the optimizer argument (though LinearSDCA objects do not implement the tf.train.Optimizer interface) when creating tf.estimator.LinearClassifier or tf.estimator.LinearRegressor. SDCA can only be used with LinearClassifier and LinearRegressor under the following conditions:  Feature columns are of type V2. Multivalent categorical columns are not normalized. In other words the sparse_combiner argument in the estimator constructor should be "sum". For classification: binary label. For regression: one-dimensional label.  Example usage: real_feature_column = numeric_column(...)
sparse_feature_column = categorical_column_with_hash_bucket(...)
linear_sdca = tf.estimator.experimental.LinearSDCA(
    example_id_column='example_id',
    num_loss_partitions=1,
    num_table_shards=1,
    symmetric_l2_regularization=2.0)
classifier = tf.estimator.LinearClassifier(
    feature_columns=[real_feature_column, sparse_feature_column],
    weight_column=...,
    optimizer=linear_sdca)
classifier.train(input_fn_train, steps=50)
classifier.evaluate(input_fn=input_fn_eval)
 Here the expectation is that the input_fn_* functions passed to train and evaluate return a pair (dict, label_tensor) where dict has example_id_column as key whose value is a Tensor of shape [batch_size] and dtype string. num_loss_partitions defines sigma' in eq (11) of [3]. Convergence of (global) loss is guaranteed if num_loss_partitions is larger or equal to the product (#concurrent train ops/per worker) x (#workers). Larger values for num_loss_partitions lead to slower convergence. The recommended value for num_loss_partitions in tf.estimator (where currently there is one process per worker) is the number of workers running the train steps. It defaults to 1 (single machine). num_table_shards defines the number of shards for the internal state table, typically set to match the number of parameter servers for large data sets. The SDCA algorithm was originally introduced in [1] and it was followed by the L1 proximal step [2], a distributed version [3] and adaptive sampling [4]. [1] www.jmlr.org/papers/volume14/shalev-shwartz13a/shalev-shwartz13a.pdf [2] https://arxiv.org/pdf/1309.2375.pdf [3] https://arxiv.org/pdf/1502.03508.pdf [4] https://arxiv.org/pdf/1502.08053.pdf Details specific to this implementation are provided in: https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/linear_optimizer/doc/sdca.ipynb

 Args
  example_id_column   The column name containing the example ids.
  num_loss_partitions   Number of workers.
  num_table_shards   Number of shards of the internal state table, typically set to match the number of parameter servers.
  symmetric_l1_regularization   A float value, must be greater than or equal to zero.
  symmetric_l2_regularization   A float value, must be greater than zero and should typically be greater than 1.
  adaptive   A boolean indicating whether to use adaptive sampling.    Methods get_train_step View source
get_train_step(
    state_manager, weight_column_name, loss_type, feature_columns, features,
    targets, bias_var, global_step
)
 Returns the training operation of an SdcaModel optimizer.


tf.estimator.experimental.make_early_stopping_hook     View source on GitHub    Creates early-stopping hook.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.make_early_stopping_hook
tf.estimator.experimental.make_early_stopping_hook(
    estimator, should_stop_fn, run_every_secs=60, run_every_steps=None
)
 Returns a SessionRunHook that stops training when should_stop_fn returns True. Usage example: estimator = ...
hook = early_stopping.make_early_stopping_hook(
    estimator, should_stop_fn=make_stop_fn(...))
train_spec = tf.estimator.TrainSpec(..., hooks=[hook])
tf.estimator.train_and_evaluate(estimator, train_spec, ...)
 Caveat: Current implementation supports early-stopping both training and evaluation in local mode. In distributed mode, training can be stopped but evaluation (where it's a separate job) will indefinitely wait for new model checkpoints to evaluate, so you will need other means to detect and stop it. Early-stopping evaluation in distributed mode requires changes in train_and_evaluate API and will be addressed in a future revision.

 Args
  estimator   A tf.estimator.Estimator instance.
  should_stop_fn   callable, function that takes no arguments and returns a bool. If the function returns True, stopping will be initiated by the chief.
  run_every_secs   If specified, calls should_stop_fn at an interval of run_every_secs seconds. Defaults to 60 seconds. Either this or run_every_steps must be set.
  run_every_steps   If specified, calls should_stop_fn every run_every_steps steps. Either this or run_every_secs must be set.

 Returns   A SessionRunHook that periodically executes should_stop_fn and initiates early stopping if the function returns True.

 Raises
  TypeError   If estimator is not of type tf.estimator.Estimator.
  ValueError   If both run_every_secs and run_every_steps are set.


tf.estimator.experimental.make_stop_at_checkpoint_step_hook     View source on GitHub    Creates a proper StopAtCheckpointStepHook based on chief status.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.make_stop_at_checkpoint_step_hook
tf.estimator.experimental.make_stop_at_checkpoint_step_hook(
    estimator, last_step, wait_after_file_check_secs=30
)


tf.estimator.experimental.RNNClassifier A classifier for TensorFlow RNN models. Inherits From: RNNEstimator, Estimator
tf.estimator.experimental.RNNClassifier(
    sequence_feature_columns, context_feature_columns=None, units=None,
    cell_type=USE_DEFAULT, rnn_cell_fn=None, return_sequences=False, model_dir=None,
    n_classes=2, weight_column=None, label_vocabulary=None,
    optimizer='Adagrad',
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,
    sequence_mask='sequence_mask', config=None
)
 Trains a recurrent neural network model to classify instances into one of multiple classes. Example: token_sequence = sequence_categorical_column_with_hash_bucket(...)
token_emb = embedding_column(categorical_column=token_sequence, ...)

estimator = RNNClassifier(
    sequence_feature_columns=[token_emb],
    units=[32, 16], cell_type='lstm')

# Input builders
def input_fn_train: # returns x, y
  pass
estimator.train(input_fn=input_fn_train, steps=100)

def input_fn_eval: # returns x, y
  pass
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
def input_fn_predict: # returns x, None
  pass
predictions = estimator.predict(input_fn=input_fn_predict)
 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if weight_column is not None, a feature with key=weight_column whose value is a Tensor. for each column in sequence_feature_columns:  a feature with key=column.name whose value is a SparseTensor.
 for each column in context_feature_columns:  if column is a CategoricalColumn, a feature with key=column.name whose value is a SparseTensor. if column is a WeightedCategoricalColumn, two features: the first with key the id column name, the second with key the weight column name. Both features' value must be a SparseTensor. if column is a DenseColumn, a feature with key=column.name whose value is a Tensor.
  Loss is calculated by using softmax cross entropy.

 Args
  sequence_feature_columns   An iterable containing the FeatureColumns that represent sequential input. All items in the set should either be sequence columns (e.g. sequence_numeric_column) or constructed from one (e.g. embedding_column with sequence_categorical_column_* as input).
  context_feature_columns   An iterable containing the FeatureColumns for contextual input. The data represented by these columns will be replicated and given to the RNN at each timestep. These columns must be instances of classes derived from DenseColumn such as numeric_column, not the sequential variants.
  units   Iterable of integer number of hidden units per RNN layer. If set, cell_type must also be specified and rnn_cell_fn must be None.
  cell_type   A class producing a RNN cell or a string specifying the cell type. Supported strings are: 'simple_rnn', 'lstm', and 'gru'. If set, units must also be specified and rnn_cell_fn must be None.
  rnn_cell_fn   A function that returns a RNN cell instance that will be used to construct the RNN. If set, units and cell_type cannot be set. This is for advanced users who need additional customization beyond units and cell_type. Note that tf.keras.layers.StackedRNNCells is needed for stacked RNNs.
  return_sequences   A boolean indicating whether to return the last output in the output sequence, or the full sequence. Note that if True, weight_column must be None or a string.
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  n_classes   Number of label classes. Defaults to 2, namely binary classification. Must be > 1.
  weight_column   A string or a NumericColumn created by tf.feature_column.numeric_column defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. If it is a string, it is used as a key to fetch weight tensor from the features. If it is a NumericColumn, raw tensor is fetched by key weight_column.key, then weight_column.normalizer_fn is applied on it to get weight tensor.
  label_vocabulary   A list of strings represents possible label values. If given, labels must be string type and have any value in label_vocabulary. If it is not given, that means labels are already encoded as integer or float within [0, 1] for n_classes=2 and encoded as integer values in {0, 1,..., n_classes-1} for n_classes>2 . Also there will be errors if vocabulary is not provided and labels are string.
  optimizer   An instance of tf.Optimizer or string specifying optimizer type. Defaults to Adagrad optimizer.
  loss_reduction   One of tf.losses.Reduction except NONE. Describes how to reduce training loss over batch. Defaults to SUM_OVER_BATCH_SIZE.
  sequence_mask   A string with the name of the sequence mask tensor. If sequence_mask is in the features dictionary, the provided tensor is used, otherwise the sequence mask is computed from the length of sequential features. The sequence mask is used in evaluation and training mode to aggregate loss and metrics computation while excluding padding steps. It is also added to the predictions dictionary in prediction mode to indicate which steps are padding.
  config   RunConfig object to configure the runtime settings.

 Raises
  ValueError   If units, cell_type, and rnn_cell_fn are not compatible.    Eager Compatibility Estimators are not compatible with eager execution.

 Attributes
  config

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
eval_dir(
    name=None
)
 Shows the directory name where evaluation metrics are dumped.

 Args
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A string which is the path of directory contains evaluation metrics.
 evaluate View source
evaluate(
    input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
 Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until:
steps batches are processed, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 Args
  input_fn   A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  steps   Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
  checkpoint_path   Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint.
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean.

 Raises
  ValueError   If steps <= 0.    experimental_export_all_saved_models View source
experimental_export_all_saved_models(
    export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
    checkpoint_path=None
)
 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 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.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    export_savedmodel View source
export_savedmodel(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, strip_default_attrs=False
)
 Exports inference graph as a SavedModel into the given dir. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This function has been renamed, use export_saved_model instead. 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  strip_default_attrs   Boolean. If True, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see Stripping Default-Valued Attributes.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.


tf.estimator.experimental.RNNEstimator An Estimator for TensorFlow RNN models with user-specified head. Inherits From: Estimator
tf.estimator.experimental.RNNEstimator(
    head, sequence_feature_columns, context_feature_columns=None, units=None,
    cell_type=USE_DEFAULT, rnn_cell_fn=None, return_sequences=False, model_dir=None,
    optimizer='Adagrad', config=None
)
 Example: token_sequence = sequence_categorical_column_with_hash_bucket(...)
token_emb = embedding_column(categorical_column=token_sequence, ...)

estimator = RNNEstimator(
    head=tf.estimator.RegressionHead(),
    sequence_feature_columns=[token_emb],
    units=[32, 16], cell_type='lstm')

# Or with custom RNN cell:
def rnn_cell_fn(_):
  cells = [ tf.keras.layers.LSTMCell(size) for size in [32, 16] ]
  return tf.keras.layers.StackedRNNCells(cells)

estimator = RNNEstimator(
    head=tf.estimator.RegressionHead(),
    sequence_feature_columns=[token_emb],
    rnn_cell_fn=rnn_cell_fn)

# Input builders
def input_fn_train: # returns x, y
  pass
estimator.train(input_fn=input_fn_train, steps=100)

def input_fn_eval: # returns x, y
  pass
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
def input_fn_predict: # returns x, None
  pass
predictions = estimator.predict(input_fn=input_fn_predict)
 Input of train and evaluate should have following features, otherwise there will be a KeyError:  if the head's weight_column is not None, a feature with key=weight_column whose value is a Tensor. for each column in sequence_feature_columns:  a feature with key=column.name whose value is a SparseTensor.
 for each column in context_feature_columns:  if column is a CategoricalColumn, a feature with key=column.name whose value is a SparseTensor. if column is a WeightedCategoricalColumn, two features: the first with key the id column name, the second with key the weight column name. Both features' value must be a SparseTensor. if column is a DenseColumn, a feature with key=column.name whose value is a Tensor.
  Loss and predicted output are determined by the specified head.

 Args
  head   A Head instance. This specifies the model's output and loss function to be optimized.
  sequence_feature_columns   An iterable containing the FeatureColumns that represent sequential input. All items in the set should either be sequence columns (e.g. sequence_numeric_column) or constructed from one (e.g. embedding_column with sequence_categorical_column_* as input).
  context_feature_columns   An iterable containing the FeatureColumns for contextual input. The data represented by these columns will be replicated and given to the RNN at each timestep. These columns must be instances of classes derived from DenseColumn such as numeric_column, not the sequential variants.
  units   Iterable of integer number of hidden units per RNN layer. If set, cell_type must also be specified and rnn_cell_fn must be None.
  cell_type   A class producing a RNN cell or a string specifying the cell type. Supported strings are: 'simple_rnn', 'lstm', and 'gru'. If set, units must also be specified and rnn_cell_fn must be None.
  rnn_cell_fn   A function that returns a RNN cell instance that will be used to construct the RNN. If set, units and cell_type cannot be set. This is for advanced users who need additional customization beyond units and cell_type. Note that tf.keras.layers.StackedRNNCells is needed for stacked RNNs.
  return_sequences   A boolean indicating whether to return the last output in the output sequence, or the full sequence.
  model_dir   Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model.
  optimizer   An instance of tf.Optimizer or string specifying optimizer type. Defaults to Adagrad optimizer.
  config   RunConfig object to configure the runtime settings.

 Raises
  ValueError   If units, cell_type, and rnn_cell_fn are not compatible.    Eager Compatibility Estimators are not compatible with eager execution.

 Attributes
  config

  model_dir

  model_fn   Returns the model_fn which is bound to self.params.
  params
   Methods eval_dir View source
eval_dir(
    name=None
)
 Shows the directory name where evaluation metrics are dumped.

 Args
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A string which is the path of directory contains evaluation metrics.
 evaluate View source
evaluate(
    input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
 Evaluates the model given evaluation data input_fn. For each step, calls input_fn, which returns one batch of data. Evaluates until:
steps batches are processed, or
input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration).

 Args
  input_fn   A function that constructs the input data for evaluation. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  steps   Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the evaluation call.
  checkpoint_path   Path of a specific checkpoint to evaluate. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, evaluation is run with newly initialized Variables instead of ones restored from checkpoint.
  name   Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard.

 Returns   A dict containing the evaluation metrics specified in model_fn keyed by name, as well as an entry global_step which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the loss (mean loss per mini-batch) and the average_loss (mean loss per sample). Canned classifiers also return the accuracy. Canned regressors also return the label/mean and the prediction/mean.

 Raises
  ValueError   If steps <= 0.    experimental_export_all_saved_models View source
experimental_export_all_saved_models(
    export_dir_base, input_receiver_fn_map, assets_extra=None, as_text=False,
    checkpoint_path=None
)
 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  input_receiver_fn_map   dict of tf.estimator.ModeKeys to input_receiver_fn mappings, where the input_receiver_fn is a function that takes no arguments and returns the appropriate subclass of InputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if any input_receiver_fn is None, no export_outputs are provided, or no checkpoint can be found.    export_saved_model View source
export_saved_model(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, experimental_mode=ModeKeys.PREDICT
)
 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.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  experimental_mode   tf.estimator.ModeKeys value indicating with mode will be exported. Note that this feature is experimental.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    export_savedmodel View source
export_savedmodel(
    export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False,
    checkpoint_path=None, strip_default_attrs=False
)
 Exports inference graph as a SavedModel into the given dir. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: This function has been renamed, use export_saved_model instead. 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'}.

 Args
  export_dir_base   A string containing a directory in which to create timestamped subdirectories containing exported SavedModels.
  serving_input_receiver_fn   A function that takes no argument and returns a tf.estimator.export.ServingInputReceiver or tf.estimator.export.TensorServingInputReceiver.
  assets_extra   A dict specifying how to populate the assets.extra directory within the exported SavedModel, or None if no extra assets are needed.
  as_text   whether to write the SavedModel proto in text format.
  checkpoint_path   The checkpoint path to export. If None (the default), the most recent checkpoint found within the model directory is chosen.
  strip_default_attrs   Boolean. If True, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see Stripping Default-Valued Attributes.

 Returns   The path to the exported directory as a bytes object.

 Raises
  ValueError   if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.    get_variable_names View source
get_variable_names()
 Returns list of all variable names in this model.

 Returns   List of names.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    get_variable_value View source
get_variable_value(
    name
)
 Returns value of the variable given by name.

 Args
  name   string or a list of string, name of the tensor.

 Returns   Numpy array - value of the tensor.

 Raises
  ValueError   If the Estimator has not produced a checkpoint yet.    latest_checkpoint View source
latest_checkpoint()
 Finds the filename of the latest saved checkpoint file in model_dir.

 Returns   The full path to the latest checkpoint or None if no checkpoint was found.
 predict View source
predict(
    input_fn, predict_keys=None, hooks=None, checkpoint_path=None,
    yield_single_examples=True
)
 Yields predictions for given features. Please note that interleaving two predict outputs does not work. See: issue/20506

 Args
  input_fn   A function that constructs the features. Prediction continues until input_fn raises an end-of-input exception (tf.errors.OutOfRangeError or StopIteration). See Premade Estimators for more information. The function should construct and return one of the following:
tf.data.Dataset object -- Outputs of Dataset object must have same constraints as below. features -- A tf.Tensor or a dictionary of string feature name to Tensor. features are consumed by model_fn. They should satisfy the expectation of model_fn from inputs. A tuple, in which case the first item is extracted as features.

  predict_keys   list of str, name of the keys to predict. It is used if the tf.estimator.EstimatorSpec.predictions is a dict. If predict_keys is used then rest of the predictions will be filtered from the dictionary. If None, returns all.
  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the prediction call.
  checkpoint_path   Path of a specific checkpoint to predict. If None, the latest checkpoint in model_dir is used. If there are no checkpoints in model_dir, prediction is run with newly initialized Variables instead of ones restored from checkpoint.
  yield_single_examples   If False, yields the whole batch as returned by the model_fn instead of decomposing the batch into individual elements. This is useful if model_fn returns some tensors whose first dimension is not equal to the batch size.

 Yields   Evaluated values of predictions tensors.

 Raises
  ValueError   If batch length of predictions is not the same and yield_single_examples is True.
  ValueError   If there is a conflict between predict_keys and predictions. For example if predict_keys is not None but tf.estimator.EstimatorSpec.predictions is not a dict.    train View source
train(
    input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
 Trains a model given training data input_fn.

 Args
  input_fn   A function that provides input data for training as minibatches. See Premade Estimators for more information. The function should construct and return one of the following:  A tf.data.Dataset object: Outputs of Dataset object must be a tuple (features, labels) with same constraints as below. A tuple (features, labels): Where features is a tf.Tensor or a dictionary of string feature name to Tensor and labels is a Tensor or a dictionary of string label name to Tensor. Both features and labels are consumed by model_fn. They should satisfy the expectation of model_fn from inputs.

  hooks   List of tf.train.SessionRunHook subclass instances. Used for callbacks inside the training loop.
  steps   Number of steps for which to train the model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. steps works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set max_steps instead. If set, max_steps must be None.
  max_steps   Number of total steps for which to train model. If None, train forever or train until input_fn generates the tf.errors.OutOfRange error or StopIteration exception. If set, steps must be None. If OutOfRange or StopIteration occurs in the middle, training stops before max_steps steps. Two calls to train(steps=100) means 200 training iterations. On the other hand, two calls to train(max_steps=100) means that the second call will not do any iteration since first call did all 100 steps.
  saving_listeners   list of CheckpointSaverListener objects. Used for callbacks that run immediately before or after checkpoint savings.

 Returns   self, for chaining.

 Raises
  ValueError   If both steps and max_steps are not None.
  ValueError   If either steps or max_steps <= 0.