tf.estimator.experimental.stop_if_higher_hook     View source on GitHub    Creates hook to stop if the given metric is higher than the threshold.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.stop_if_higher_hook
tf.estimator.experimental.stop_if_higher_hook(
    estimator, metric_name, threshold, eval_dir=None, min_steps=0,
    run_every_secs=60, run_every_steps=None
)
 Usage example: estimator = ...
# Hook to stop training if accuracy becomes higher than 0.9.
hook = early_stopping.stop_if_higher_hook(estimator, "accuracy", 0.9)
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.
  metric_name   str, metric to track. "loss", "accuracy", etc.
  threshold   Numeric threshold for the given metric.
  eval_dir   If set, directory containing summary files with eval metrics. By default, estimator.eval_dir() will be used.
  min_steps   int, stop is never requested if global step is less than this value. Defaults to 0.
  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   An early-stopping hook of type SessionRunHook that periodically checks if the given metric is higher than specified threshold and initiates early stopping if true.


tf.estimator.experimental.stop_if_lower_hook     View source on GitHub    Creates hook to stop if the given metric is lower than the threshold.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.stop_if_lower_hook
tf.estimator.experimental.stop_if_lower_hook(
    estimator, metric_name, threshold, eval_dir=None, min_steps=0,
    run_every_secs=60, run_every_steps=None
)
 Usage example: estimator = ...
# Hook to stop training if loss becomes lower than 100.
hook = early_stopping.stop_if_lower_hook(estimator, "loss", 100)
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.
  metric_name   str, metric to track. "loss", "accuracy", etc.
  threshold   Numeric threshold for the given metric.
  eval_dir   If set, directory containing summary files with eval metrics. By default, estimator.eval_dir() will be used.
  min_steps   int, stop is never requested if global step is less than this value. Defaults to 0.
  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   An early-stopping hook of type SessionRunHook that periodically checks if the given metric is lower than specified threshold and initiates early stopping if true.


tf.estimator.experimental.stop_if_no_decrease_hook     View source on GitHub    Creates hook to stop if metric does not decrease within given max steps.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.stop_if_no_decrease_hook
tf.estimator.experimental.stop_if_no_decrease_hook(
    estimator, metric_name, max_steps_without_decrease, eval_dir=None, min_steps=0,
    run_every_secs=60, run_every_steps=None
)
 Usage example: estimator = ...
# Hook to stop training if loss does not decrease in over 100000 steps.
hook = early_stopping.stop_if_no_decrease_hook(estimator, "loss", 100000)
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.
  metric_name   str, metric to track. "loss", "accuracy", etc.
  max_steps_without_decrease   int, maximum number of training steps with no decrease in the given metric.
  eval_dir   If set, directory containing summary files with eval metrics. By default, estimator.eval_dir() will be used.
  min_steps   int, stop is never requested if global step is less than this value. Defaults to 0.
  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   An early-stopping hook of type SessionRunHook that periodically checks if the given metric shows no decrease over given maximum number of training steps, and initiates early stopping if true.


tf.estimator.experimental.stop_if_no_increase_hook     View source on GitHub    Creates hook to stop if metric does not increase within given max steps.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.experimental.stop_if_no_increase_hook
tf.estimator.experimental.stop_if_no_increase_hook(
    estimator, metric_name, max_steps_without_increase, eval_dir=None, min_steps=0,
    run_every_secs=60, run_every_steps=None
)
 Usage example: estimator = ...
# Hook to stop training if accuracy does not increase in over 100000 steps.
hook = early_stopping.stop_if_no_increase_hook(estimator, "accuracy", 100000)
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.
  metric_name   str, metric to track. "loss", "accuracy", etc.
  max_steps_without_increase   int, maximum number of training steps with no increase in the given metric.
  eval_dir   If set, directory containing summary files with eval metrics. By default, estimator.eval_dir() will be used.
  min_steps   int, stop is never requested if global step is less than this value. Defaults to 0.
  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   An early-stopping hook of type SessionRunHook that periodically checks if the given metric shows no increase over given maximum number of training steps, and initiates early stopping if true.


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


tf.estimator.export.build_parsing_serving_input_receiver_fn     View source on GitHub    Build a serving_input_receiver_fn expecting fed tf.Examples.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.build_parsing_serving_input_receiver_fn
tf.estimator.export.build_parsing_serving_input_receiver_fn(
    feature_spec, default_batch_size=None
)
 Creates a serving_input_receiver_fn that expects a serialized tf.Example fed into a string placeholder. The function parses the tf.Example according to the provided feature_spec, and returns all parsed Tensors as features.

 Args
  feature_spec   a dict of string to VarLenFeature/FixedLenFeature.
  default_batch_size   the number of query examples expected per batch. Leave unset for variable batch size (recommended).

 Returns   A serving_input_receiver_fn suitable for use in serving.


tf.estimator.export.build_raw_serving_input_receiver_fn     View source on GitHub    Build a serving_input_receiver_fn expecting feature Tensors.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.build_raw_serving_input_receiver_fn
tf.estimator.export.build_raw_serving_input_receiver_fn(
    features, default_batch_size=None
)
 Creates an serving_input_receiver_fn that expects all features to be fed directly.

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

 Returns   A serving_input_receiver_fn.


tf.estimator.export.ClassificationOutput     View source on GitHub    Represents the output of a classification head. Inherits From: ExportOutput  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.ClassificationOutput
tf.estimator.export.ClassificationOutput(
    scores=None, classes=None
)
 Either classes or scores or both must be set. The classes Tensor must provide string labels, not integer class IDs. If only classes is set, it is interpreted as providing top-k results in descending order. If only scores is set, it is interpreted as providing a score for every class in order of class ID. If both classes and scores are set, they are interpreted as zipped, so each score corresponds to the class at the same index. Clients should not depend on the order of the entries.

 Args
  scores   A float Tensor giving scores (sometimes but not always interpretable as probabilities) for each class. May be None, but only if classes is set. Interpretation varies-- see class doc.
  classes   A string Tensor giving predicted class labels. May be None, but only if scores is set. Interpretation varies-- see class doc.

 Raises
  ValueError   if neither classes nor scores is set, or one of them is not a Tensor with the correct dtype.

 Attributes
  classes

  scores
   Methods as_signature_def View source
as_signature_def(
    receiver_tensors
)
 Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs.

 Args
  receiver_tensors   a Tensor, or a dict of string to Tensor, specifying input nodes that will be fed.


tf.estimator.export.ExportOutput     View source on GitHub    Represents an output of a model that can be served.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.ExportOutput  These typically correspond to model heads. Methods as_signature_def View source
@abc.abstractmethod
as_signature_def(
    receiver_tensors
)
 Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs.

 Args
  receiver_tensors   a Tensor, or a dict of string to Tensor, specifying input nodes that will be fed.


tf.estimator.export.PredictOutput     View source on GitHub    Represents the output of a generic prediction head. Inherits From: ExportOutput  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.PredictOutput
tf.estimator.export.PredictOutput(
    outputs
)
 A generic prediction need not be either a classification or a regression. Named outputs must be provided as a dict from string to Tensor,

 Args
  outputs   A Tensor or a dict of string to Tensor representing the predictions.

 Raises
  ValueError   if the outputs is not dict, or any of its keys are not strings, or any of its values are not Tensors.

 Attributes
  outputs
   Methods as_signature_def View source
as_signature_def(
    receiver_tensors
)
 Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs.

 Args
  receiver_tensors   a Tensor, or a dict of string to Tensor, specifying input nodes that will be fed.


tf.estimator.export.RegressionOutput     View source on GitHub    Represents the output of a regression head. Inherits From: ExportOutput  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.RegressionOutput
tf.estimator.export.RegressionOutput(
    value
)

 Args
  value   a float Tensor giving the predicted values. Required.

 Raises
  ValueError   if the value is not a Tensor with dtype tf.float32.

 Attributes
  value
   Methods as_signature_def View source
as_signature_def(
    receiver_tensors
)
 Generate a SignatureDef proto for inclusion in a MetaGraphDef. The SignatureDef will specify outputs as described in this ExportOutput, and will use the provided receiver_tensors as inputs.

 Args
  receiver_tensors   a Tensor, or a dict of string to Tensor, specifying input nodes that will be fed.


tf.estimator.export.ServingInputReceiver     View source on GitHub    A return type for a serving_input_receiver_fn.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.ServingInputReceiver
tf.estimator.export.ServingInputReceiver(
    features, receiver_tensors, receiver_tensors_alternatives=None
)

 Attributes
  features   A Tensor, SparseTensor, or dict of string or int to Tensor or SparseTensor, specifying the features to be passed to the model. Note: if features passed is not a dict, it will be wrapped in a dict with a single entry, using 'feature' as the key. Consequently, the model must accept a feature dict of the form {'feature': tensor}. You may use TensorServingInputReceiver if you want the tensor to be passed as is.
  receiver_tensors   A Tensor, SparseTensor, or dict of string to Tensor or SparseTensor, specifying input nodes where this receiver expects to be fed by default. Typically, this is a single placeholder expecting serialized tf.Example protos.
  receiver_tensors_alternatives   a dict of string to additional groups of receiver tensors, each of which may be a Tensor, SparseTensor, or dict of string to Tensor orSparseTensor. These named receiver tensor alternatives generate additional serving signatures, which may be used to feed inputs at different points within the input receiver subgraph. A typical usage is to allow feeding raw feature Tensors downstream of the tf.parse_example() op. Defaults to None.


tf.estimator.export.TensorServingInputReceiver     View source on GitHub    A return type for a serving_input_receiver_fn.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.export.TensorServingInputReceiver
tf.estimator.export.TensorServingInputReceiver(
    features, receiver_tensors, receiver_tensors_alternatives=None
)
 This is for use with models that expect a single Tensor or SparseTensor as an input feature, as opposed to a dict of features. The normal ServingInputReceiver always returns a feature dict, even if it contains only one entry, and so can be used only with models that accept such a dict. For models that accept only a single raw feature, the serving_input_receiver_fn provided to Estimator.export_saved_model() should return this TensorServingInputReceiver instead. See: https://github.com/tensorflow/tensorflow/issues/11674 Note that the receiver_tensors and receiver_tensor_alternatives arguments will be automatically converted to the dict representation in either case, because the SavedModel format requires each input Tensor to have a name (provided by the dict key).

 Attributes
  features   A single Tensor or SparseTensor, representing the feature to be passed to the model.
  receiver_tensors   A Tensor, SparseTensor, or dict of string to Tensor or SparseTensor, specifying input nodes where this receiver expects to be fed by default. Typically, this is a single placeholder expecting serialized tf.Example protos.
  receiver_tensors_alternatives   a dict of string to additional groups of receiver tensors, each of which may be a Tensor, SparseTensor, or dict of string to Tensor orSparseTensor. These named receiver tensor alternatives generate additional serving signatures, which may be used to feed inputs at different points within the input receiver subgraph. A typical usage is to allow feeding raw feature Tensors downstream of the tf.parse_example() op. Defaults to None.


tf.estimator.Exporter     View source on GitHub    A class representing a type of model export.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.Exporter

 Attributes
  name   Directory name. A directory name under the export base directory where exports of this type are written. Should not be None nor empty.
   Methods export View source
@abc.abstractmethod
export(
    estimator, export_path, checkpoint_path, eval_result, is_the_final_export
)
 Exports the given Estimator to a specific format.

 Args
  estimator   the Estimator to export.
  export_path   A string containing a directory where to write the export.
  checkpoint_path   The checkpoint path to export.
  eval_result   The output of Estimator.evaluate on this checkpoint.
  is_the_final_export   This boolean is True when this is an export in the end of training. It is False for the intermediate exports during the training. When passing Exporter to tf.estimator.train_and_evaluate is_the_final_export is always False if TrainSpec.max_steps is None.

 Returns   The string path to the exported directory or None if export is skipped.


tf.estimator.FeedFnHook Runs feed_fn and sets the feed_dict accordingly. Inherits From: SessionRunHook  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.FeedFnHook, tf.compat.v1.train.FeedFnHook
tf.estimator.FeedFnHook(
    feed_fn
)

 Args
  feed_fn   function that takes no arguments and returns dict of Tensor to feed.    Methods after_create_session View source
after_create_session(
    session, coord
)
 Called when new TensorFlow session is created. This is called to signal the hooks that a new session has been created. This has two essential differences with the situation in which begin is called:  When this is called, the graph is finalized and ops can no longer be added to the graph. This method will also be called as a result of recovering a wrapped session, not only at the beginning of the overall session.

 Args
  session   A TensorFlow Session that has been created.
  coord   A Coordinator object which keeps track of all threads.    after_run View source
after_run(
    run_context, run_values
)
 Called after each call to run(). The run_values argument contains results of requested ops/tensors by before_run(). The run_context argument is the same one send to before_run call. run_context.request_stop() can be called to stop the iteration. If session.run() raises any exceptions then after_run() is not called.

 Args
  run_context   A SessionRunContext object.
  run_values   A SessionRunValues object.    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()
 Called once before using the session. When called, the default graph is the one that will be launched in the session. The hook can modify the graph by adding new operations to it. After the begin() call the graph will be finalized and the other callbacks can not modify the graph anymore. Second call of begin() on the same graph, should not change the graph. end View source
end(
    session
)
 Called at the end of session. The session argument can be used in case the hook wants to run final ops, such as saving a last checkpoint. If session.run() raises exception other than OutOfRangeError or StopIteration then end() is not called. Note the difference between end() and after_run() behavior when session.run() raises OutOfRangeError or StopIteration. In that case end() is called but after_run() is not called.

 Args
  session   A TensorFlow Session that will be soon closed.


tf.estimator.FinalExporter     View source on GitHub    This class exports the serving graph and checkpoints at the end. Inherits From: Exporter  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.FinalExporter
tf.estimator.FinalExporter(
    name, serving_input_receiver_fn, assets_extra=None, as_text=False
)
 This class performs a single export at the end of training.

 Args
  name   unique name of this Exporter that is going to be used in the export path.
  serving_input_receiver_fn   a function that takes no arguments and returns a ServingInputReceiver.
  assets_extra   An optional dict specifying how to populate the assets.extra directory within the exported SavedModel. Each key should give the 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'}.
  as_text   whether to write the SavedModel proto in text format. Defaults to False.

 Raises
  ValueError   if any arguments is invalid.

 Attributes
  name   Directory name. A directory name under the export base directory where exports of this type are written. Should not be None nor empty.
   Methods export View source
export(
    estimator, export_path, checkpoint_path, eval_result, is_the_final_export
)
 Exports the given Estimator to a specific format.

 Args
  estimator   the Estimator to export.
  export_path   A string containing a directory where to write the export.
  checkpoint_path   The checkpoint path to export.
  eval_result   The output of Estimator.evaluate on this checkpoint.
  is_the_final_export   This boolean is True when this is an export in the end of training. It is False for the intermediate exports during the training. When passing Exporter to tf.estimator.train_and_evaluate is_the_final_export is always False if TrainSpec.max_steps is None.

 Returns   The string path to the exported directory or None if export is skipped.


tf.estimator.FinalOpsHook A hook which evaluates Tensors at the end of a session. Inherits From: SessionRunHook  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.FinalOpsHook, tf.compat.v1.train.FinalOpsHook
tf.estimator.FinalOpsHook(
    final_ops, final_ops_feed_dict=None
)

 Args
  final_ops   A single Tensor, a list of Tensors or a dictionary of names to Tensors.
  final_ops_feed_dict   A feed dictionary to use when running final_ops_dict.

 Attributes
  final_ops_values
   Methods after_create_session View source
after_create_session(
    session, coord
)
 Called when new TensorFlow session is created. This is called to signal the hooks that a new session has been created. This has two essential differences with the situation in which begin is called:  When this is called, the graph is finalized and ops can no longer be added to the graph. This method will also be called as a result of recovering a wrapped session, not only at the beginning of the overall session.

 Args
  session   A TensorFlow Session that has been created.
  coord   A Coordinator object which keeps track of all threads.    after_run View source
after_run(
    run_context, run_values
)
 Called after each call to run(). The run_values argument contains results of requested ops/tensors by before_run(). The run_context argument is the same one send to before_run call. run_context.request_stop() can be called to stop the iteration. If session.run() raises any exceptions then after_run() is not called.

 Args
  run_context   A SessionRunContext object.
  run_values   A SessionRunValues object.    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()
 Called once before using the session. When called, the default graph is the one that will be launched in the session. The hook can modify the graph by adding new operations to it. After the begin() call the graph will be finalized and the other callbacks can not modify the graph anymore. Second call of begin() on the same graph, should not change the graph. end View source
end(
    session
)
 Called at the end of session. The session argument can be used in case the hook wants to run final ops, such as saving a last checkpoint. If session.run() raises exception other than OutOfRangeError or StopIteration then end() is not called. Note the difference between end() and after_run() behavior when session.run() raises OutOfRangeError or StopIteration. In that case end() is called but after_run() is not called.

 Args
  session   A TensorFlow Session that will be soon closed.


tf.estimator.GlobalStepWaiterHook Delays execution until global step reaches wait_until_step. Inherits From: SessionRunHook  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.GlobalStepWaiterHook, tf.compat.v1.train.GlobalStepWaiterHook
tf.estimator.GlobalStepWaiterHook(
    wait_until_step
)
 This hook delays execution until global step reaches to wait_until_step. It is used to gradually start workers in distributed settings. One example usage would be setting wait_until_step=int(K*log(task_id+1)) assuming that task_id=0 is the chief.

 Args
  wait_until_step   an int shows until which global step should we wait.    Methods after_create_session View source
after_create_session(
    session, coord
)
 Called when new TensorFlow session is created. This is called to signal the hooks that a new session has been created. This has two essential differences with the situation in which begin is called:  When this is called, the graph is finalized and ops can no longer be added to the graph. This method will also be called as a result of recovering a wrapped session, not only at the beginning of the overall session.

 Args
  session   A TensorFlow Session that has been created.
  coord   A Coordinator object which keeps track of all threads.    after_run View source
after_run(
    run_context, run_values
)
 Called after each call to run(). The run_values argument contains results of requested ops/tensors by before_run(). The run_context argument is the same one send to before_run call. run_context.request_stop() can be called to stop the iteration. If session.run() raises any exceptions then after_run() is not called.

 Args
  run_context   A SessionRunContext object.
  run_values   A SessionRunValues object.    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()
 Called once before using the session. When called, the default graph is the one that will be launched in the session. The hook can modify the graph by adding new operations to it. After the begin() call the graph will be finalized and the other callbacks can not modify the graph anymore. Second call of begin() on the same graph, should not change the graph. end View source
end(
    session
)
 Called at the end of session. The session argument can be used in case the hook wants to run final ops, such as saving a last checkpoint. If session.run() raises exception other than OutOfRangeError or StopIteration then end() is not called. Note the difference between end() and after_run() behavior when session.run() raises OutOfRangeError or StopIteration. In that case end() is called but after_run() is not called.

 Args
  session   A TensorFlow Session that will be soon closed.


tf.estimator.Head     View source on GitHub    Interface for the head/top of a model.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.Head  Head sits on top of the model network and handles computing the outputs of the network. Given logits (or output of a hidden layer), a Head knows how to compute predictions, loss, train_op, metrics and export outputs. It is meant to:  Simplify writing model_fn and to make model_fn more configurable for Estimator. Simpilfy creating loss and metrics for the train and test loop in Eager execution. Support wide range of machine learning models. Since most heads can work with logits, they can support DNN, RNN, Wide, Wide&Deep, Global objectives, Gradient boosted trees and many other types of machine learning models.  Common usage: Here is simplified model_fn to build a DNN regression model. def _my_dnn_model_fn(features, labels, mode, params, config=None):
  # Optionally your callers can pass head to model_fn as a param.
  head = tf.estimator.RegressionHead(...)

  feature_columns = tf.feature_column.numeric_column(...)
  feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
  inputs = feature_layer(features)

  # Compute logits with tf.keras.layers API
  hidden_layer0 = tf.keras.layers.Dense(
      units=1000, activation="relu")(inputs)
  hidden_layer1 = tf.keras.layers.Dense(
      units=500, activation="relu")(hidden_layer0)
  logits = tf.keras.layers.Dense(
      units=head.logits_dimension, activation=None)(hidden_layer1)

  # Or use Keras model for logits computation
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Dense(units=1000, activation="relu"))
  model.add(tf.keras.layers.Dense(units=500, activation="relu"))
  model.add(tf.keras.layers.Dense(
     units=head.logits_dimension, activation=None))
  logits = model(inputs)

  return head.create_estimator_spec(
      features=features,
      labels=labels,
      mode=mode,
      logits=logits,
      optimizer=optimizer)

 Attributes
  logits_dimension   Size of the last dimension of the logits Tensor. Often is the number of classes, labels, or real values to be predicted. Typically, logits is of shape [batch_size, logits_dimension].

  loss_reduction   One of tf.losses.Reduction. Describes how to reduce training loss over batch, such as mean or sum.

  name   The name of this head.    Methods create_estimator_spec View source
create_estimator_spec(
    features, mode, logits, labels=None, optimizer=None, trainable_variables=None,
    train_op_fn=None, update_ops=None, regularization_losses=None
)
 Returns EstimatorSpec that a model_fn can return. It is recommended to pass all args via name.

 Args
  features   Input dict mapping string feature names to Tensor or SparseTensor objects containing the values for that feature in a minibatch. Often to be used to fetch example-weight tensor.
  mode   Estimator's ModeKeys.
  logits   Logits Tensor to be used by the head.
  labels   Labels Tensor, or dict mapping string label names to Tensor objects of the label values.
  optimizer   An tf.keras.optimizers.Optimizer instance to optimize the loss in TRAIN mode. Namely, sets train_op = optimizer.get_updates(loss, trainable_variables), which updates variables to minimize loss.
  trainable_variables   A list or tuple of Variable objects to update to minimize loss. In Tensorflow 1.x, by default these are the list of variables collected in the graph under the key GraphKeys.TRAINABLE_VARIABLES. As Tensorflow 2.x doesn't have collections and GraphKeys, trainable_variables need to be passed explicitly here.
  train_op_fn   Function that takes a scalar loss Tensor and returns an op to optimize the model with the loss in TRAIN mode. Used if optimizer is None. Exactly one of train_op_fn and optimizer must be set in TRAIN mode. By default, it is None in other modes. If you want to optimize loss yourself, you can pass lambda _: tf.no_op() and then use EstimatorSpec.loss to compute and apply gradients.
  update_ops   A list or tuple of update ops to be run at training time. For example, layers such as BatchNormalization create mean and variance update ops that need to be run at training time. In Tensorflow 1.x, these are thrown into an UPDATE_OPS collection. As Tensorflow 2.x doesn't have collections, update_ops need to be passed explicitly here.
  regularization_losses   A list of additional scalar losses to be added to the training loss, such as regularization losses.

 Returns   EstimatorSpec.
 loss View source
@abc.abstractmethod
loss(
    labels, logits, features=None, mode=None, regularization_losses=None
)
 Returns a loss Tensor from provided arguments. Note that, the args of features and mode are most likely not used, but some Head implementations may require them.

 Args
  labels   Labels Tensor, or dict mapping string label names to Tensor objects of the label values.
  logits   Logits Tensor to be used for loss construction.
  features   Input dict mapping string feature names to Tensor or SparseTensor objects containing the values for that feature in a minibatch. Often to be used to fetch example-weight tensor.
  mode   Estimator's ModeKeys. To be used in case loss calculation is different in Train and Eval mode.
  regularization_losses   A list of additional scalar losses to be added to the training loss, such as regularization losses.

 Returns   A scalar Tensor representing regularized training loss used in train and eval.
 metrics View source
@abc.abstractmethod
metrics(
    regularization_losses=None
)
 Returns a dict of metric objects.

 Args
  regularization_losses   A list of additional scalar losses to be added to the training loss, such as regularization losses.

 Returns   A dict of metrics keyed by string name. The value is an instance of Metric class.
 predictions View source
@abc.abstractmethod
predictions(
    logits, keys=None
)
 Returns a dict of predictions from provided logits.

 Args
  logits   Logits Tensor to be used for prediction construction.
  keys   A list of string for prediction keys. Defaults to None, meaning if not specified, predictions will be created for all the pre-defined valid keys in the head.

 Returns   A dict of predicted Tensor keyed by prediction name.
 update_metrics View source
@abc.abstractmethod
update_metrics(
    eval_metrics, features, logits, labels, mode=None, regularization_losses=None
)
 Updates metric objects and returns a dict of the updated metrics.

 Args
  eval_metrics   A dict of metrics to be updated.
  features   Input dict mapping string feature names to Tensor or SparseTensor objects containing the values for that feature in a minibatch. Often to be used to fetch example-weight tensor.
  logits   logits Tensor to be used for metrics update.
  labels   Labels Tensor, or dict mapping string label names to Tensor objects of the label values.
  mode   Estimator's ModeKeys. In most cases, this arg is not used and can be removed in the method implementation.
  regularization_losses   A list of additional scalar losses to be added to the training and evaluation loss, such as regularization losses. Note that, the mode arg is not used in the tf.estimator.*Head. If the update of the metrics doesn't rely on mode, it can be safely ignored in the method signature.

 Returns   A dict of updated metrics keyed by name. The value is an instance of Metric class.


tf.estimator.LatestExporter     View source on GitHub    This class regularly exports the serving graph and checkpoints. Inherits From: Exporter  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.estimator.LatestExporter
tf.estimator.LatestExporter(
    name, serving_input_receiver_fn, assets_extra=None, as_text=False,
    exports_to_keep=5
)
 In addition to exporting, this class also garbage collects stale exports.

 Args
  name   unique name of this Exporter that is going to be used in the export path.
  serving_input_receiver_fn   a function that takes no arguments and returns a ServingInputReceiver.
  assets_extra   An optional dict specifying how to populate the assets.extra directory within the exported SavedModel. Each key should give the 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'}.
  as_text   whether to write the SavedModel proto in text format. Defaults to False.
  exports_to_keep   Number of exports to keep. Older exports will be garbage-collected. Defaults to 5. Set to None to disable garbage collection.

 Raises
  ValueError   if any arguments is invalid.

 Attributes
  name   Directory name. A directory name under the export base directory where exports of this type are written. Should not be None nor empty.
   Methods export View source
export(
    estimator, export_path, checkpoint_path, eval_result, is_the_final_export
)
 Exports the given Estimator to a specific format.

 Args
  estimator   the Estimator to export.
  export_path   A string containing a directory where to write the export.
  checkpoint_path   The checkpoint path to export.
  eval_result   The output of Estimator.evaluate on this checkpoint.
  is_the_final_export   This boolean is True when this is an export in the end of training. It is False for the intermediate exports during the training. When passing Exporter to tf.estimator.train_and_evaluate is_the_final_export is always False if TrainSpec.max_steps is None.

 Returns   The string path to the exported directory or None if export is skipped.


tf.estimator.LinearClassifier     View source on GitHub    Linear classifier model. Inherits From: Estimator, Estimator
tf.estimator.LinearClassifier(
    feature_columns, model_dir=None, n_classes=2, weight_column=None,
    label_vocabulary=None, optimizer='Ftrl', config=None,
    warm_start_from=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,
    sparse_combiner='sum'
)
 Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification. Example: categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)

categorical_feature_a_x_categorical_feature_b = crossed_column(...)

# Estimator using the default optimizer.
estimator = tf.estimator.LinearClassifier(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b])

# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearClassifier(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    optimizer=tf.keras.optimizers.Ftrl(
      learning_rate=0.1,
      l1_regularization_strength=0.001
    ))

# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearClassifier(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    optimizer=lambda: tf.keras.optimizers.Ftrl(
        learning_rate=tf.exponential_decay(
            learning_rate=0.1,
            global_step=tf.get_global_step(),
            decay_steps=10000,
            decay_rate=0.96))

# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.LinearClassifier(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    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 SparseColumn, a feature with key=column.name whose value is a SparseTensor. if column is a WeightedSparseColumn, 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 RealValuedColumn, a feature with key=column.name whose value is a Tensor.
  Loss is calculated by using softmax cross entropy.

 Args
  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.
  n_classes   number of label classes. Default is binary classification. Note that class labels are integers representing the class index (i.e. values from 0 to n_classes-1). For arbitrary label values (e.g. string labels), convert to class indices first.
  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.keras.optimizers.* or tf.estimator.experimental.LinearSDCA used to train the model. Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to FTRL optimizer.
  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 and biases 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.
  sparse_combiner   A string specifying how to reduce if a categorical column is multivalent. One of "mean", "sqrtn", and "sum" -- these are effectively different ways to do example-level normalization, which can be useful for bag-of-words features. for more details, see tf.feature_column.linear_model.

 Raises
  ValueError   if n_classes < 2.    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.LinearEstimator     View source on GitHub    An estimator for TensorFlow linear models with user-specified head. Inherits From: Estimator, Estimator
tf.estimator.LinearEstimator(
    head, feature_columns, model_dir=None, optimizer='Ftrl', config=None,
    sparse_combiner='sum', warm_start_from=None
)
 Example: categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)

categorical_feature_a_x_categorical_feature_b = crossed_column(...)

# Estimator using the default optimizer.
estimator = tf.estimator.LinearEstimator(
    head=tf.estimator.MultiLabelHead(n_classes=3),
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b])

# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearEstimator(
    head=tf.estimator.MultiLabelHead(n_classes=3),
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    optimizer=lambda: tf.keras.optimizers.Ftrl(
        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 using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearEstimator(
    head=tf.estimator.MultiLabelHead(n_classes=3),
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b])
    optimizer=tf.keras.optimizers.Ftrl(
        learning_rate=0.1,
        l1_regularization_strength=0.001
    ))

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, steps=100)
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
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 and predicted output are determined by the specified head.

 Args
  head   A Head instance constructed with a method such as tf.estimator.MultiLabelHead.
  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.
  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 FTRL optimizer.
  config   RunConfig object to configure the runtime settings.
  sparse_combiner   A string specifying how to reduce if a categorical column is multivalent. One of "mean", "sqrtn", and "sum" -- these are effectively different ways to do example-level normalization, which can be useful for bag-of-words features. for more details, see tf.feature_column.linear_model.
  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 and biases are warm-started, and it is assumed that vocabularies and Tensor names are unchanged.    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.LinearRegressor     View source on GitHub    An estimator for TensorFlow Linear regression problems. Inherits From: Estimator, Estimator
tf.estimator.LinearRegressor(
    feature_columns, model_dir=None, label_dimension=1, weight_column=None,
    optimizer='Ftrl', config=None, warm_start_from=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,
    sparse_combiner='sum'
)
 Train a linear regression model to predict label value given observation of feature values. Example: categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)

categorical_feature_a_x_categorical_feature_b = crossed_column(...)

# Estimator using the default optimizer.
estimator = tf.estimator.LinearRegressor(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b])

# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearRegressor(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    optimizer=tf.keras.optimizers.Ftrl(
      learning_rate=0.1,
      l1_regularization_strength=0.001
    ))

# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearRegressor(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    optimizer=lambda: tf.keras.optimizers.Ftrl(
        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.LinearRegressor(
    feature_columns=[categorical_column_a,
                     categorical_feature_a_x_categorical_feature_b],
    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 SparseColumn, a feature with key=column.name whose value is a SparseTensor. if column is a WeightedSparseColumn, 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 RealValuedColumn, a feature with key=column.name whose value is a Tensor.
  Loss is calculated by using mean squared error.

 Args
  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.* or tf.estimator.experimental.LinearSDCA used to train the model. Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to FTRL optimizer.
  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 and biases 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.
  sparse_combiner   A string specifying how to reduce if a categorical column is multivalent. One of "mean", "sqrtn", and "sum" -- these are effectively different ways to do example-level normalization, which can be useful for bag-of-words features. for more details, see tf.feature_column.linear_model.    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.