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 the input_fn passed to train, 'evaluate, andpredict. This should be a singleTensorordict` of same.

    • labels: This is the second item returned from the input_fn passed to train, 'evaluate, andpredict. This should be a singleTensorordictof same (for multi-head models). If mode isModeKeys.PREDICT,labels=Nonewill be passed. If themodel_fn's signature does not acceptmode, themodel_fnmust still be able to handlelabels=None`.
    • mode: Optional. Specifies if this training, evaluation or prediction. See ModeKeys.
    • params: Optional dict of hyperparameters. Will receive what is passed to Estimator in params parameter. This allows to configure Estimators from hyper parameter tuning.
    • config: Optional configuration object. Will receive what is passed to Estimator in config parameter, or the default config. Allows updating things in your model_fn based on configuration such as num_ps_replicas, or model_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. If None, the model_dir in config will be used if set. If both are set, they must be same. If both are None, a temporary directory will be used.

  • config: Configuration object.
  • params: dict of hyper parameters that will be passed into model_fn. Keys are names of parameters, values are basic python types.

Raises:

  • ValueError: parameters of model_fn don't match params.
  • ValueError: if this is called via a subclass and if that class overrides a member of Estimator.

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 to Tensor or SparseTensor. labels - Tensor or dictionary of Tensor with labels.
  • steps: Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
  • hooks: List of 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.
  • 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: If steps <= 0.
  • ValueError: If no model has been trained, namely model_dir, or the given checkpoint_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 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 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 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 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 a ServingInputReceiver.
  • 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 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 to Tensor or SparseTensor. If it returns a tuple, first item is extracted as features. Prediction continues until input_fn raises an end-of-input exception (OutOfRangeError or StopIteration).
  • predict_keys: list of str, name of the keys to predict. It is used if the 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 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.

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 between predict_keys and predictions. For example if predict_keys is not None but EstimatorSpec.predictions is not a dict.

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 to Tensor. labels - Tensor or dictionary of Tensor with labels.
  • hooks: List of SessionRunHook subclass instances. Used for callbacks inside the training loop.
  • steps: Number of steps for which to train model. If None, train forever or train until input_fn generates the OutOfRange or StopIteration error. 'steps' works incrementally. If you call two times train(steps=10) then training occurs in total 20 steps. If OutOfRange or StopIteration error occurs in the middle, training stops before 20 steps. If you don't want to have incremental behaviour 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 OutOfRange or StopIteration error. If set, steps must be None. If OutOfRange or StopIteration error 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.

Returns:

self, for chaining.

Raises:

  • ValueError: If both steps and max_steps are not None.
  • ValueError: If either steps or max_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

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部