tf.estimator.Estimator
tf.estimator.Estimator
class tf.estimator.Estimator
Defined in tensorflow/python/estimator/estimator.py
.
Estimator class to train and evaluate TensorFlow models.
The Estimator
object wraps a model which is specified by a model_fn
, which, given inputs and a number of other parameters, returns the ops necessary to perform training, evaluation, or predictions.
All outputs (checkpoints, event files, etc.) are written to model_dir
, or a subdirectory thereof. If model_dir
is not set, a temporary directory is used.
The config
argument can be passed RunConfig
object containing information about the execution environment. It is passed on to the model_fn
, if the model_fn
has a parameter named "config" (and input functions in the same manner). If the config
parameter is not passed, it is instantiated by the Estimator
. Not passing config means that defaults useful for local execution are used. Estimator
makes config available to the model (for instance, to allow specialization based on the number of workers available), and also uses some of its fields to control internals, especially regarding checkpointing.
The params
argument contains hyperparameters. It is passed to the model_fn
, if the model_fn
has a parameter named "params", and to the input functions in the same manner. Estimator
only passes params along, it does not inspect it. The structure of params
is therefore entirely up to the developer.
None of Estimator
's methods can be overridden in subclasses (its constructor enforces this). Subclasses should use model_fn
to configure the base class, and may add methods implementing specialized functionality.
Properties
config
model_dir
params
Methods
__init__
__init__( model_fn, model_dir=None, config=None, params=None )
Constructs an Estimator
instance.
Args:
-
model_fn
: Model function. Follows the signature:-
Args:
-
features
: This is the first item returned from theinput_fn
passed totrain
, 'evaluate, and
predict. This should be a single
Tensoror
dict` of same. -
labels
: This is the second item returned from theinput_fn
passed totrain
, 'evaluate, and
predict. This should be a single
Tensoror
dictof same (for multi-head models). If mode is
ModeKeys.PREDICT,
labels=Nonewill be passed. If the
model_fn's signature does not accept
mode, the
model_fnmust still be able to handle
labels=None`. -
mode
: Optional. Specifies if this training, evaluation or prediction. SeeModeKeys
. -
params
: Optionaldict
of hyperparameters. Will receive what is passed to Estimator inparams
parameter. This allows to configure Estimators from hyper parameter tuning. -
config
: Optional configuration object. Will receive what is passed to Estimator inconfig
parameter, or the defaultconfig
. Allows updating things in your model_fn based on configuration such asnum_ps_replicas
, ormodel_dir
. -
Returns:
EstimatorSpec
-
-
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. IfNone
, the model_dir inconfig
will be used if set. If both are set, they must be same. If both areNone
, a temporary directory will be used. -
config
: Configuration object. -
params
:dict
of hyper parameters that will be passed intomodel_fn
. Keys are names of parameters, values are basic python types.
Raises:
-
ValueError
: parameters ofmodel_fn
don't matchparams
. -
ValueError
: if this is called via a subclass and if that class overrides a member ofEstimator
.
evaluate
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 (OutOfRangeError
or StopIteration
).
Args:
-
input_fn
: Input function returning a tuple of: features - Dictionary of string feature name toTensor
orSparseTensor
. labels -Tensor
or dictionary ofTensor
with labels. -
steps
: Number of steps for which to evaluate model. IfNone
, evaluates untilinput_fn
raises an end-of-input exception. -
hooks
: List ofSessionRunHook
subclass instances. Used for callbacks inside the evaluation call. -
checkpoint_path
: Path of a specific checkpoint to evaluate. IfNone
, the latest checkpoint inmodel_dir
is used. -
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.
Raises:
-
ValueError
: Ifsteps <= 0
. -
ValueError
: If no model has been trained, namelymodel_dir
, or the givencheckpoint_path
is empty.
export_savedmodel
export_savedmodel( export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None )
Exports inference graph as a SavedModel into given dir.
This method builds a new graph by first calling the serving_input_receiver_fn to obtain feature Tensor
s, 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 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 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 ExportOutput
s, 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 extra_assets argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as {'my_asset_file.txt': '/path/to/my_asset_file.txt'}
.
Args:
-
export_dir_base
: A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. -
serving_input_receiver_fn
: A function that takes no argument and returns aServingInputReceiver
. -
assets_extra
: A dict specifying how to populate the assets.extra directory within the exported SavedModel, orNone
if no extra assets are needed. -
as_text
: whether to write the SavedModel proto in text format. -
checkpoint_path
: The checkpoint path to export. IfNone
(the default), the most recent checkpoint found within the model directory is chosen.
Returns:
The string path to the exported directory.
Raises:
-
ValueError
: if no serving_input_receiver_fn is provided, no export_outputs are provided, or no checkpoint can be found.
predict
predict( input_fn, predict_keys=None, hooks=None, checkpoint_path=None )
Returns predictions for given features.
Args:
-
input_fn
: Input function returning features which is a dictionary of string feature name toTensor
orSparseTensor
. If it returns a tuple, first item is extracted as features. Prediction continues untilinput_fn
raises an end-of-input exception (OutOfRangeError
orStopIteration
). -
predict_keys
: list ofstr
, name of the keys to predict. It is used if theEstimatorSpec.predictions
is adict
. Ifpredict_keys
is used then rest of the predictions will be filtered from the dictionary. IfNone
, returns all. -
hooks
: List ofSessionRunHook
subclass instances. Used for callbacks inside the prediction call. -
checkpoint_path
: Path of a specific checkpoint to predict. IfNone
, the latest checkpoint inmodel_dir
is used.
Yields:
Evaluated values of predictions
tensors.
Raises:
-
ValueError
: Could not find a trained model in model_dir. -
ValueError
: if batch length of predictions are not same. -
ValueError
: If there is a conflict betweenpredict_keys
andpredictions
. For example ifpredict_keys
is notNone
butEstimatorSpec.predictions
is not adict
.
train
train( input_fn, hooks=None, steps=None, max_steps=None )
Trains a model given training data input_fn.
Args:
-
input_fn
: Input function returning a tuple of: features -Tensor
or dictionary of string feature name toTensor
. labels -Tensor
or dictionary ofTensor
with labels. -
hooks
: List ofSessionRunHook
subclass instances. Used for callbacks inside the training loop. -
steps
: Number of steps for which to train model. IfNone
, train forever or train until input_fn generates theOutOfRange
orStopIteration
error. 'steps' works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. IfOutOfRange
orStopIteration
error occurs in the middle, training stops before 20 steps. If you don't want to have incremental behaviour please setmax_steps
instead. If set,max_steps
must beNone
. -
max_steps
: Number of total steps for which to train model. IfNone
, train forever or train until input_fn generates theOutOfRange
orStopIteration
error. If set,steps
must beNone
. IfOutOfRange
orStopIteration
error occurs in the middle, training stops beforemax_steps
steps.Two calls to
train(steps=100)
means 200 training iterations. On the other hand, two calls totrain(max_steps=100)
means that the second call will not do any iteration since first call did all 100 steps.
Returns:
self
, for chaining.
Raises:
-
ValueError
: If bothsteps
andmax_steps
are notNone
. -
ValueError
: If eithersteps
ormax_steps
is <= 0.
© 2017 The TensorFlow Authors. All rights reserved.
Licensed under the Creative Commons Attribution License 3.0.
Code samples licensed under the Apache 2.0 License.
https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator