Tensorflow Training

Training

[TOC]

This library provides a set of classes and functions that helps train models.

Optimizers

The Optimizer base class provides methods to compute gradients for a loss and apply gradients to variables. A collection of subclasses implement classic optimization algorithms such as GradientDescent and Adagrad.

You never instantiate the Optimizer class itself, but instead instantiate one of the subclasses.


class tf.train.Optimizer {#Optimizer}

Base class for optimizers.

This class defines the API to add Ops to train a model. You never use this class directly, but instead instantiate one of its subclasses such asGradientDescentOptimizerAdagradOptimizer, or MomentumOptimizer.

Usage

```python

Create an optimizer with the desired parameters.

opt = GradientDescentOptimizer(learning_rate=0.1)

Add Ops to the graph to minimize a cost by updating a list of variables.

"cost" is a Tensor, and the list of variables contains tf.Variable

objects.

optop = opt.minimize(cost, varlist=) ```

In the training program you will just have to run the returned Op.

```python

Execute opt_op to do one step of training:

opt_op.run() ```

Processing gradients before applying them.

Calling minimize() takes care of both computing the gradients and applying them to the variables. If you want to process the gradients before applying them you can instead use the optimizer in three steps:

  1. Compute the gradients with compute_gradients().
  2. Process the gradients as you wish.
  3. Apply the processed gradients with apply_gradients().

Example:

```python

Create an optimizer.

opt = GradientDescentOptimizer(learning_rate=0.1)

Compute the gradients for a list of variables.

gradsandvars = opt.compute_gradients(loss, )

gradsandvars is a list of tuples (gradient, variable). Do whatever you

need to the 'gradient' part, for example cap them, etc.

cappedgradsand_vars = [(MyCapper(gv[0]), gv[1]) for gv in gradsandvars]

Ask the optimizer to apply the capped gradients.

opt.applygradients(cappedgradsandvars) ```


tf.train.Optimizer.__init__(use_locking, name) {#Optimizer.init}

Create a new Optimizer.

This must be called by the constructors of subclasses.

Args:
  • use_locking: Bool. If True apply use locks to prevent concurrent updates to variables.
  • name: A non-empty string. The name to use for accumulators created for the optimizer.
Raises:
  • ValueError: If name is malformed.

tf.train.Optimizer.minimize(loss, global_step=None, var_list=None, gate_gradients=1, aggregation_method=None, colocate_gradients_with_ops=False, name=None, grad_loss=None){#Optimizer.minimize}

Add operations to minimize loss by updating var_list.

This method simply combines calls compute_gradients() and apply_gradients(). If you want to process the gradient before applying them callcompute_gradients() and apply_gradients() explicitly instead of using this function.

Args:
  • loss: A Tensor containing the value to minimize.
  • global_step: Optional Variable to increment by one after the variables have been updated.
  • var_list: Optional list of Variable objects to update to minimize loss. Defaults to the list of variables collected in the graph under the keyGraphKeys.TRAINABLE_VARIABLES.
  • gate_gradients: How to gate the computation of gradients. Can be GATE_NONEGATE_OP, or GATE_GRAPH.
  • aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod.
  • colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op.
  • name: Optional name for the returned operation.
  • grad_loss: Optional. A Tensor holding the gradient computed for loss.
Returns:

An Operation that updates the variables in var_list. If global_step was not None, that operation also increments global_step.

Raises:
  • ValueError: If some of the variables are not Variable objects.

tf.train.Optimizer.compute_gradients(loss, var_list=None, gate_gradients=1, aggregation_method=None, colocate_gradients_with_ops=False, grad_loss=None){#Optimizer.compute_gradients}

Compute gradients of loss for the variables in var_list.

This is the first part of minimize(). It returns a list of (gradient, variable) pairs where "gradient" is the gradient for "variable". Note that "gradient" can be a Tensor, an IndexedSlices, or None if there is no gradient for the given variable.

Args:
  • loss: A Tensor containing the value to minimize.
  • var_list: Optional list of tf.Variable to update to minimize loss. Defaults to the list of variables collected in the graph under the keyGraphKey.TRAINABLE_VARIABLES.
  • gate_gradients: How to gate the computation of gradients. Can be GATE_NONEGATE_OP, or GATE_GRAPH.
  • aggregation_method: Specifies the method used to combine gradient terms. Valid values are defined in the class AggregationMethod.
  • colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op.
  • grad_loss: Optional. A Tensor holding the gradient computed for loss.
Returns:

A list of (gradient, variable) pairs. Variable is always present, but gradient can be None.

Raises:
  • TypeError: If var_list contains anything else than Variable objects.
  • ValueError: If some arguments are invalid.

tf.train.Optimizer.apply_gradients(grads_and_vars, global_step=None, name=None) {#Optimizer.apply_gradients}

Apply gradients to variables.

This is the second part of minimize(). It returns an Operation that applies gradients.

Args:
  • grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients().
  • global_step: Optional Variable to increment by one after the variables have been updated.
  • name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor.
Returns:

An Operation that applies the specified gradients. If global_step was not None, that operation also increments global_step.

Raises:
  • TypeError: If grads_and_vars is malformed.
  • ValueError: If none of the variables have gradients.

Gating Gradients

Both minimize() and compute_gradients() accept a gate_gradients argument that controls the degree of parallelism during the application of the gradients.

The possible values are: GATE_NONEGATE_OP, and GATE_GRAPH.

GATE_NONE: Compute and apply gradients in parallel. This provides the maximum parallelism in execution, at the cost of some non-reproducibility in the results. For example the two gradients of matmul depend on the input values: With GATE_NONE one of the gradients could be applied to one of the inputsbefore the other gradient is computed resulting in non-reproducible results.

GATE_OP: For each Op, make sure all gradients are computed before they are used. This prevents race conditions for Ops that generate gradients for multiple inputs where the gradients depend on the inputs.

GATE_GRAPH: Make sure all gradients for all variables are computed before any one of them is used. This provides the least parallelism but can be useful if you want to process all gradients before applying any of them.

Slots

Some optimizer subclasses, such as MomentumOptimizer and AdagradOptimizer allocate and manage additional variables associated with the variables to train. These are called Slots. Slots have names and you can ask the optimizer for the names of the slots that it uses. Once you have a slot name you can ask the optimizer for the variable it created to hold the slot value.

This can be useful if you want to log debug a training algorithm, report stats about the slots, etc.


tf.train.Optimizer.get_slot_names() {#Optimizer.getslotnames}

Return a list of the names of slots created by the Optimizer.

See get_slot().

Returns:

A list of strings.


tf.train.Optimizer.get_slot(var, name) {#Optimizer.get_slot}

Return a slot named name created for var by the Optimizer.

Some Optimizer subclasses use additional variables. For example Momentum and Adagrad use variables to accumulate updates. This method gives access to these Variable objects if for some reason you need them.

Use get_slot_names() to get the list of slot names created by the Optimizer.

Args:
  • var: A variable passed to minimize() or apply_gradients().
  • name: A string.
Returns:

The Variable for the slot if it was created, None otherwise.

Other Methods


tf.train.Optimizer.get_name() {#Optimizer.get_name}


class tf.train.GradientDescentOptimizer {#GradientDescentOptimizer}

Optimizer that implements the gradient descent algorithm.


tf.train.GradientDescentOptimizer.__init__(learning_rate, use_locking=False, name='GradientDescent'){#GradientDescentOptimizer.init}

Construct a new gradient descent optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate to use.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "GradientDescent".

class tf.train.AdadeltaOptimizer {#AdadeltaOptimizer}

Optimizer that implements the Adadelta algorithm.

See M. D. Zeiler (pdf)


tf.train.AdadeltaOptimizer.__init__(learning_rate=0.001, rho=0.95, epsilon=1e-08, use_locking=False, name='Adadelta'){#AdadeltaOptimizer.init}

Construct a new Adadelta optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • rho: A Tensor or a floating point value. The decay rate.
  • epsilon: A Tensor or a floating point value. A constant epsilon used to better conditioning the grad update.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "Adadelta".

class tf.train.AdagradOptimizer {#AdagradOptimizer}

Optimizer that implements the Adagrad algorithm.

See this paper.


tf.train.AdagradOptimizer.__init__(learning_rate, initial_accumulator_value=0.1, use_locking=False, name='Adagrad'){#AdagradOptimizer.init}

Construct a new Adagrad optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • initial_accumulator_value: A floating point value. Starting value for the accumulators, must be positive.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "Adagrad".
Raises:
  • ValueError: If the initial_accumulator_value is invalid.

class tf.train.AdagradDAOptimizer {#AdagradDAOptimizer}

Adagrad Dual Averaging algorithm for sparse linear models.

See this paper.

This optimizer takes care of regularization of unseen features in a mini batch by updating them when they are seen with a closed form update rule that is equivalent to having updated them on every mini-batch.

AdagradDA is typically used when there is a need for large sparsity in the trained model. This optimizer only guarantees sparsity for linear models. Be careful when using AdagradDA for deep networks as it will require careful initialization of the gradient accumulators for it to train.


tf.train.AdagradDAOptimizer.__init__(learning_rate, global_step, initial_gradient_squared_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='AdagradDA'){#AdagradDAOptimizer.init}

Construct a new AdagradDA optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • global_step: A Tensor containing the current training step number.
  • initial_gradient_squared_accumulator_value: A floating point value. Starting value for the accumulators, must be positive.
  • l1_regularization_strength: A float value, must be greater than or equal to zero.
  • l2_regularization_strength: A float value, must be greater than or equal to zero.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "AdagradDA".
Raises:
  • ValueError: If the initial_gradient_squared_accumulator_value is invalid.

class tf.train.MomentumOptimizer {#MomentumOptimizer}

Optimizer that implements the Momentum algorithm.


tf.train.MomentumOptimizer.__init__(learning_rate, momentum, use_locking=False, name='Momentum', use_nesterov=False){#MomentumOptimizer.init}

Construct a new Momentum optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • momentum: A Tensor or a floating point value. The momentum.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "Momentum".

class tf.train.AdamOptimizer {#AdamOptimizer}

Optimizer that implements the Adam algorithm.

See Kingma et. al., 2014 (pdf).


tf.train.AdamOptimizer.__init__(learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-08, use_locking=False, name='Adam'){#AdamOptimizer.init}

Construct a new Adam optimizer.

Initialization:

m_0 <- 0 (Initialize initial 1st moment vector) v_0 <- 0 (Initialize initial 2nd moment vector) t <- 0 (Initialize timestep)

The update rule for variable with gradient g uses an optimization described at the end of section2 of the paper:

``` t <- t + 1 lrt <- learningrate * sqrt(1 - beta2^t) / (1 - beta1^t)

mt <- beta1 * m{t-1} + (1 - beta1) * g vt <- beta2 * v{t-1} + (1 - beta2) * g * g variable <- variable - lrt * mt / (sqrt(v_t) + epsilon) ```

The default value of 1e-8 for epsilon might not be a good default in general. For example, when training an Inception network on ImageNet a current good choice is 1.0 or 0.1.

Note that in dense implement of this algorithm, mt, vt and variable will update even if g is zero, but in sparse implement, mt, vt and variable will not update in iterations g is zero.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • beta1: A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates.
  • beta2: A float value or a constant float tensor. The exponential decay rate for the 2nd moment estimates.
  • epsilon: A small constant for numerical stability.
  • use_locking: If True use locks for update operations.
  • name: Optional name for the operations created when applying gradients. Defaults to "Adam".

class tf.train.FtrlOptimizer {#FtrlOptimizer}

Optimizer that implements the FTRL algorithm.

See this paper.


tf.train.FtrlOptimizer.__init__(learning_rate, learning_rate_power=-0.5, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='Ftrl'){#FtrlOptimizer.init}

Construct a new FTRL optimizer.

Args:
  • learning_rate: A float value or a constant float Tensor.
  • learning_rate_power: A float value, must be less or equal to zero.
  • initial_accumulator_value: The starting value for accumulators. Only positive values are allowed.
  • l1_regularization_strength: A float value, must be greater than or equal to zero.
  • l2_regularization_strength: A float value, must be greater than or equal to zero.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "Ftrl".
Raises:
  • ValueError: If one of the arguments is invalid.

class tf.train.ProximalGradientDescentOptimizer {#ProximalGradientDescentOptimizer}

Optimizer that implements the proximal gradient descent algorithm.

See this paper.


tf.train.ProximalGradientDescentOptimizer.__init__(learning_rate, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='ProximalGradientDescent'){#ProximalGradientDescentOptimizer.init}

Construct a new proximal gradient descent optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate to use.
  • l1_regularization_strength: A float value, must be greater than or equal to zero.
  • l2_regularization_strength: A float value, must be greater than or equal to zero.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "GradientDescent".

class tf.train.ProximalAdagradOptimizer {#ProximalAdagradOptimizer}

Optimizer that implements the Proximal Adagrad algorithm.

See this paper.


tf.train.ProximalAdagradOptimizer.__init__(learning_rate, initial_accumulator_value=0.1, l1_regularization_strength=0.0, l2_regularization_strength=0.0, use_locking=False, name='ProximalAdagrad'){#ProximalAdagradOptimizer.init}

Construct a new ProximalAdagrad optimizer.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • initial_accumulator_value: A floating point value. Starting value for the accumulators, must be positive.
  • l1_regularization_strength: A float value, must be greater than or equal to zero.
  • l2_regularization_strength: A float value, must be greater than or equal to zero.
  • use_locking: If True use locks for update operations.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "Adagrad".
Raises:
  • ValueError: If the initial_accumulator_value is invalid.

class tf.train.RMSPropOptimizer {#RMSPropOptimizer}

Optimizer that implements the RMSProp algorithm.

See the paper.


tf.train.RMSPropOptimizer.__init__(learning_rate, decay=0.9, momentum=0.0, epsilon=1e-10, use_locking=False, centered=False, name='RMSProp'){#RMSPropOptimizer.init}

Construct a new RMSProp optimizer.

Note that in dense implement of this algorithm, mt and vt will update even if g is zero, but in sparse implement, mt and vt will not update in iterations g is zero.

Args:
  • learning_rate: A Tensor or a floating point value. The learning rate.
  • decay: Discounting factor for the history/coming gradient
  • momentum: A scalar tensor.
  • epsilon: Small value to avoid zero denominator.
  • use_locking: If True use locks for update operation.
  • centered: If True, gradients are normalized by the estimated variance of the gradient; if False, by the uncentered second moment. Setting this to True may help with training, but is slightly more expensive in terms of computation and memory. Defaults to False.
  • name: Optional name prefix for the operations created when applying gradients. Defaults to "RMSProp".

Gradient Computation

TensorFlow provides functions to compute the derivatives for a given TensorFlow computation graph, adding operations to the graph. The optimizer classes automatically compute derivatives on your graph, but creators of new Optimizers or expert users can call the lower-level functions below.


tf.gradients(ys, xs, grad_ys=None, name='gradients', colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None){#gradients}

Constructs symbolic partial derivatives of sum of ys w.r.t. x in xs.

ys and xs are each a Tensor or a list of tensors. grad_ys is a list of Tensor, holding the gradients received by the ys. The list must be the same length as ys.

gradients() adds ops to the graph to output the partial derivatives of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the sum(dy/dx) for y in ys.

grad_ys is a list of tensors of the same length as ys that holds the initial gradients for each y in ys. When grad_ys is None, we fill in a tensor of '1's of the shape of y for each y in ys. A user can provide their own initial grad_ys to compute the derivatives using a different initial gradient for each y (e.g., if one wanted to weight the gradient differently for each value in each y).

Args:
  • ys: A Tensor or list of tensors to be differentiated.
  • xs: A Tensor or list of tensors to be used for differentiation.
  • grad_ys: Optional. A Tensor or list of tensors the same size as ys and holding the gradients computed for each y in ys.
  • name: Optional name to use for grouping all the gradient ops together. defaults to 'gradients'.
  • colocate_gradients_with_ops: If True, try colocating gradients with the corresponding op.
  • gate_gradients: If True, add a tuple around the gradients returned for an operations. This avoids some race conditions.
  • aggregation_method: Specifies the method used to combine gradient terms. Accepted values are constants defined in the class AggregationMethod.
Returns:

A list of sum(dy/dx) for each x in xs.

Raises:
  • LookupError: if one of the operations between x and y does not have a registered gradient function.
  • ValueError: if the arguments are invalid.

class tf.AggregationMethod {#AggregationMethod}

A class listing aggregation methods used to combine gradients.

Computing partial derivatives can require aggregating gradient contributions. This class lists the various methods that can be used to combine gradients in the graph:

  • ADD_N: All of the gradient terms are summed as part of one operation using the "AddN" op. It has the property that all gradients must be ready before any aggregation is performed.
  • DEFAULT: The system-chosen default aggregation method.

tf.stop_gradient(input, name=None) {#stop_gradient}

Stops gradient computation.

When executed in a graph, this op outputs its input tensor as-is.

When building ops to compute gradients, this op prevents the contribution of its inputs to be taken into account. Normally, the gradient generator adds ops to a graph to compute the derivatives of a specified 'loss' by recursively finding out inputs that contributed to its computation. If you insert this op in the graph it inputs are masked from the gradient generator. They are not taken into account for computing gradients.

This is useful any time you want to compute a value with TensorFlow but need to pretend that the value was a constant. Some examples include:

  • The EM algorithm where the M-step should not involve backpropagation through the output of the E-step.
  • Contrastive divergence training of Boltzmann machines where, when differentiating the energy function, the training must not backpropagate through the graph that generated the samples from the model.
  • Adversarial training, where no backprop should happen through the adversarial example generation process.
Args:
  • input: A Tensor.
  • name: A name for the operation (optional).
Returns:

Tensor. Has the same type as input.


tf.hessians(ys, xs, name='hessians', colocate_gradients_with_ops=False, gate_gradients=False, aggregation_method=None){#hessians}

Constructs the Hessian of sum of ys with respect to x in xs.

hessians() adds ops to the graph to output the Hessian matrix of ys with respect to xs. It returns a list of Tensor of length len(xs) where each tensor is the Hessian of sum(ys). This function currently only supports evaluating the Hessian with respect to (a list of) one- dimensional tensors.

The Hessian is a matrix of second-order partial derivatives of a scalar tensor (see https://en.wikipedia.org/wiki/Hessian_matrix for more details).

Args:
  • ys: A Tensor or list of tensors to be differentiated.
  • xs: A Tensor or list of tensors to be used for differentiation.
  • name: Optional name to use for grouping all the gradient ops together. defaults to 'hessians'.
  • colocate_gradients_with_ops: See gradients() documentation for details.
  • gate_gradients: See gradients() documentation for details.
  • aggregation_method: See gradients() documentation for details.
Returns:

A list of Hessian matrices of sum(y) for each x in xs.

Raises:
  • LookupError: if one of the operations between xs and ys does not have a registered gradient function.
  • ValueError: if the arguments are invalid or not supported. Currently, this function only supports one-dimensional x in xs.

Gradient Clipping

TensorFlow provides several operations that you can use to add clipping functions to your graph. You can use these functions to perform general data clipping, but they're particularly useful for handling exploding or vanishing gradients.


tf.clip_by_value(t, clip_value_min, clip_value_max, name=None) {#clipbyvalue}

Clips tensor values to a specified min and max.

Given a tensor t, this operation returns a tensor of the same type and shape as t with its values clipped to clip_value_min and clip_value_max. Any values less than clip_value_min are set to clip_value_min. Any values greater than clip_value_max are set to clip_value_max.

Args:
  • t: A Tensor.
  • clip_value_min: A 0-D (scalar) Tensor. The minimum value to clip by.
  • clip_value_max: A 0-D (scalar) Tensor. The maximum value to clip by.
  • name: A name for the operation (optional).
Returns:

A clipped Tensor.


tf.clip_by_norm(t, clip_norm, axes=None, name=None) {#clipbynorm}

Clips tensor values to a maximum L2-norm.

Given a tensor t, and a maximum clip value clip_norm, this operation normalizes t so that its L2-norm is less than or equal to clip_norm, along the dimensions given in axes. Specifically, in the default case where all dimensions are used for calculation, if the L2-norm of t is already less than or equal to clip_norm, then t is not modified. If the L2-norm is greater than clip_norm, then this operation returns a tensor of the same type and shape as t with its values set to:

t * clip_norm / l2norm(t)

In this case, the L2-norm of the output tensor is clip_norm.

As another example, if t is a matrix and axes == [1], then each row of the output will have L2-norm equal to clip_norm. If axes == [0] instead, each column of the output will be clipped.

This operation is typically used to clip gradients before applying them with an optimizer.

Args:
  • t: A Tensor.
  • clip_norm: A 0-D (scalar) Tensor > 0. A maximum clipping value.
  • axes: A 1-D (vector) Tensor of type int32 containing the dimensions to use for computing the L2-norm. If None (the default), uses all dimensions.
  • name: A name for the operation (optional).
Returns:

A clipped Tensor.


tf.clip_by_average_norm(t, clip_norm, name=None) {#clipbyaverage_norm}

Clips tensor values to a maximum average L2-norm.

Given a tensor t, and a maximum clip value clip_norm, this operation normalizes t so that its average L2-norm is less than or equal to clip_norm. Specifically, if the average L2-norm is already less than or equal to clip_norm, then t is not modified. If the average L2-norm is greater than clip_norm, then this operation returns a tensor of the same type and shape as t with its values set to:

t * clip_norm / l2norm_avg(t)

In this case, the average L2-norm of the output tensor is clip_norm.

This operation is typically used to clip gradients before applying them with an optimizer.

Args:
  • t: A Tensor.
  • clip_norm: A 0-D (scalar) Tensor > 0. A maximum clipping value.
  • name: A name for the operation (optional).
Returns:

A clipped Tensor.


tf.clip_by_global_norm(t_list, clip_norm, use_norm=None, name=None) {#clipbyglobal_norm}

Clips values of multiple tensors by the ratio of the sum of their norms.

Given a tuple or list of tensors t_list, and a clipping ratio clip_norm, this operation returns a list of clipped tensors list_clipped and the global norm (global_norm) of all tensors in t_list. Optionally, if you've already computed the global norm for t_list, you can specify the global norm with use_norm.

To perform the clipping, the values t_list[i] are set to:

t_list[i] * clip_norm / max(global_norm, clip_norm)

where:

global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))

If clip_norm > global_norm then the entries in t_list remain as they are, otherwise they're all shrunk by the global ratio.

Any of the entries of t_list that are of type None are ignored.

This is the correct way to perform gradient clipping (for example, see Pascanu et al., 2012 (pdf)).

However, it is slower than clip_by_norm() because all the parameters must be ready before the clipping operation can be performed.

Args:
  • t_list: A tuple or list of mixed TensorsIndexedSlices, or None.
  • clip_norm: A 0-D (scalar) Tensor > 0. The clipping ratio.
  • use_norm: A 0-D (scalar) Tensor of type float (optional). The global norm to use. If not provided, global_norm() is used to compute the norm.
  • name: A name for the operation (optional).
Returns:
  • list_clipped: A list of Tensors of the same type as list_t.
  • global_norm: A 0-D (scalar) Tensor representing the global norm.
Raises:
  • TypeError: If t_list is not a sequence.

tf.global_norm(t_list, name=None) {#global_norm}

Computes the global norm of multiple tensors.

Given a tuple or list of tensors t_list, this operation returns the global norm of the elements in all tensors in t_list. The global norm is computed as:

global_norm = sqrt(sum([l2norm(t)**2 for t in t_list]))

Any entries in t_list that are of type None are ignored.

Args:
  • t_list: A tuple or list of mixed TensorsIndexedSlices, or None.
  • name: A name for the operation (optional).
Returns:

A 0-D (scalar) Tensor of type float.

Raises:
  • TypeError: If t_list is not a sequence.

Decaying the learning rate


tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None){#exponential_decay}

Applies exponential decay to the learning rate.

When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies an exponential decay function to a provided initial learning rate. It requires a global_step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.

The function returns the decayed learning rate. It is computed as:

python decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)

If the argument staircase is True, then global_step / decay_steps is an integer division and the decayed learning rate follows a staircase function.

Example: decay every 100000 steps with a base of 0.96:

```python ... globalstep = tf.Variable(0, trainable=False) starterlearningrate = 0.1 learningrate = tf.train.exponentialdecay(starterlearningrate, globalstep, 100000, 0.96, staircase=True)

Passing global_step to minimize() will increment it at each step.

learningstep = ( tf.train.GradientDescentOptimizer(learningrate) .minimize(...my loss..., globalstep=globalstep) ) ```

Args:
  • learning_rate: A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
  • global_step: A scalar int32 or int64 Tensor or a Python number. Global step to use for the decay computation. Must not be negative.
  • decay_steps: A scalar int32 or int64 Tensor or a Python number. Must be positive. See the decay computation above.
  • decay_rate: A scalar float32 or float64 Tensor or a Python number. The decay rate.
  • staircase: Boolean. If True decay the learning rate at discrete intervals
  • name: String. Optional name of the operation. Defaults to 'ExponentialDecay'.
Returns:

A scalar Tensor of the same type as learning_rate. The decayed learning rate.

Raises:
  • ValueError: if global_step is not supplied.

tf.train.inverse_time_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None){#inversetimedecay}

Applies inverse time decay to the initial learning rate.

When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies an inverse decay function to a provided initial learning rate. It requires an global_step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.

The function returns the decayed learning rate. It is computed as:

python decayed_learning_rate = learning_rate / (1 + decay_rate * t)

Example: decay 1/t with a rate of 0.5:

```python ... globalstep = tf.Variable(0, trainable=False) learningrate = 0.1 k = 0.5 learningrate = tf.train.inversetimedecay(learningrate, global_step, k)

Passing global_step to minimize() will increment it at each step.

learningstep = ( tf.train.GradientDescentOptimizer(learningrate) .minimize(...my loss..., globalstep=globalstep) ) ```

Args:
  • learning_rate: A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
  • global_step: A Python number. Global step to use for the decay computation. Must not be negative.
  • decay_steps: How often to apply decay.
  • decay_rate: A Python number. The decay rate.
  • staircase: Whether to apply decay in a discrete staircase, as opposed to continuous, fashion.
  • name: String. Optional name of the operation. Defaults to 'InverseTimeDecay'.
Returns:

A scalar Tensor of the same type as learning_rate. The decayed learning rate.

Raises:
  • ValueError: if global_step is not supplied.

tf.train.natural_exp_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False, name=None){#naturalexpdecay}

Applies natural exponential decay to the initial learning rate.

When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies an exponential decay function to a provided initial learning rate. It requires an global_step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.

The function returns the decayed learning rate. It is computed as:

python decayed_learning_rate = learning_rate * exp(-decay_rate * global_step)

Example: decay exponentially with a base of 0.96:

```python ... globalstep = tf.Variable(0, trainable=False) learningrate = 0.1 k = 0.5 learningrate = tf.train.exponentialtimedecay(learningrate, global_step, k)

Passing global_step to minimize() will increment it at each step.

learningstep = ( tf.train.GradientDescentOptimizer(learningrate) .minimize(...my loss..., globalstep=globalstep) ) ```

Args:
  • learning_rate: A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
  • global_step: A Python number. Global step to use for the decay computation. Must not be negative.
  • decay_steps: How often to apply decay.
  • decay_rate: A Python number. The decay rate.
  • staircase: Whether to apply decay in a discrete staircase, as opposed to continuous, fashion.
  • name: String. Optional name of the operation. Defaults to 'ExponentialTimeDecay'.
Returns:

A scalar Tensor of the same type as learning_rate. The decayed learning rate.

Raises:
  • ValueError: if global_step is not supplied.

tf.train.piecewise_constant(x, boundaries, values, name=None) {#piecewise_constant}

Piecewise constant from boundaries and interval values.

Example: use a learning rate that's 1.0 for the first 100000 steps, 0.5 for steps 100001 to 110000, and 0.1 for any additional steps.

```python globalstep = tf.Variable(0, trainable=False) boundaries = [100000, 110000] values = [1.0, 0.5, 0.1] learningrate = tf.train.piecewiseconstant(globalstep, boundaries, values)

Later, whenever we perform an optimization step, we increment global_step.

```

Args:
  • x: A 0-D scalar Tensor. Must be one of the following types: float32float64uint8int8int16int32int64.
  • boundaries: A list of Tensors or ints or floats with strictly increasing entries, and with all elements having the same type as x.
  • values: A list of Tensors or floats orints that specifies the values for the intervals defined byboundaries. It should have one more element thanboundaries`, and all elements should have the same type.
  • name: A string. Optional name of the operation. Defaults to 'PiecewiseConstant'.
Returns:

A 0-D Tensor. Its value is values[0] when x <= boundaries[0]values[1] when x > boundaries[0] and x <= boundaries[1], ..., and values[-1] whenx > boundaries[-1].

Raises:
  • ValueError: if types of x and buondaries do not match, or types of all values do not match.

tf.train.polynomial_decay(learning_rate, global_step, decay_steps, end_learning_rate=0.0001, power=1.0, cycle=False, name=None){#polynomial_decay}

Applies a polynomial decay to the learning rate.

It is commonly observed that a monotonically decreasing learning rate, whose degree of change is carefully chosen, results in a better performing model. This function applies a polynomial decay function to a provided initial learning_rate to reach an end_learning_rate in the given decay_steps.

It requires a global_step value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step.

The function returns the decayed learning rate. It is computed as:

```python globalstep = min(globalstep, decaysteps) decayedlearningrate = (learningrate - endlearningrate) * (1 - globalstep / decaysteps) ^ (power) + endlearningrate

```

If cycle is True then a multiple of decay_steps is used, the first one that is bigger than global_steps.

```python decaysteps = decaysteps * ceil(globalstep / decaysteps) decayedlearningrate = (learningrate - endlearning_rate) * (1 - globalstep / decaysteps) ^ (power) + endlearningrate

```

Example: decay from 0.1 to 0.01 in 10000 steps using sqrt (i.e. power=0.5):

```python ... globalstep = tf.Variable(0, trainable=False) starterlearningrate = 0.1 endlearningrate = 0.01 decaysteps = 10000 learningrate = tf.train.polynomialdecay(starterlearningrate, globalstep, decaysteps, endlearningrate, power=0.5)

Passing global_step to minimize() will increment it at each step.

learningstep = ( tf.train.GradientDescentOptimizer(learningrate) .minimize(...my loss..., globalstep=globalstep) ) ```

Args:
  • learning_rate: A scalar float32 or float64 Tensor or a Python number. The initial learning rate.
  • global_step: A scalar int32 or int64 Tensor or a Python number. Global step to use for the decay computation. Must not be negative.
  • decay_steps: A scalar int32 or int64 Tensor or a Python number. Must be positive. See the decay computation above.
  • end_learning_rate: A scalar float32 or float64 Tensor or a Python number. The minimal end learning rate.
  • power: A scalar float32 or float64 Tensor or a Python number. The power of the polynomial. Defaults to sqrt, i.e. 0.5.
  • cycle: A boolean, whether or not it should cycle beyond decay_steps.
  • name: String. Optional name of the operation. Defaults to 'PolynomialDecay'.
Returns:

A scalar Tensor of the same type as learning_rate. The decayed learning rate.

Raises:
  • ValueError: if global_step is not supplied.

Moving Averages

Some training algorithms, such as GradientDescent and Momentum often benefit from maintaining a moving average of variables during optimization. Using the moving averages for evaluations often improve results significantly.


class tf.train.ExponentialMovingAverage {#ExponentialMovingAverage}

Maintains moving averages of variables by employing an exponential decay.

When training a model, it is often beneficial to maintain moving averages of the trained parameters. Evaluations that use averaged parameters sometimes produce significantly better results than the final trained values.

The apply() method adds shadow copies of trained variables and add ops that maintain a moving average of the trained variables in their shadow copies. It is used when building the training model. The ops that maintain moving averages are typically run after each training step. The average() andaverage_name() methods give access to the shadow variables and their names. They are useful when building an evaluation model, or when restoring a model from a checkpoint file. They help use the moving averages in place of the last trained values for evaluations.

The moving averages are computed using exponential decay. You specify the decay value when creating the ExponentialMovingAverage object. The shadow variables are initialized with the same initial values as the trained variables. When you run the ops to maintain the moving averages, each shadow variable is updated with the formula:

shadow_variable -= (1 - decay) * (shadow_variable - variable)

This is mathematically equivalent to the classic formula below, but the use of an assign_sub op (the "-=" in the formula) allows concurrent lockless updates to the variables:

shadow_variable = decay * shadow_variable + (1 - decay) * variable

Reasonable values for decay are close to 1.0, typically in the multiple-nines range: 0.999, 0.9999, etc.

Example usage when creating a training model:

```python

Create variables.

var0 = tf.Variable(...) var1 = tf.Variable(...)

... use the variables to build a training model...

...

Create an op that applies the optimizer. This is what we usually

would use as a training op.

optop = opt.minimize(myloss, [var0, var1])

Create an ExponentialMovingAverage object

ema = tf.train.ExponentialMovingAverage(decay=0.9999)

Create the shadow variables, and add ops to maintain moving averages

of var0 and var1.

maintainaveragesop = ema.apply([var0, var1])

Create an op that will update the moving averages after each training

step. This is what we will use in place of the usual training op.

with tf.controldependencies([optop]): training_op = tf.group(maintainaveragesop)

...train the model by running training_op... ```

There are two ways to use the moving averages for evaluations:

  • Build a model that uses the shadow variables instead of the variables. For this, use the average() method which returns the shadow variable for a given variable.
  • Build a model normally but load the checkpoint files to evaluate by using the shadow variable names. For this use the average_name() method. See the Saver class for more information on restoring saved variables.

Example of restoring the shadow variable values:

```python

Create a Saver that loads variables from their saved shadow values.

shadowvar0name = ema.averagename(var0) shadowvar1name = ema.averagename(var1) saver = tf.train.Saver({shadowvar0name: var0, shadowvar1name: var1}) saver.restore(...checkpoint filename...)

var0 and var1 now hold the moving average values

```


tf.train.ExponentialMovingAverage.__init__(decay, num_updates=None, name='ExponentialMovingAverage'){#ExponentialMovingAverage.init}

Creates a new ExponentialMovingAverage object.

The apply() method has to be called to create shadow variables and add ops to maintain moving averages.

The optional num_updates parameter allows one to tweak the decay rate dynamically. It is typical to pass the count of training steps, usually kept in a variable that is incremented at each step, in which case the decay rate is lower at the start of training. This makes moving averages move faster. If passed, the actual decay rate used is:

min(decay, (1 + num_updates) / (10 + num_updates))

Args:
  • decay: Float. The decay to use.
  • num_updates: Optional count of number of updates applied to variables.
  • name: String. Optional prefix name to use for the name of ops added in apply().

tf.train.ExponentialMovingAverage.apply(var_list=None) {#ExponentialMovingAverage.apply}

Maintains moving averages of variables.

var_list must be a list of Variable or Tensor objects. This method creates shadow variables for all elements of var_list. Shadow variables forVariable objects are initialized to the variable's initial value. They will be added to the GraphKeys.MOVING_AVERAGE_VARIABLES collection. For Tensorobjects, the shadow variables are initialized to 0 and zero debiased (see docstring in assign_moving_average for more details).

shadow variables are created with trainable=False and added to the GraphKeys.ALL_VARIABLES collection. They will be returned by calls totf.all_variables().

Returns an op that updates all shadow variables as described above.

Note that apply() can be called multiple times with different lists of variables.

Args:
  • var_list: A list of Variable or Tensor objects. The variables and Tensors must be of types float16, float32, or float64.
Returns:

An Operation that updates the moving averages.

Raises:
  • TypeError: If the arguments are not all float16, float32, or float64.
  • ValueError: If the moving average of one of the variables is already being computed.

tf.train.ExponentialMovingAverage.average_name(var) {#ExponentialMovingAverage.average_name}

Returns the name of the Variable holding the average for var.

The typical scenario for ExponentialMovingAverage is to compute moving averages of variables during training, and restore the variables from the computed moving averages during evaluations.

To restore variables, you have to know the name of the shadow variables. That name and the original variable can then be passed to a Saver() object to restore the variable from the moving average value with: saver = tf.train.Saver({ema.average_name(var): var})

average_name() can be called whether or not apply() has been called.

Args:
  • var: A Variable object.
Returns:

A string: The name of the variable that will be used or was used by the ExponentialMovingAverage class to hold the moving average of var.


tf.train.ExponentialMovingAverage.average(var) {#ExponentialMovingAverage.average}

Returns the Variable holding the average of var.

Args:
  • var: A Variable object.
Returns:

Variable object or None if the moving average of var is not maintained.


tf.train.ExponentialMovingAverage.variables_to_restore(moving_avg_variables=None){#ExponentialMovingAverage.variablestorestore}

Returns a map of names to Variables to restore.

If a variable has a moving average, use the moving average variable name as the restore name; otherwise, use the variable name.

For example,

python variables_to_restore = ema.variables_to_restore() saver = tf.train.Saver(variables_to_restore)

Below is an example of such mapping:

conv/batchnorm/gamma/ExponentialMovingAverage: conv/batchnorm/gamma, conv_4/conv2d_params/ExponentialMovingAverage: conv_4/conv2d_params, global_step: global_step

Args:
  • moving_avg_variables: a list of variables that require to use of the moving variable name to be restored. If None, it will default to variables.movingaveragevariables() + variables.trainable_variables()
Returns:

A map from restorenames to variables. The restorename can be the moving_average version of the variable name if it exist, or the original variable name.

Coordinator and QueueRunner

See Threading and Queues for how to use threads and queues. For documentation on the Queue API, see Queues.


class tf.train.Coordinator {#Coordinator}

A coordinator for threads.

This class implements a simple mechanism to coordinate the termination of a set of threads.

Usage:

```python

Create a coordinator.

coord = Coordinator()

Start a number of threads, passing the coordinator to each of them.

...start thread 1...(coord, ...) ...start thread N...(coord, ...)

Wait for all the threads to terminate.

coord.join(threads) ```

Any of the threads can call coord.request_stop() to ask for all the threads to stop. To cooperate with the requests, each thread must check forcoord.should_stop() on a regular basis. coord.should_stop() returns True as soon as coord.request_stop() has been called.

A typical thread running with a coordinator will do something like:

python while not coord.should_stop(): ...do some work...

Exception handling:

A thread can report an exception to the coordinator as part of the should_stop() call. The exception will be re-raised from the coord.join() call.

Thread code:

python try: while not coord.should_stop(): ...do some work... except Exception as e: coord.request_stop(e)

Main code:

python try: ... coord = Coordinator() # Start a number of threads, passing the coordinator to each of them. ...start thread 1...(coord, ...) ...start thread N...(coord, ...) # Wait for all the threads to terminate. coord.join(threads) except Exception as e: ...exception that was passed to coord.request_stop()

To simplify the thread implementation, the Coordinator provides a context handler stop_on_exception() that automatically requests a stop if an exception is raised. Using the context handler the thread code above can be written as:

python with coord.stop_on_exception(): while not coord.should_stop(): ...do some work...

Grace period for stopping:

After a thread has called coord.request_stop() the other threads have a fixed time to stop, this is called the 'stop grace period' and defaults to 2 minutes. If any of the threads is still alive after the grace period expires coord.join() raises a RuntimeException reporting the laggards.

python try: ... coord = Coordinator() # Start a number of threads, passing the coordinator to each of them. ...start thread 1...(coord, ...) ...start thread N...(coord, ...) # Wait for all the threads to terminate, give them 10s grace period coord.join(threads, stop_grace_period_secs=10) except RuntimeException: ...one of the threads took more than 10s to stop after request_stop() ...was called. except Exception: ...exception that was passed to coord.request_stop()


tf.train.Coordinator.__init__(clean_stop_exception_types=None) {#Coordinator.init}

Create a new Coordinator.

Args:
  • clean_stop_exception_types: Optional tuple of Exception types that should cause a clean stop of the coordinator. If an exception of one of these types is reported to request_stop(ex) the coordinator will behave as if request_stop(None) was called. Defaults to (tf.errors.OutOfRangeError,)which is used by input queues to signal the end of input. When feeding training data from a Python iterator it is common to add StopIteration to this list.

tf.train.Coordinator.clear_stop() {#Coordinator.clear_stop}

Clears the stop flag.

After this is called, calls to should_stop() will return False.


tf.train.Coordinator.join(threads=None, stop_grace_period_secs=120) {#Coordinator.join}

Wait for threads to terminate.

This call blocks until a set of threads have terminated. The set of thread is the union of the threads passed in the threads argument and the list of threads that registered with the coordinator by calling Coordinator.register_thread().

After the threads stop, if an exc_info was passed to request_stop, that exception is re-raised.

Grace period handling: When request_stop() is called, threads are given 'stopgraceperiod_secs' seconds to terminate. If any of them is still alive after that period expires, a RuntimeError is raised. Note that if an exc_info was passed to request_stop() then it is raised instead of that RuntimeError.

Args:
  • threads: List of threading.Threads. The started threads to join in addition to the registered threads.
  • stop_grace_period_secs: Number of seconds given to threads to stop after request_stop() has been called.
Raises:
  • RuntimeError: If any thread is still alive after request_stop() is called and the grace period expires.

tf.train.Coordinator.joined {#Coordinator.joined}


tf.train.Coordinator.raise_requested_exception() {#Coordinator.raiserequestedexception}

If an exception has been passed to request_stop, this raises it.


tf.train.Coordinator.register_thread(thread) {#Coordinator.register_thread}

Register a thread to join.

Args:
  • thread: A Python thread to join.

tf.train.Coordinator.request_stop(ex=None) {#Coordinator.request_stop}

Request that the threads stop.

After this is called, calls to should_stop() will return True.

Note: If an exception is being passed in, in must be in the context of handling the exception (i.e. try: ... except Exception as ex: ...) and not a newly created one.

Args:
  • ex: Optional Exception, or Python exc_info tuple as returned by sys.exc_info(). If this is the first call to request_stop() the corresponding exception is recorded and re-raised from join().

tf.train.Coordinator.should_stop() {#Coordinator.should_stop}

Check if stop was requested.

Returns:

True if a stop was requested.


tf.train.Coordinator.stop_on_exception() {#Coordinator.stoponexception}

Context manager to request stop when an Exception is raised.

Code that uses a coordinator must catch exceptions and pass them to the request_stop() method to stop the other threads managed by the coordinator.

This context handler simplifies the exception handling. Use it as follows:

python with coord.stop_on_exception(): # Any exception raised in the body of the with # clause is reported to the coordinator before terminating # the execution of the body. ...body...

This is completely equivalent to the slightly longer code:

python try: ...body... exception Exception as ex: coord.request_stop(ex)

Yields:

nothing.


tf.train.Coordinator.wait_for_stop(timeout=None) {#Coordinator.waitforstop}

Wait till the Coordinator is told to stop.

Args:
  • timeout: Float. Sleep for up to that many seconds waiting for should_stop() to become True.
Returns:

True if the Coordinator is told stop, False if the timeout expired.


class tf.train.QueueRunner {#QueueRunner}

Holds a list of enqueue operations for a queue, each to be run in a thread.

Queues are a convenient TensorFlow mechanism to compute tensors asynchronously using multiple threads. For example in the canonical 'Input Reader' setup one set of threads generates filenames in a queue; a second set of threads read records from the files, processes them, and enqueues tensors on a second queue; a third set of threads dequeues these input records to construct batches and runs them through training operations.

There are several delicate issues when running multiple threads that way: closing the queues in sequence as the input is exhausted, correctly catching and reporting exceptions, etc.

The QueueRunner, combined with the Coordinator, helps handle these issues.


tf.train.QueueRunner.__init__(queue=None, enqueue_ops=None, close_op=None, cancel_op=None, queue_closed_exception_types=None, queue_runner_def=None, import_scope=None){#QueueRunner.init}

Create a QueueRunner.

On construction the QueueRunner adds an op to close the queue. That op will be run if the enqueue ops raise exceptions.

When you later call the create_threads() method, the QueueRunner will create one thread for each op in enqueue_ops. Each thread will run its enqueue op in parallel with the other threads. The enqueue ops do not have to all be the same op, but it is expected that they all enqueue tensors in queue.

Args:
  • queue: A Queue.
  • enqueue_ops: List of enqueue ops to run in threads later.
  • close_op: Op to close the queue. Pending enqueue ops are preserved.
  • cancel_op: Op to close the queue and cancel pending enqueue ops.
  • queue_closed_exception_types: Optional tuple of Exception types that indicate that the queue has been closed when raised during an enqueue operation. Defaults to (tf.errors.OutOfRangeError,). Another common case includes (tf.errors.OutOfRangeError, tf.errors.CancelledError), when some of the enqueue ops may dequeue from other Queues.
  • queue_runner_def: Optional QueueRunnerDef protocol buffer. If specified, recreates the QueueRunner from its contents. queue_runner_def and the other arguments are mutually exclusive.
  • import_scope: Optional string. Name scope to add. Only used when initializing from protocol buffer.
Raises:
  • ValueError: If both queue_runner_def and queue are both specified.
  • ValueError: If queue or enqueue_ops are not provided when not restoring from queue_runner_def.

tf.train.QueueRunner.cancel_op {#QueueRunner.cancel_op}


tf.train.QueueRunner.close_op {#QueueRunner.close_op}


tf.train.QueueRunner.create_threads(sess, coord=None, daemon=False, start=False){#QueueRunner.create_threads}

Create threads to run the enqueue ops for the given session.

This method requires a session in which the graph was launched. It creates a list of threads, optionally starting them. There is one thread for each op passed in enqueue_ops.

The coord argument is an optional coordinator that the threads will use to terminate together and report exceptions. If a coordinator is given, this method starts an additional thread to close the queue when the coordinator requests a stop.

If previously created threads for the given session are still running, no new threads will be created.

Args:
  • sess: A Session.
  • coord: Optional Coordinator object for reporting errors and checking stop conditions.
  • daemon: Boolean. If True make the threads daemon threads.
  • start: Boolean. If True starts the threads. If False the caller must call the start() method of the returned threads.
Returns:

A list of threads.


tf.train.QueueRunner.enqueue_ops {#QueueRunner.enqueue_ops}


tf.train.QueueRunner.exceptions_raised {#QueueRunner.exceptions_raised}

Exceptions raised but not handled by the QueueRunner threads.

Exceptions raised in queue runner threads are handled in one of two ways depending on whether or not a Coordinator was passed tocreate_threads():

  • With a Coordinator, exceptions are reported to the coordinator and forgotten by the QueueRunner.
  • Without a Coordinator, exceptions are captured by the QueueRunner and made available in this exceptions_raised property.
Returns:

A list of Python Exception objects. The list is empty if no exception was captured. (No exceptions are captured when using a Coordinator.)


tf.train.QueueRunner.from_proto(queue_runner_def, import_scope=None) {#QueueRunner.from_proto}

Returns a QueueRunner object created from queue_runner_def.


tf.train.QueueRunner.name {#QueueRunner.name}

The string name of the underlying Queue.


tf.train.QueueRunner.queue {#QueueRunner.queue}


tf.train.QueueRunner.queue_closed_exception_types {#QueueRunner.queueclosedexception_types}


tf.train.QueueRunner.to_proto(export_scope=None) {#QueueRunner.to_proto}

Converts this QueueRunner to a QueueRunnerDef protocol buffer.

Args:
  • export_scope: Optional string. Name scope to remove.
Returns:

QueueRunnerDef protocol buffer, or None if the Variable is not in the specified name scope.


tf.train.add_queue_runner(qr, collection='queue_runners') {#addqueuerunner}

Adds a QueueRunner to a collection in the graph.

When building a complex model that uses many queues it is often difficult to gather all the queue runners that need to be run. This convenience function allows you to add a queue runner to a well known collection in the graph.

The companion method start_queue_runners() can be used to start threads for all the collected queue runners.

Args:
  • qr: A QueueRunner.
  • collection: A GraphKey specifying the graph collection to add the queue runner to. Defaults to GraphKeys.QUEUE_RUNNERS.

tf.train.start_queue_runners(sess=None, coord=None, daemon=True, start=True, collection='queue_runners'){#startqueuerunners}

Starts all queue runners collected in the graph.

This is a companion method to add_queue_runner(). It just starts threads for all queue runners collected in the graph. It returns the list of all threads.

Args:
  • sessSession used to run the queue ops. Defaults to the default session.
  • coord: Optional Coordinator for coordinating the started threads.
  • daemon: Whether the threads should be marked as daemons, meaning they don't block program exit.
  • start: Set to False to only create the threads, not start them.
  • collection: A GraphKey specifying the graph collection to get the queue runners from. Defaults to GraphKeys.QUEUE_RUNNERS.
Returns:

A list of threads.

Distributed execution

See Distributed TensorFlow for more information about how to configure a distributed TensorFlow program.


class tf.train.Server {#Server}

An in-process TensorFlow server, for use in distributed training.

tf.train.Server instance encapsulates a set of devices and a tf.Session target that can participate in distributed training. A server belongs to a cluster (specified by a tf.train.ClusterSpec), and corresponds to a particular task in a named job. The server can communicate with any other server in the same cluster.


tf.train.Server.__init__(server_or_cluster_def, job_name=None, task_index=None, protocol=None, config=None, start=True){#Server.init}

Creates a new server with the given definition.

The job_nametask_index, and protocol arguments are optional, and override any information provided in server_or_cluster_def.

Args:
  • server_or_cluster_def: A tf.train.ServerDef or tf.train.ClusterDef protocol buffer, or a tf.train.ClusterSpec object, describing the server to be created and/or the cluster of which it is a member.
  • job_name: (Optional.) Specifies the name of the job of which the server is a member. Defaults to the value in server_or_cluster_def, if specified.
  • task_index: (Optional.) Specifies the task index of the server in its job. Defaults to the value in server_or_cluster_def, if specified. Otherwise defaults to 0 if the server's job has only one task.
  • protocol: (Optional.) Specifies the protocol to be used by the server. Acceptable values include "grpc". Defaults to the value inserver_or_cluster_def, if specified. Otherwise defaults to "grpc".
  • config: (Options.) A tf.ConfigProto that specifies default configuration options for all sessions that run on this server.
  • start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to True.
Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while creating the TensorFlow server.


tf.train.Server.create_local_server(config=None, start=True) {#Server.createlocalserver}

Creates a new single-process cluster running on the local host.

This method is a convenience wrapper for creating a tf.train.Server with a tf.train.ServerDef that specifies a single-process cluster containing a single task in a job called "local".

Args:
  • config: (Options.) A tf.ConfigProto that specifies default configuration options for all sessions that run on this server.
  • start: (Optional.) Boolean, indicating whether to start the server after creating it. Defaults to True.
Returns:

A local tf.train.Server.


tf.train.Server.target {#Server.target}

Returns the target for a tf.Session to connect to this server.

To create a tf.Session that connects to this server, use the following snippet:

python server = tf.train.Server(...) with tf.Session(server.target): # ...

Returns:

A string containing a session target for this server.


tf.train.Server.server_def {#Server.server_def}

Returns the tf.train.ServerDef for this server.

Returns:

tf.train.ServerDef protocol buffer that describes the configuration of this server.


tf.train.Server.start() {#Server.start}

Starts this server.

Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while starting the TensorFlow server.


tf.train.Server.join() {#Server.join}

Blocks until the server has shut down.

This method currently blocks forever.

Raises:

tf.errors.OpError: Or one of its subclasses if an error occurs while joining the TensorFlow server.


class tf.train.Supervisor {#Supervisor}

A training helper that checkpoints models and computes summaries.

The Supervisor is a small wrapper around a Coordinator, a Saver, and a SessionManager that takes care of common needs of TensorFlow training programs.

Use for a single program

python with tf.Graph().as_default(): ...add operations to the graph... # Create a Supervisor that will checkpoint the model in '/tmp/mydir'. sv = Supervisor(logdir='/tmp/mydir') # Get a TensorFlow session managed by the supervisor. with sv.managed_session(FLAGS.master) as sess: # Use the session to train the graph. while not sv.should_stop(): sess.run()

Within the with sv.managed_session() block all variables in the graph have been initialized. In addition, a few services have been started to checkpoint the model and add summaries to the event log.

If the program crashes and is restarted, the managed session automatically reinitialize variables from the most recent checkpoint.

The supervisor is notified of any exception raised by one of the services. After an exception is raised, should_stop() returns True. In that case the training loop should also stop. This is why the training loop has to check for sv.should_stop().

Exceptions that indicate that the training inputs have been exhausted, tf.errors.OutOfRangeError, also cause sv.should_stop() to return True but are not re-raised from the with block: they indicate a normal termination.

Use for multiple replicas

To train with replicas you deploy the same program in a Cluster. One of the tasks must be identified as the chief: the task that handles initialization, checkpoints, summaries, and recovery. The other tasks depend on the chief for these services.

The only change you have to do to the single program code is to indicate if the program is running as the chief.

```python

Choose a task as the chief. This could be based on serverdef.taskindex,

or jobdef.name, or jobdef.tasks. It's entirely up to the end user.

But there can be only one chief.

ischief = (serverdef.taskindex == 0) server = tf.train.Server(serverdef)

with tf.Graph().asdefault(): ...add operations to the graph... # Create a Supervisor that uses log directory on a shared file system. # Indicate if you are the 'chief' sv = Supervisor(logdir='/shareddirectory/...', ischief=ischief) # Get a Session in a TensorFlow server on the cluster. with sv.managedsession(server.target) as sess: # Use the session to train the graph. while not sv.shouldstop(): sess.run() ```

In the chief task, the Supervisor works exactly as in the first example above. In the other tasks sv.managed_session() waits for the Model to have been initialized before returning a session to the training code. The non-chief tasks depend on the chief task for initializing the model.

If one of the tasks crashes and restarts, managed_session() checks if the Model is initialized. If yes, it just creates a session and returns it to the training code that proceeds normally. If the model needs to be initialized, the chief task takes care of reinitializing it; the other tasks just wait for the model to have been initialized.

NOTE: This modified program still works fine as a single program. The single program marks itself as the chief.

What master string to use

Whether you are running on your machine or in the cluster you can use the following values for the --master flag:

  • Specifying '' requests an in-process session that does not use RPC.

  • Specifying 'local' requests a session that uses the RPC-based "Master interface" to run TensorFlow programs. Seetf.train.Server.create_local_server() for details.

  • Specifying 'grpc://hostname:port' requests a session that uses the RPC interface to a specific , and also allows the in-process master to access remote tensorflow workers. Often, it is appropriate to pass server.target (for some tf.train.Server named `server).

Advanced use

Launching additional services

managed_session() launches the Checkpoint and Summary services (threads). If you need more services to run you can simply launch them in the block controlled by managed_session().

Example: Start a thread to print losses. We want this thread to run every 60 seconds, so we launch it with sv.loop().

python ... sv = Supervisor(logdir='/tmp/mydir') with sv.managed_session(FLAGS.master) as sess: sv.loop(60, print_loss, (sess)) while not sv.should_stop(): sess.run(my_train_op)

Launching fewer services

managed_session() launches the "summary" and "checkpoint" threads which use either the optionally summary_op and saver passed to the constructor, or default ones created automatically by the supervisor. If you want to run your own summary and checkpointing logic, disable these services by passingNone to the summary_op and saver parameters.

Example: Create summaries manually every 100 steps in the chief.

python # Create a Supervisor with no automatic summaries. sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None) # As summary_op was None, managed_session() does not start the # summary thread. with sv.managed_session(FLAGS.master) as sess: for step in xrange(1000000): if sv.should_stop(): break if is_chief and step % 100 == 0: # Create the summary every 100 chief steps. sv.summary_computed(sess, sess.run(my_summary_op)) else: # Train normally sess.run(my_train_op)

Custom model initialization

managed_session() only supports initializing the model by running an init_op or restoring from the latest checkpoint. If you have special initialization needs, see how to specify a local_init_op when creating the supervisor. You can also use the SessionManager directly to create a session and check if it could be initialized automatically.


tf.train.Supervisor.__init__(graph=None, ready_op=0, ready_for_local_init_op=0, is_chief=True, init_op=0, init_feed_dict=None, local_init_op=0, logdir=None, summary_op=0, saver=0, global_step=0, save_summaries_secs=120, save_model_secs=600, recovery_wait_secs=30, stop_grace_secs=120, checkpoint_basename='model.ckpt', session_manager=None, summary_writer=0, init_fn=None){#Supervisor.init}

Create a Supervisor.

Args:
  • graph: A Graph. The graph that the model will use. Defaults to the default Graph. The supervisor may add operations to the graph before creating a session, but the graph should not be modified by the caller after passing it to the supervisor.
  • ready_op: 1-D string Tensor. This tensor is evaluated by supervisors in prepare_or_wait_for_session() to check if the model is ready to use. The model is considered ready if it returns an empty array. Defaults to the tensor returned from tf.report_uninitialized_variables() If None, the model is not checked for readiness.
  • ready_for_local_init_op: 1-D string Tensor. This tensor is evaluated by supervisors in prepare_or_wait_for_session() to check if the model is ready to run the localinitop. The model is considered ready if it returns an empty array. Defaults to the tensor returned fromtf.report_uninitialized_variables(tf.all_variables()). If None, the model is not checked for readiness before running localinitop.
  • is_chief: If True, create a chief supervisor in charge of initializing and restoring the model. If False, create a supervisor that relies on a chief supervisor for inits and restore.
  • init_opOperation. Used by chief supervisors to initialize the model when it can not be recovered. Defaults to an Operation that initializes all variables. If None, no initialization is done automatically unless you pass a value for init_fn, see below.
  • init_feed_dict: A dictionary that maps Tensor objects to feed values. This feed dictionary will be used when init_op is evaluated.
  • local_init_opOperation. Used by all supervisors to run initializations that should run for every new supervisor instance. By default these are table initializers and initializers for local variables. If None, no further per supervisor-instance initialization is done automatically.
  • logdir: A string. Optional path to a directory where to checkpoint the model and log events for the visualizer. Used by chief supervisors. The directory will be created if it does not exist.
  • summary_op: An Operation that returns a Summary for the event logs. Used by chief supervisors if a logdir was specified. Defaults to the operation returned from summary.merge_all(). If None, summaries are not computed automatically.
  • saver: A Saver object. Used by chief supervisors if a logdir was specified. Defaults to the saved returned by Saver(). If None, the model is not saved automatically.
  • global_step: An integer Tensor of size 1 that counts steps. The value from 'globalstep' is used in summaries and checkpoint filenames. Default to the op named 'globalstep' in the graph if it exists, is of rank 1, size 1, and of type tf.int32 or tf.int64. If None the global step is not recorded in summaries and checkpoint files. Used by chief supervisors if a logdir was specified.
  • save_summaries_secs: Number of seconds between the computation of summaries for the event log. Defaults to 120 seconds. Pass 0 to disable summaries.
  • save_model_secs: Number of seconds between the creation of model checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints.
  • recovery_wait_secs: Number of seconds between checks that the model is ready. Used by supervisors when waiting for a chief supervisor to initialize or restore the model. Defaults to 30 seconds.
  • stop_grace_secs: Grace period, in seconds, given to running threads to stop when stop() is called. Defaults to 120 seconds.
  • checkpoint_basename: The basename for checkpoint saving.
  • session_managerSessionManager, which manages Session creation and recovery. If it is None, a default SessionManager will be created with the set of arguments passed in for backwards compatibility.
  • summary_writerSummaryWriter to use or USE_DEFAULT. Can be None to indicate that no summaries should be written.
  • init_fn: Optional callable used to initialize the model. Called after the optional init_op is called. The callable must accept one argument, the session being initialized.
Returns:

你可能感兴趣的:(tensorflow,机器学习)