code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
tensorflow tf.compat.v1.assert_rank_in tf.compat.v1.assert\_rank\_in
=============================
Assert `x` has rank in `ranks`.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_rank_in`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_rank_in)
```
tf.compat.v1.assert_rank_in(
x, ranks, data=None, summarize=None, message=None, name=None
)
```
Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_rank_in(x, (2, 4))]):
output = tf.reduce_sum(x)
```
| Args |
| `x` | Numeric `Tensor`. |
| `ranks` | Iterable of scalar `Tensor` objects. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_rank\_in". |
| Returns |
| Op raising `InvalidArgumentError` unless rank of `x` is in `ranks`. If static checks determine `x` has matching rank, a `no_op` is returned. |
| Raises |
| `ValueError` | If static checks determine `x` has mismatched rank. |
tensorflow tf.compat.v1.gradients tf.compat.v1.gradients
======================
Constructs symbolic derivatives of sum of `ys` w.r.t. x in `xs`.
```
tf.compat.v1.gradients(
ys,
xs,
grad_ys=None,
name='gradients',
colocate_gradients_with_ops=False,
gate_gradients=False,
aggregation_method=None,
stop_gradients=None,
unconnected_gradients=tf.UnconnectedGradients.NONE
)
```
`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 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` and for x in `xs`.
`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).
`stop_gradients` is a `Tensor` or a list of tensors to be considered constant with respect to all `xs`. These tensors will not be backpropagated through, as though they had been explicitly disconnected using `stop_gradient`. Among other things, this allows computation of partial derivatives as opposed to total derivatives. For example:
```
a = tf.constant(0.)
b = 2 * a
g = tf.gradients(a + b, [a, b], stop_gradients=[a, b])
```
Here the partial derivatives `g` evaluate to `[1.0, 1.0]`, compared to the total derivatives `tf.gradients(a + b, [a, b])`, which take into account the influence of `a` on `b` and evaluate to `[3.0, 1.0]`. Note that the above is equivalent to:
```
a = tf.stop_gradient(tf.constant(0.))
b = tf.stop_gradient(2 * a)
g = tf.gradients(a + b, [a, b])
```
`stop_gradients` provides a way of stopping gradient after the graph has already been constructed, as compared to [`tf.stop_gradient`](../../stop_gradient) which is used during graph construction. When the two approaches are combined, backpropagation stops at both [`tf.stop_gradient`](../../stop_gradient) nodes and nodes in `stop_gradients`, whichever is encountered first.
All integer tensors are considered constant with respect to all `xs`, as if they were included in `stop_gradients`.
`unconnected_gradients` determines the value returned for each x in xs if it is unconnected in the graph to ys. By default this is None to safeguard against errors. Mathematically these gradients are zero which can be requested using the `'zero'` option. `tf.UnconnectedGradients` provides the following options and behaviors:
```
a = tf.ones([1, 2])
b = tf.ones([3, 1])
g1 = tf.gradients([b], [a], unconnected_gradients='none')
sess.run(g1) # [None]
g2 = tf.gradients([b], [a], unconnected_gradients='zero')
sess.run(g2) # [array([[0., 0.]], dtype=float32)]
```
Let us take one practical example which comes during the back propogation phase. This function is used to evaluate the derivatives of the cost function with respect to Weights `Ws` and Biases `bs`. Below sample implementation provides the exaplantion of what it is actually used for :
```
Ws = tf.constant(0.)
bs = 2 * Ws
cost = Ws + bs # This is just an example. So, please ignore the formulas.
g = tf.gradients(cost, [Ws, bs])
dCost_dW, dCost_db = g
```
| 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`. |
| `stop_gradients` | Optional. A `Tensor` or list of tensors not to differentiate through. |
| `unconnected_gradients` | Optional. Specifies the gradient value returned when the given input tensors are unconnected. Accepted values are constants defined in the class [`tf.UnconnectedGradients`](../../unconnectedgradients) and the default value is `none`. |
| Returns |
| A list of `Tensor` of length `len(xs)` where each tensor is the `sum(dy/dx)` for y in `ys` and for 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. |
| `RuntimeError` | if called in Eager mode. |
tensorflow tf.compat.v1.hessians tf.compat.v1.hessians
=====================
Constructs the Hessian of sum of `ys` with respect to `x` in `xs`.
```
tf.compat.v1.hessians(
ys,
xs,
name='hessians',
colocate_gradients_with_ops=False,
gate_gradients=False,
aggregation_method=None
)
```
`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)`.
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(ys)` for each `x` in `xs`. |
| Raises |
| `LookupError` | if one of the operations between `xs` and `ys` does not have a registered gradient function. |
tensorflow tf.compat.v1.get_default_graph tf.compat.v1.get\_default\_graph
================================
Returns the default graph for the current thread.
```
tf.compat.v1.get_default_graph()
```
Migrate to TF2
--------------
`get_default_graph` does not work with either eager execution or [`tf.function`](../../function), and you should not invoke it directly. To migrate code that uses Graph-related functions to TF2, rewrite the code without them. See the [migration guide](https://www.tensorflow.org/guide/migrate) for more description about the behavior and semantic changes between Tensorflow 1 and Tensorflow 2.
Description
-----------
The returned graph will be the innermost graph on which a [`Graph.as_default()`](https://www.tensorflow.org/api_docs/python/tf/Graph#as_default) context has been entered, or a global default graph if none has been explicitly created.
>
> **Note:** The default graph is a property of the current thread. If you create a new thread, and wish to use the default graph in that thread, you must explicitly add a `with g.as_default():` in that thread's function.
>
| Returns |
| The default `Graph` being used in the current thread. |
tensorflow tf.compat.v1.LogMessage tf.compat.v1.LogMessage
=======================
A ProtocolMessage
| Attributes |
| `level` | `Level level` |
| `message` | `string message` |
| Class Variables |
| DEBUGGING | `10` |
| ERROR | `40` |
| FATAL | `50` |
| INFO | `20` |
| Level | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
| UNKNOWN | `0` |
| WARN | `30` |
tensorflow tf.compat.v1.constant tf.compat.v1.constant
=====================
Creates a constant tensor.
```
tf.compat.v1.constant(
value, dtype=None, shape=None, name='Const', verify_shape=False
)
```
The resulting tensor is populated with values of type `dtype`, as specified by arguments `value` and (optionally) `shape` (see examples below).
The argument `value` can be a constant value, or a list of values of type `dtype`. If `value` is a list, then the length of the list must be less than or equal to the number of elements implied by the `shape` argument (if specified). In the case where the list length is less than the number of elements specified by `shape`, the last element in the list will be used to fill the remaining entries.
The argument `shape` is optional. If present, it specifies the dimensions of the resulting tensor. If not present, the shape of `value` is used.
If the argument `dtype` is not specified, then the type is inferred from the type of `value`.
#### For example:
```
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
```
[`tf.constant`](../../constant) differs from [`tf.fill`](../../fill) in a few ways:
* [`tf.constant`](../../constant) supports arbitrary constants, not just uniform scalar Tensors like [`tf.fill`](../../fill).
* [`tf.constant`](../../constant) creates a `Const` node in the computation graph with the exact value at graph construction time. On the other hand, [`tf.fill`](../../fill) creates an Op in the graph that is expanded at runtime.
* Because [`tf.constant`](../../constant) only embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereas [`tf.fill`](../../fill) does.
| Args |
| `value` | A constant value (or list) of output type `dtype`. |
| `dtype` | The type of the elements of the resulting tensor. |
| `shape` | Optional dimensions of resulting tensor. |
| `name` | Optional name for the tensor. |
| `verify_shape` | Boolean that enables verification of a shape of values. |
| Returns |
| A Constant Tensor. |
| Raises |
| `TypeError` | if shape is incorrectly specified or unsupported. |
tensorflow tf.compat.v1.assign tf.compat.v1.assign
===================
Update `ref` by assigning `value` to it.
```
tf.compat.v1.assign(
ref, value, validate_shape=None, use_locking=None, name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.assign`](assign) is mostly compatible with eager execution and [`tf.function`](../../function). However, argument 'validate\_shape' will be ignored. To avoid shape validation, set 'shape' to tf.TensorShape(None) when constructing the variable:
```
import tensorflow as tf
a = tf.Variable([1], shape=tf.TensorShape(None))
tf.compat.v1.assign(a, [2,3])
```
To switch to the native TF2 style, one could use method 'assign' of [`tf.Variable`](../../variable):
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `ref` | `self` | In `assign()` method |
| `value` | `value` | In `assign()` method |
| `validate_shape` | Not supported | Specify `shape` in the constructor to replicate behavior |
| `use_locking` | `use_locking` | In `assign()` method |
| `name` | `name` | In `assign()` method |
| - | `read_value` | Set to True to replicate behavior (True is default) |
Description
-----------
This operation outputs a Tensor that holds the new value of `ref` after the value has been assigned. This makes it easier to chain operations that need to use the reset value.
| Args |
| `ref` | A mutable `Tensor`. Should be from a `Variable` node. May be uninitialized. |
| `value` | A `Tensor`. Must have the same shape and dtype as `ref`. The value to be assigned to the variable. |
| `validate_shape` | An optional `bool`. Defaults to `True`. If true, the operation will validate that the shape of 'value' matches the shape of the Tensor being assigned to. If false, 'ref' will take on the shape of 'value'. |
| `use_locking` | An optional `bool`. Defaults to `True`. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` that will hold the new value of `ref` after the assignment has completed. |
#### Before & After Usage Example
#### Before:
```
with tf.Graph().as_default():
with tf.compat.v1.Session() as sess:
a = tf.compat.v1.Variable(0, dtype=tf.int64)
sess.run(a.initializer)
update_op = tf.compat.v1.assign(a, 2)
res_a = sess.run(update_op)
res_a
2
```
#### After:
```
b = tf.Variable(0, dtype=tf.int64)
res_b = b.assign(2)
res_b.numpy()
2
```
tensorflow tf.compat.v1.get_default_session tf.compat.v1.get\_default\_session
==================================
Returns the default session for the current thread.
```
tf.compat.v1.get_default_session()
```
The returned `Session` will be the innermost session on which a `Session` or `Session.as_default()` context has been entered.
>
> **Note:** The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function.
>
| Returns |
| The default `Session` being used in the current thread. |
tensorflow tf.compat.v1.random_normal_initializer tf.compat.v1.random\_normal\_initializer
========================================
Initializer that generates tensors with a normal distribution.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.random_normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/random_normal_initializer)
```
tf.compat.v1.random_normal_initializer(
mean=0.0,
stddev=1.0,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../function).
To switch to TF2, switch to using either [`tf.initializers.RandomNormal`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomNormal) or [`tf.keras.initializers.RandomNormal`](../../keras/initializers/randomnormal) (neither from [`compat.v1`](../v1)) and pass the dtype when calling the initializer. Keep in mind that the default stddev and the behavior of fixed seeds have changed.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.random_normal_initializer(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.initializers.RandomNormal(
mean=mean,
seed=seed,
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | Default changes from 1.0 to 0.05 |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported. |
Description
-----------
| Args |
| `mean` | a python scalar or a scalar tensor. Mean of the random values to generate. |
| `stddev` | a python scalar or a scalar tensor. Standard deviation of the random values to generate. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L567-L573)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L561-L565)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow Module: tf.compat.v1.initializers Module: tf.compat.v1.initializers
=================================
Public API for tf.initializers namespace.
Classes
-------
[`class constant`](keras/initializers/constant): Initializer that generates tensors with constant values.
[`class glorot_normal`](keras/initializers/glorot_normal): The Glorot normal initializer, also called Xavier normal initializer.
[`class glorot_uniform`](keras/initializers/glorot_uniform): The Glorot uniform initializer, also called Xavier uniform initializer.
[`class identity`](keras/initializers/identity): Initializer that generates the identity matrix.
[`class ones`](keras/initializers/ones): Initializer that generates tensors initialized to 1.
[`class orthogonal`](keras/initializers/orthogonal): Initializer that generates an orthogonal matrix.
[`class random_normal`](random_normal_initializer): Initializer that generates tensors with a normal distribution.
[`class random_uniform`](random_uniform_initializer): Initializer that generates tensors with a uniform distribution.
[`class truncated_normal`](truncated_normal_initializer): Initializer that generates a truncated normal distribution.
[`class uniform_unit_scaling`](uniform_unit_scaling_initializer): Initializer that generates tensors without scaling variance.
[`class variance_scaling`](keras/initializers/variancescaling): Initializer capable of adapting its scale to the shape of weights tensors.
[`class zeros`](keras/initializers/zeros): Initializer that generates tensors initialized to 0.
Functions
---------
[`global_variables(...)`](global_variables_initializer): Returns an Op that initializes global variables.
[`he_normal(...)`](initializers/he_normal): He normal initializer.
[`he_uniform(...)`](initializers/he_uniform): He uniform variance scaling initializer.
[`lecun_normal(...)`](initializers/lecun_normal): LeCun normal initializer.
[`lecun_uniform(...)`](initializers/lecun_uniform): LeCun uniform initializer.
[`local_variables(...)`](local_variables_initializer): Returns an Op that initializes all local variables.
[`tables_initializer(...)`](tables_initializer): Returns an Op that initializes all tables of the default graph.
[`variables(...)`](variables_initializer): Returns an Op that initializes a list of variables.
| programming_docs |
tensorflow tf.compat.v1.batch_gather tf.compat.v1.batch\_gather
==========================
Gather slices from params according to indices with leading batch dims. (deprecated)
```
tf.compat.v1.batch_gather(
params, indices, name=None
)
```
tensorflow tf.compat.v1.AttrValue tf.compat.v1.AttrValue
======================
A ProtocolMessage
| Attributes |
| `b` | `bool b` |
| `f` | `float f` |
| `func` | `NameAttrList func` |
| `i` | `int64 i` |
| `list` | `ListValue list` |
| `placeholder` | `string placeholder` |
| `s` | `bytes s` |
| `shape` | `TensorShapeProto shape` |
| `tensor` | `TensorProto tensor` |
| `type` | `DataType type` |
Child Classes
-------------
[`class ListValue`](attrvalue/listvalue)
tensorflow tf.compat.v1.Print tf.compat.v1.Print
==================
Prints a list of tensors. (deprecated)
```
tf.compat.v1.Print(
input_, data, message=None, first_n=None, summarize=None, name=None
)
```
Migrate to TF2
--------------
This API is deprecated. Use [`tf.print`](../../print) instead. [`tf.print`](../../print) does not need the `input_` argument.
[`tf.print`](../../print) works in TF2 when executing eagerly and inside a [`tf.function`](../../function).
In TF1-styled sessions, an explicit control dependency declaration is needed to execute the [`tf.print`](../../print) operation. Refer to the documentation of [`tf.print`](../../print) for more details.
Description
-----------
This is an identity op (behaves like [`tf.identity`](../../identity)) with the side effect of printing `data` when evaluating.
>
> **Note:** This op prints to the standard error. It is not currently compatible with jupyter notebook (printing to the notebook *server's* output, not into the notebook).
>
| Args |
| `input_` | A tensor passed through this op. |
| `data` | A list of tensors to print out when op is evaluated. |
| `message` | A string, prefix of the error message. |
| `first_n` | Only log `first_n` number of times. Negative numbers log always; this is the default. |
| `summarize` | Only print this many entries of each tensor. If None, then a maximum of 3 elements are printed per input tensor. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type and contents as `input_`.
```
sess = tf.compat.v1.Session()
with sess.as_default():
tensor = tf.range(10)
print_op = tf.print(tensor)
with tf.control_dependencies([print_op]):
out = tf.add(tensor, tensor)
sess.run(out)
```
|
tensorflow tf.compat.v1.load_file_system_library tf.compat.v1.load\_file\_system\_library
========================================
Loads a TensorFlow plugin, containing file system implementation. (deprecated)
```
tf.compat.v1.load_file_system_library(
library_filename
)
```
Pass `library_filename` to a platform-specific mechanism for dynamically loading a library. The rules for determining the exact location of the library are platform-specific and are not documented here.
| Args |
| `library_filename` | Path to the plugin. Relative or absolute filesystem path to a dynamic library file. |
| Returns |
| None. |
| Raises |
| `RuntimeError` | when unable to load the library. |
tensorflow tf.compat.v1.decode_csv tf.compat.v1.decode\_csv
========================
Convert CSV records to tensors. Each column maps to one tensor.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.io.decode_csv`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/decode_csv)
```
tf.compat.v1.decode_csv(
records,
record_defaults,
field_delim=',',
use_quote_delim=True,
name=None,
na_value='',
select_cols=None
)
```
RFC 4180 format is expected for the CSV records. (<https://tools.ietf.org/html/rfc4180>) Note that we allow leading and trailing spaces with int or float field.
| Args |
| `records` | A `Tensor` of type `string`. Each string is a record/row in the csv and all records should have the same format. |
| `record_defaults` | A list of `Tensor` objects with specific types. Acceptable types are `float32`, `float64`, `int32`, `int64`, `string`. One tensor per column of the input record, with either a scalar default value for that column or an empty vector if the column is required. |
| `field_delim` | An optional `string`. Defaults to `","`. char delimiter to separate fields in a record. |
| `use_quote_delim` | An optional `bool`. Defaults to `True`. If false, treats double quotation marks as regular characters inside of the string fields (ignoring RFC 4180, Section 2, Bullet 5). |
| `name` | A name for the operation (optional). |
| `na_value` | Additional string to recognize as NA/NaN. |
| `select_cols` | Optional sorted list of column indices to select. If specified, only this subset of columns will be parsed and returned. |
| Returns |
| A list of `Tensor` objects. Has the same type as `record_defaults`. Each tensor will have the same shape as records. |
| Raises |
| `ValueError` | If any of the arguments is malformed. |
tensorflow tf.compat.v1.GraphOptions tf.compat.v1.GraphOptions
=========================
A ProtocolMessage
| Attributes |
| `build_cost_model` | `int64 build_cost_model` |
| `build_cost_model_after` | `int64 build_cost_model_after` |
| `enable_bfloat16_sendrecv` | `bool enable_bfloat16_sendrecv` |
| `enable_recv_scheduling` | `bool enable_recv_scheduling` |
| `infer_shapes` | `bool infer_shapes` |
| `optimizer_options` | `OptimizerOptions optimizer_options` |
| `place_pruned_graph` | `bool place_pruned_graph` |
| `rewrite_options` | `RewriterConfig rewrite_options` |
| `timeline_step` | `int32 timeline_step` |
tensorflow tf.compat.v1.bincount tf.compat.v1.bincount
=====================
Counts the number of occurrences of each value in an integer array.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.bincount`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/bincount)
```
tf.compat.v1.bincount(
arr,
weights=None,
minlength=None,
maxlength=None,
dtype=tf.dtypes.int32
)
```
If `minlength` and `maxlength` are not given, returns a vector with length `tf.reduce_max(arr) + 1` if `arr` is non-empty, and length 0 otherwise. If `weights` are non-None, then index `i` of the output stores the sum of the value in `weights` at each index where the corresponding value in `arr` is `i`.
| Args |
| `arr` | An int32 tensor of non-negative values. |
| `weights` | If non-None, must be the same shape as arr. For each value in `arr`, the bin will be incremented by the corresponding weight instead of 1. |
| `minlength` | If given, ensures the output has length at least `minlength`, padding with zeros at the end if necessary. |
| `maxlength` | If given, skips values in `arr` that are equal or greater than `maxlength`, ensuring that the output has length at most `maxlength`. |
| `dtype` | If `weights` is None, determines the type of the output bins. |
| Returns |
| A vector with the same dtype as `weights` or the given `dtype`. The bin values. |
tensorflow tf.compat.v1.sparse_placeholder tf.compat.v1.sparse\_placeholder
================================
Inserts a placeholder for a sparse tensor that will be always fed.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.placeholder`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_placeholder)
```
tf.compat.v1.sparse_placeholder(
dtype, shape=None, name=None
)
```
#### For example:
```
x = tf.compat.v1.sparse.placeholder(tf.float32)
y = tf.sparse.reduce_sum(x)
with tf.compat.v1.Session() as sess:
print(sess.run(y)) # ERROR: will fail because x was not fed.
indices = np.array([[3, 2, 0], [4, 5, 1]], dtype=np.int64)
values = np.array([1.0, 2.0], dtype=np.float32)
shape = np.array([7, 9, 2], dtype=np.int64)
print(sess.run(y, feed_dict={
x: tf.compat.v1.SparseTensorValue(indices, values, shape)})) # Will
succeed.
print(sess.run(y, feed_dict={
x: (indices, values, shape)})) # Will succeed.
sp = tf.sparse.SparseTensor(indices=indices, values=values,
dense_shape=shape)
sp_value = sp.eval(session=sess)
print(sess.run(y, feed_dict={x: sp_value})) # Will succeed.
```
@compatibility{eager} Placeholders are not compatible with eager execution.
| Args |
| `dtype` | The type of `values` elements in the tensor to be fed. |
| `shape` | The shape of the tensor to be fed (optional). If the shape is not specified, you can feed a sparse tensor of any shape. |
| `name` | A name for prefixing the operations (optional). |
| Returns |
| A `SparseTensor` that may be used as a handle for feeding a value, but not evaluated directly. |
| Raises |
| `RuntimeError` | if eager execution is enabled |
tensorflow tf.compat.v1.serialize_many_sparse tf.compat.v1.serialize\_many\_sparse
====================================
Serialize `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor`.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.io.serialize_many_sparse`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/serialize_many_sparse)
```
tf.compat.v1.serialize_many_sparse(
sp_input,
name=None,
out_type=tf.dtypes.string
)
```
The `SparseTensor` must have rank `R` greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the `SparseTensor` must be sorted in increasing order of this first dimension. The serialized `SparseTensor` objects going into each row of the output `Tensor` will have rank `R-1`.
The minibatch size `N` is extracted from `sparse_shape[0]`.
| Args |
| `sp_input` | The input rank `R` `SparseTensor`. |
| `name` | A name prefix for the returned tensors (optional). |
| `out_type` | The `dtype` to use for serialization. |
| Returns |
| A matrix (2-D `Tensor`) with `N` rows and `3` columns. Each column represents serialized `SparseTensor`'s indices, values, and shape (respectively). |
| Raises |
| `TypeError` | If `sp_input` is not a `SparseTensor`. |
tensorflow tf.compat.v1.div tf.compat.v1.div
================
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated)
```
tf.compat.v1.div(
x, y, name=None
)
```
Migrate to TF2
--------------
This function is deprecated in TF2. Prefer using the Tensor division operator, [`tf.divide`](../../math/divide), or [`tf.math.divide`](../../math/divide), which obey the Python 3 division operator semantics.
Description
-----------
This function divides `x` and `y`, forcing Python 2 semantics. That is, if `x` and `y` are both integers then the result will be an integer. This is in contrast to Python 3, where division with `/` is always a float while division with `//` is always an integer.
| Args |
| `x` | `Tensor` numerator of real numeric type. |
| `y` | `Tensor` denominator of real numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` returns the quotient of x and y. |
tensorflow Module: tf.compat.v1.data Module: tf.compat.v1.data
=========================
[`tf.data.Dataset`](../../data/dataset) API for input pipelines.
See [Importing Data](https://tensorflow.org/guide/data) for an overview.
Modules
-------
[`experimental`](data/experimental) module: Experimental API for building input pipelines.
Classes
-------
[`class Dataset`](data/dataset): Represents a potentially large set of elements.
[`class DatasetSpec`](../../data/datasetspec): Type specification for [`tf.data.Dataset`](../../data/dataset).
[`class FixedLengthRecordDataset`](data/fixedlengthrecorddataset): A `Dataset` of fixed-length records from one or more binary files.
[`class Iterator`](data/iterator): Represents the state of iterating through a `Dataset`.
[`class Options`](../../data/options): Represents options for [`tf.data.Dataset`](../../data/dataset).
[`class TFRecordDataset`](data/tfrecorddataset): A `Dataset` comprising records from one or more TFRecord files.
[`class TextLineDataset`](data/textlinedataset): A `Dataset` comprising lines from one or more text files.
[`class ThreadingOptions`](../../data/threadingoptions): Represents options for dataset threading.
Functions
---------
[`get_output_classes(...)`](data/get_output_classes): Returns the output classes for elements of the input dataset / iterator.
[`get_output_shapes(...)`](data/get_output_shapes): Returns the output shapes for elements of the input dataset / iterator.
[`get_output_types(...)`](data/get_output_types): Returns the output shapes for elements of the input dataset / iterator.
[`make_initializable_iterator(...)`](data/make_initializable_iterator): Creates an iterator for elements of `dataset`.
[`make_one_shot_iterator(...)`](data/make_one_shot_iterator): Creates an iterator for elements of `dataset`.
| Other Members |
| AUTOTUNE | `-1` |
| INFINITE\_CARDINALITY | `-1` |
| UNKNOWN\_CARDINALITY | `-2` |
tensorflow tf.compat.v1.container tf.compat.v1.container
======================
Wrapper for [`Graph.container()`](https://www.tensorflow.org/api_docs/python/tf/Graph#container) using the default graph.
```
tf.compat.v1.container(
container_name
)
```
| Args |
| `container_name` | The container string to use in the context. |
| Returns |
| A context manager that specifies the default container to use for newly created stateful ops. |
tensorflow tf.compat.v1.assert_none_equal tf.compat.v1.assert\_none\_equal
================================
Assert the condition `x != y` holds element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_none_equal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_none_equal)
```
tf.compat.v1.assert_none_equal(
x, y, data=None, summarize=None, message=None, name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.assert_none_equal`](assert_none_equal) is compatible with eager execution and [`tf.function`](../../function). Please use [`tf.debugging.assert_none_equal`](../../debugging/assert_none_equal) instead when migrating to TF2. Apart from `data`, all arguments are supported with the same argument name.
If you want to ensure the assert statements run before the potentially-invalid computation, please use [`tf.control_dependencies`](../../control_dependencies), as tf.function auto-control dependencies are insufficient for assert statements.
#### Structural Mapping to Native TF2
Before:
```
tf.compat.v1.assert_none_equal(
x=x, y=y, data=data, summarize=summarize,
message=message, name=name)
```
After:
```
tf.debugging.assert_none_equal(
x=x, y=y, message=message,
summarize=summarize, name=name)
```
#### TF1 & TF2 Usage Example
TF1:
```
g = tf.Graph()
with g.as_default():
a = tf.compat.v1.placeholder(tf.float32, [2])
b = tf.compat.v1.placeholder(tf.float32, [2])
result = tf.compat.v1.assert_none_equal(a, b,
message='"a != b" does not hold for the given inputs')
with tf.compat.v1.control_dependencies([result]):
sum_node = a + b
sess = tf.compat.v1.Session(graph=g)
val = sess.run(sum_node, feed_dict={a: [1, 2], b:[2, 1]})
```
TF2:
```
a = tf.Variable([1, 2], dtype=tf.float32)
b = tf.Variable([2, 1], dtype=tf.float32)
assert_op = tf.debugging.assert_none_equal(a, b, message=
'"a != b" does not hold for the given inputs')
# When working with tf.control_dependencies
with tf.control_dependencies([assert_op]):
val = a + b
```
Description
-----------
This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have `x[i] != y[i]`. If both `x` and `y` are empty, this is trivially satisfied.
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_none_equal(x, y)]):
output = tf.reduce_sum(x)
```
| Args |
| `x` | Numeric `Tensor`. |
| `y` | Numeric `Tensor`, same dtype as and broadcastable to `x`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_none\_equal". |
| Returns |
| Op that raises `InvalidArgumentError` if `x != y` is False. |
| Raises |
| `InvalidArgumentError` | if the check can be performed immediately and `x != y` is False. The check can be performed immediately during eager execution or if `x` and `y` are statically known. |
tensorflow tf.compat.v1.placeholder tf.compat.v1.placeholder
========================
Inserts a placeholder for a tensor that will be always fed.
```
tf.compat.v1.placeholder(
dtype, shape=None, name=None
)
```
Migrate to TF2
--------------
This API is not compatible with eager execution and [`tf.function`](../../function). To migrate to TF2, rewrite the code to be compatible with eager execution. Check the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls. In TF2, you can just pass tensors directly into ops and layers. If you want to explicitly set up your inputs, also see [Keras functional API](https://www.tensorflow.org/guide/keras/functional) on how to use [`tf.keras.Input`](../../keras/input) to replace [`tf.compat.v1.placeholder`](placeholder). [`tf.function`](../../function) arguments also do the job of [`tf.compat.v1.placeholder`](placeholder). For more details please read [Better performance with tf.function](https://www.tensorflow.org/guide/function).
Description
-----------
#### For example:
```
x = tf.compat.v1.placeholder(tf.float32, shape=(1024, 1024))
y = tf.matmul(x, x)
with tf.compat.v1.Session() as sess:
print(sess.run(y)) # ERROR: will fail because x was not fed.
rand_array = np.random.rand(1024, 1024)
print(sess.run(y, feed_dict={x: rand_array})) # Will succeed.
```
| Args |
| `dtype` | The type of elements in the tensor to be fed. |
| `shape` | The shape of the tensor to be fed (optional). If the shape is not specified, you can feed a tensor of any shape. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` that may be used as a handle for feeding a value, but not evaluated directly. |
| Raises |
| `RuntimeError` | if eager execution is enabled |
tensorflow tf.compat.v1.create_partitioned_variables tf.compat.v1.create\_partitioned\_variables
===========================================
Create a list of partitioned variables according to the given `slicing`. (deprecated)
```
tf.compat.v1.create_partitioned_variables(
shape,
slicing,
initializer,
dtype=tf.dtypes.float32,
trainable=True,
collections=None,
name=None,
reuse=None
)
```
Currently only one dimension of the full variable can be sliced, and the full variable can be reconstructed by the concatenation of the returned list along that dimension.
| Args |
| `shape` | List of integers. The shape of the full variable. |
| `slicing` | List of integers. How to partition the variable. Must be of the same length as `shape`. Each value indicate how many slices to create in the corresponding dimension. Presently only one of the values can be more than 1; that is, the variable can only be sliced along one dimension. For convenience, The requested number of partitions does not have to divide the corresponding dimension evenly. If it does not, the shapes of the partitions are incremented by 1 starting from partition 0 until all slack is absorbed. The adjustment rules may change in the future, but as you can save/restore these variables with different slicing specifications this should not be a problem. |
| `initializer` | A `Tensor` of shape `shape` or a variable initializer function. If a function, it will be called once for each slice, passing the shape and data type of the slice as parameters. The function must return a tensor with the same shape as the slice. |
| `dtype` | Type of the variables. Ignored if `initializer` is a `Tensor`. |
| `trainable` | If True also add all the variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. |
| `collections` | List of graph collections keys to add the variables to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. |
| `name` | Optional name for the full variable. Defaults to `"PartitionedVariable"` and gets uniquified automatically. |
| `reuse` | Boolean or `None`; if `True` and name is set, it would reuse previously created variables. if `False` it will create new variables. if `None`, it would inherit the parent scope reuse. |
| Returns |
| A list of Variables corresponding to the slicing. |
| Raises |
| `ValueError` | If any of the arguments is malformed. |
| programming_docs |
tensorflow Module: tf.compat.v1.bitwise Module: tf.compat.v1.bitwise
============================
Operations for manipulating the binary representations of integers.
Functions
---------
[`bitwise_and(...)`](../../bitwise/bitwise_and): Elementwise computes the bitwise AND of `x` and `y`.
[`bitwise_or(...)`](../../bitwise/bitwise_or): Elementwise computes the bitwise OR of `x` and `y`.
[`bitwise_xor(...)`](../../bitwise/bitwise_xor): Elementwise computes the bitwise XOR of `x` and `y`.
[`invert(...)`](../../bitwise/invert): Invert (flip) each bit of supported types; for example, type `uint8` value 01010101 becomes 10101010.
[`left_shift(...)`](../../bitwise/left_shift): Elementwise computes the bitwise left-shift of `x` and `y`.
[`right_shift(...)`](../../bitwise/right_shift): Elementwise computes the bitwise right-shift of `x` and `y`.
tensorflow tf.compat.v1.Variable tf.compat.v1.Variable
=====================
See the [Variables Guide](https://tensorflow.org/guide/variables).
Inherits From: [`Variable`](../../variable)
```
tf.compat.v1.Variable(
initial_value=None,
trainable=None,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None,
expected_shape=None,
import_scope=None,
constraint=None,
use_resource=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE,
shape=None
)
```
A variable maintains state in the graph across calls to `run()`. You add a variable to the graph by constructing an instance of the class `Variable`.
The `Variable()` constructor requires an initial value for the variable, which can be a `Tensor` of any type and shape. The initial value defines the type and shape of the variable. After construction, the type and shape of the variable are fixed. The value can be changed using one of the assign methods.
If you want to change the shape of a variable later you have to use an `assign` Op with `validate_shape=False`.
Just like any `Tensor`, variables created with `Variable()` can be used as inputs for other Ops in the graph. Additionally, all the operators overloaded for the `Tensor` class are carried over to variables, so you can also add nodes to the graph by just doing arithmetic on variables.
```
import tensorflow as tf
# Create a variable.
w = tf.Variable(<initial-value>, name=<optional-name>)
# Use the variable in the graph like any Tensor.
y = tf.matmul(w, ...another variable or tensor...)
# The overloaded operators are available too.
z = tf.sigmoid(w + y)
# Assign a new value to the variable with `assign()` or a related method.
w.assign(w + 1.0)
w.assign_add(1.0)
```
When you launch the graph, variables have to be explicitly initialized before you can run Ops that use their value. You can initialize a variable by running its *initializer op*, restoring the variable from a save file, or simply running an `assign` Op that assigns a value to the variable. In fact, the variable *initializer op* is just an `assign` Op that assigns the variable's initial value to the variable itself.
```
# Launch the graph in a session.
with tf.compat.v1.Session() as sess:
# Run the variable initializer.
sess.run(w.initializer)
# ...you now can run ops that use the value of 'w'...
```
The most common initialization pattern is to use the convenience function `global_variables_initializer()` to add an Op to the graph that initializes all the variables. You then run that Op after launching the graph.
```
# Add an Op to initialize global variables.
init_op = tf.compat.v1.global_variables_initializer()
# Launch the graph in a session.
with tf.compat.v1.Session() as sess:
# Run the Op that initializes global variables.
sess.run(init_op)
# ...you can now run any Op that uses variable values...
```
If you need to create a variable with an initial value dependent on another variable, use the other variable's `initialized_value()`. This ensures that variables are initialized in the right order.
All variables are automatically collected in the graph where they are created. By default, the constructor adds the new variable to the graph collection `GraphKeys.GLOBAL_VARIABLES`. The convenience function `global_variables()` returns the contents of that collection.
When building a machine learning model it is often convenient to distinguish between variables holding the trainable model parameters and other variables such as a `global step` variable used to count training steps. To make this easier, the variable constructor supports a `trainable=<bool>` parameter. If `True`, the new variable is also added to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. The convenience function `trainable_variables()` returns the contents of this collection. The various `Optimizer` classes use this collection as the default list of variables to optimize.
```
v = tf.Variable(True)
tf.cond(v, lambda: v.assign(False), my_false_fn) # Note: this is broken.
```
Here, adding `use_resource=True` when constructing the variable will fix any nondeterminism issues:
```
v = tf.Variable(True, use_resource=True)
tf.cond(v, lambda: v.assign(False), my_false_fn)
```
To use the replacement for variables which does not have these issues:
* Add `use_resource=True` when constructing [`tf.Variable`](../../variable);
* Call `tf.compat.v1.get_variable_scope().set_use_resource(True)` inside a [`tf.compat.v1.variable_scope`](variable_scope) before the [`tf.compat.v1.get_variable()`](get_variable) call.
| Args |
| `initial_value` | A `Tensor`, or Python object convertible to a `Tensor`, which is the initial value for the Variable. The initial value must have a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, `dtype` must be specified. (Note that initializer functions from init\_ops.py must first be bound to a shape before being used here.) |
| `trainable` | If `True`, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. Defaults to `True`, unless `synchronization` is set to `ON_READ`, in which case it defaults to `False`. |
| `collections` | List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`. |
| `validate_shape` | If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of `initial_value` must be known. |
| `caching_device` | Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. |
| `name` | Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically. |
| `variable_def` | `VariableDef` protocol buffer. If not `None`, recreates the Variable object with its contents, referencing the variable's nodes in the graph, which must already exist. The graph is not changed. `variable_def` and the other arguments are mutually exclusive. |
| `dtype` | If set, initial\_value will be converted to the given type. If `None`, either the datatype will be kept (if `initial_value` is a Tensor), or `convert_to_tensor` will decide. |
| `expected_shape` | A TensorShape. If set, initial\_value is expected to have this shape. |
| `import_scope` | Optional `string`. Name scope to add to the `Variable.` Only used when initializing from protocol buffer. |
| `constraint` | An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `use_resource` | whether to use resource variables. |
| `synchronization` | Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableSynchronization`](../../variablesynchronization). By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. |
| `aggregation` | Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableAggregation`](../../variableaggregation). |
| `shape` | (optional) The shape of this variable. If None, the shape of `initial_value` will be used. When setting this argument to [`tf.TensorShape(None)`](../../tensorshape) (representing an unspecified shape), the variable can be assigned with values of different shapes. |
| Raises |
| `ValueError` | If both `variable_def` and initial\_value are specified. |
| `ValueError` | If the initial value is not specified, or does not have a shape and `validate_shape` is `True`. |
| `RuntimeError` | If eager execution is enabled. |
| Attributes |
| `aggregation` | |
| `constraint` | Returns the constraint function associated with this variable. |
| `device` | The device of this variable. |
| `dtype` | The `DType` of this variable. |
| `graph` | The `Graph` of this variable. |
| `initial_value` | Returns the Tensor used as the initial value for the variable. Note that this is different from `initialized_value()` which runs the op that initializes the variable before returning its value. This method returns the tensor that is used by the op that initializes the variable. |
| `initializer` | The initializer operation for this variable. |
| `name` | The name of this variable. |
| `op` | The `Operation` of this variable. |
| `shape` | The `TensorShape` of this variable. |
| `synchronization` | |
| `trainable` | |
Child Classes
-------------
[`class SaveSliceInfo`](../../variable/savesliceinfo)
Methods
-------
### `assign`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L579-L595)
```
assign(
value, use_locking=False, name=None, read_value=True
)
```
Assigns a new value to the variable.
This is essentially a shortcut for `assign(self, value)`.
| Args |
| `value` | A `Tensor`. The new value for this variable. |
| `use_locking` | If `True`, use locking during the assignment. |
| `name` | The name of the operation to be created |
| `read_value` | if True, will return something which evaluates to the new value of the variable; if False will return the assign op. |
| Returns |
| The updated variable. If `read_value` is false, instead returns None in Eager mode and the assign op in graph mode. |
### `assign_add`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L597-L613)
```
assign_add(
delta, use_locking=False, name=None, read_value=True
)
```
Adds a value to this variable.
This is essentially a shortcut for `assign_add(self, delta)`.
| Args |
| `delta` | A `Tensor`. The value to add to this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | The name of the operation to be created |
| `read_value` | if True, will return something which evaluates to the new value of the variable; if False will return the assign op. |
| Returns |
| The updated variable. If `read_value` is false, instead returns None in Eager mode and the assign op in graph mode. |
### `assign_sub`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L615-L631)
```
assign_sub(
delta, use_locking=False, name=None, read_value=True
)
```
Subtracts a value from this variable.
This is essentially a shortcut for `assign_sub(self, delta)`.
| Args |
| `delta` | A `Tensor`. The value to subtract from this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | The name of the operation to be created |
| `read_value` | if True, will return something which evaluates to the new value of the variable; if False will return the assign op. |
| Returns |
| The updated variable. If `read_value` is false, instead returns None in Eager mode and the assign op in graph mode. |
### `batch_scatter_update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L747-L791)
```
batch_scatter_update(
sparse_delta, use_locking=False, name=None
)
```
Assigns [`tf.IndexedSlices`](../../indexedslices) to this variable batch-wise.
Analogous to `batch_gather`. This assumes that this variable and the sparse\_delta IndexedSlices have a series of leading dimensions that are the same for all of them, and the updates are performed on the last dimension of indices. In other words, the dimensions should be the following:
`num_prefix_dims = sparse_delta.indices.ndims - 1` `batch_dim = num_prefix_dims + 1` `sparse_delta.updates.shape = sparse_delta.indices.shape + var.shape[ batch_dim:]`
where
`sparse_delta.updates.shape[:num_prefix_dims]` `== sparse_delta.indices.shape[:num_prefix_dims]` `== var.shape[:num_prefix_dims]`
And the operation performed can be expressed as:
`var[i_1, ..., i_n, sparse_delta.indices[i_1, ..., i_n, j]] = sparse_delta.updates[ i_1, ..., i_n, j]`
When sparse\_delta.indices is a 1D tensor, this operation is equivalent to `scatter_update`.
To avoid this operation one can looping over the first `ndims` of the variable and using `scatter_update` on the subtensors that result of slicing the first dimension. This is a valid option for `ndims = 1`, but less efficient than this implementation.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to be assigned to this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `count_up_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L962-L983)
```
count_up_to(
limit
)
```
Increments this variable until it reaches `limit`. (deprecated)
When that Op is run it tries to increment the variable by `1`. If incrementing the variable would bring it above `limit` then the Op raises the exception `OutOfRangeError`.
If no error is raised, the Op outputs the value of the variable before the increment.
This is essentially a shortcut for `count_up_to(self, limit)`.
| Args |
| `limit` | value at which incrementing the variable raises an error. |
| Returns |
| A `Tensor` that will hold the variable value before the increment. If no other Op modifies this variable, the values produced will all be distinct. |
### `eval`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L496-L526)
```
eval(
session=None
)
```
In a session, computes and returns the value of this variable.
This is not a graph construction method, it does not add ops to the graph.
This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See [`tf.compat.v1.Session`](session) for more information on launching a graph and on sessions.
```
v = tf.Variable([1, 2])
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
print(v.eval(sess))
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
print(v.eval())
```
| Args |
| `session` | The session to use to evaluate this variable. If none, the default session is used. |
| Returns |
| A numpy `ndarray` with a copy of the value of this variable. |
### `experimental_ref`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1205-L1207)
```
experimental_ref()
```
DEPRECATED FUNCTION
### `from_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1189-L1192)
```
@staticmethod
from_proto(
variable_def, import_scope=None
)
```
Returns a `Variable` object created from `variable_def`.
### `gather_nd`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L947-L960)
```
gather_nd(
indices, name=None
)
```
Gather slices from `params` into a Tensor with shape specified by `indices`.
See tf.gather\_nd for details.
| Args |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `params`. |
### `get_shape`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1169-L1171)
```
get_shape()
```
Alias of [`Variable.shape`](https://www.tensorflow.org/api_docs/python/tf/Variable#shape).
### `initialized_value`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L528-L553)
```
initialized_value()
```
Returns the value of the initialized variable. (deprecated)
You should use this instead of the variable itself to initialize another variable with a value that depends on the value of this variable.
```
# Initialize 'v' with a random tensor.
v = tf.Variable(tf.random.truncated_normal([10, 40]))
# Use `initialized_value` to guarantee that `v` has been
# initialized before its value is used to initialize `w`.
# The random values are picked only once.
w = tf.Variable(v.initialized_value() * 2.0)
```
| Returns |
| A `Tensor` holding the value of this variable after its initializer has run. |
### `load`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L985-L1028)
```
load(
value, session=None
)
```
Load new value into this variable. (deprecated)
Writes new value to variable's memory. Doesn't add ops to the graph.
This convenience method requires a session where the graph containing this variable has been launched. If no session is passed, the default session is used. See [`tf.compat.v1.Session`](session) for more information on launching a graph and on sessions.
```
v = tf.Variable([1, 2])
init = tf.compat.v1.global_variables_initializer()
with tf.compat.v1.Session() as sess:
sess.run(init)
# Usage passing the session explicitly.
v.load([2, 3], sess)
print(v.eval(sess)) # prints [2 3]
# Usage with the default session. The 'with' block
# above makes 'sess' the default session.
v.load([3, 4], sess)
print(v.eval()) # prints [3 4]
```
| Args |
| `value` | New variable value |
| `session` | The session to use to evaluate this variable. If none, the default session is used. |
| Raises |
| `ValueError` | Session is not passed and no default session |
### `read_value`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L465-L474)
```
read_value()
```
Returns the value of this variable, read in the current context.
Can be different from value() if it's on another device, with control dependencies, etc.
| Returns |
| A `Tensor` containing the value of the variable. |
### `ref`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1209-L1248)
```
ref()
```
Returns a hashable reference object to this Variable.
The primary use case for this API is to put variables in a set/dictionary. We can't put variables in a set/dictionary as `variable.__hash__()` is no longer available starting Tensorflow 2.0.
The following will raise an exception starting 2.0
```
x = tf.Variable(5)
y = tf.Variable(10)
z = tf.Variable(10)
variable_set = {x, y, z}
Traceback (most recent call last):
TypeError: Variable is unhashable. Instead, use tensor.ref() as the key.
variable_dict = {x: 'five', y: 'ten'}
Traceback (most recent call last):
TypeError: Variable is unhashable. Instead, use tensor.ref() as the key.
```
Instead, we can use `variable.ref()`.
```
variable_set = {x.ref(), y.ref(), z.ref()}
x.ref() in variable_set
True
variable_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'}
variable_dict[y.ref()]
'ten'
```
Also, the reference object provides `.deref()` function that returns the original Variable.
```
x = tf.Variable(5)
x.ref().deref()
<tf.Variable 'Variable:0' shape=() dtype=int32, numpy=5>
```
### `scatter_add`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L649-L663)
```
scatter_add(
sparse_delta, use_locking=False, name=None
)
```
Adds [`tf.IndexedSlices`](../../indexedslices) to this variable.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to be added to this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_div`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L715-L729)
```
scatter_div(
sparse_delta, use_locking=False, name=None
)
```
Divide this variable by [`tf.IndexedSlices`](../../indexedslices).
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to divide this variable by. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_max`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L665-L680)
```
scatter_max(
sparse_delta, use_locking=False, name=None
)
```
Updates this variable with the max of [`tf.IndexedSlices`](../../indexedslices) and itself.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to use as an argument of max with this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_min`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L682-L697)
```
scatter_min(
sparse_delta, use_locking=False, name=None
)
```
Updates this variable with the min of [`tf.IndexedSlices`](../../indexedslices) and itself.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to use as an argument of min with this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_mul`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L699-L713)
```
scatter_mul(
sparse_delta, use_locking=False, name=None
)
```
Multiply this variable by [`tf.IndexedSlices`](../../indexedslices).
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to multiply this variable by. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_nd_add`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L839-L883)
```
scatter_nd_add(
indices, updates, name=None
)
```
Applies sparse addition to individual values or slices in a Variable.
The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into self. It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th dimension of self.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
```
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
v.scatter_nd_add(indices, updates)
print(v)
```
The resulting update to v would look like this:
```
[1, 13, 3, 14, 14, 6, 7, 20]
```
See [`tf.scatter_nd`](../../scatter_nd) for more details about how to make updates to slices.
| Args |
| `indices` | The indices to be used in the operation. |
| `updates` | The values to be used in the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
### `scatter_nd_sub`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L793-L837)
```
scatter_nd_sub(
indices, updates, name=None
)
```
Applies sparse subtraction to individual values or slices in a Variable.
Assuming the variable has rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into self. It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th dimension of self.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
```
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
v.scatter_nd_sub(indices, updates)
print(v)
```
After the update `v` would look like this:
```
[1, -9, 3, -6, -4, 6, 7, -4]
```
See [`tf.scatter_nd`](../../scatter_nd) for more details about how to make updates to slices.
| Args |
| `indices` | The indices to be used in the operation. |
| `updates` | The values to be used in the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
### `scatter_nd_update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L885-L929)
```
scatter_nd_update(
indices, updates, name=None
)
```
Applies sparse assignment to individual values or slices in a Variable.
The Variable has rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into self. It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th dimension of self.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, self.shape[K], ..., self.shape[P-1]].
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
```
v = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
v.scatter_nd_update(indices, updates)
print(v)
```
The resulting update to v would look like this:
```
[1, 11, 3, 10, 9, 6, 7, 12]
```
See [`tf.scatter_nd`](../../scatter_nd) for more details about how to make updates to slices.
| Args |
| `indices` | The indices to be used in the operation. |
| `updates` | The values to be used in the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
### `scatter_sub`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L633-L647)
```
scatter_sub(
sparse_delta, use_locking=False, name=None
)
```
Subtracts [`tf.IndexedSlices`](../../indexedslices) from this variable.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to be subtracted from this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `scatter_update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L731-L745)
```
scatter_update(
sparse_delta, use_locking=False, name=None
)
```
Assigns [`tf.IndexedSlices`](../../indexedslices) to this variable.
| Args |
| `sparse_delta` | [`tf.IndexedSlices`](../../indexedslices) to be assigned to this variable. |
| `use_locking` | If `True`, use locking during the operation. |
| `name` | the name of the operation. |
| Returns |
| The updated variable. |
| Raises |
| `TypeError` | if `sparse_delta` is not an `IndexedSlices`. |
### `set_shape`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L476-L482)
```
set_shape(
shape
)
```
Overrides the shape for this variable.
| Args |
| `shape` | the `TensorShape` representing the overridden shape. |
### `sparse_read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L931-L945)
```
sparse_read(
indices, name=None
)
```
Gather slices from params axis axis according to indices.
This function supports a subset of tf.gather, see tf.gather for details on usage.
| Args |
| `indices` | The index `Tensor`. Must be one of the following types: `int32`, `int64`. Must be in range `[0, params.shape[axis])`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `params`. |
### `to_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1177-L1187)
```
to_proto(
export_scope=None
)
```
Converts a `Variable` to a `VariableDef` protocol buffer.
| Args |
| `export_scope` | Optional `string`. Name scope to remove. |
| Returns |
| A `VariableDef` protocol buffer, or `None` if the `Variable` is not in the specified name scope. |
### `value`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L446-L463)
```
value()
```
Returns the last snapshot of this variable.
You usually do not need to call this method as all ops that need the value of the variable call it automatically through a `convert_to_tensor()` call.
Returns a `Tensor` which holds the value of the variable. You can not assign a new value to this tensor as it is not a reference to the variable.
To avoid copies, if the consumer of the returned value is on the same device as the variable, this actually returns the live value of the variable, not a copy. Updates to the variable are seen by the consumer. If the consumer is on a different device it will get a copy of the variable.
| Returns |
| A `Tensor` containing the value of the variable. |
### `__abs__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L364-L408)
```
__abs__(
name=None
)
```
Computes the absolute value of a tensor.
Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input.
Given a tensor `x` of complex numbers, this operation returns a tensor of type `float32` or `float64` that is the absolute value of each element in `x`. For a complex number \(a + bj\), its absolute value is computed as \(\sqrt{a^2 + b^2}\).
#### For example:
```
# real number
x = tf.constant([-2.25, 3.25])
tf.abs(x)
<tf.Tensor: shape=(2,), dtype=float32,
numpy=array([2.25, 3.25], dtype=float32)>
```
```
# complex number
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
tf.abs(x)
<tf.Tensor: shape=(2, 1), dtype=float64, numpy=
array([[5.25594901],
[6.60492241]])>
```
| Args |
| `x` | A `Tensor` or `SparseTensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, `complex64` or `complex128`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` of the same size, type and sparsity as `x`, with absolute values. Note, for `complex64` or `complex128` input, the returned `Tensor` will be of type `float32` or `float64`, respectively. |
### `__add__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__add__(
y
)
```
The operation invoked by the [`Tensor.**add**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__add__) operator.
#### Purpose in the API:
This method is exposed in TensorFlow's API so that library developers can register dispatching for [`Tensor.**add**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__add__) to allow it to handle custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation.
| Args |
| `x` | The left-hand side of the `+` operator. |
| `y` | The right-hand side of the `+` operator. |
| `name` | an optional name for the operation. |
| Returns |
| The result of the elementwise `+` operation. |
### `__and__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__and__(
y
)
```
### `__div__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__div__(
y
)
```
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated)
#### Migrate to TF2
This function is deprecated in TF2. Prefer using the Tensor division operator, [`tf.divide`](../../math/divide), or [`tf.math.divide`](../../math/divide), which obey the Python 3 division operator semantics.
#### Description
This function divides `x` and `y`, forcing Python 2 semantics. That is, if `x` and `y` are both integers then the result will be an integer. This is in contrast to Python 3, where division with `/` is always a float while division with `//` is always an integer.
| Args |
| `x` | `Tensor` numerator of real numeric type. |
| `y` | `Tensor` denominator of real numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` returns the quotient of x and y. |
### `__eq__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1088-L1094)
```
__eq__(
other
)
```
Compares two variables element-wise for equality.
### `__floordiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__floordiv__(
y
)
```
Divides `x / y` elementwise, rounding toward the most negative integer.
Mathematically, this is equivalent to floor(x / y). For example: floor(8.4 / 4.0) = floor(2.1) = 2.0 floor(-8.4 / 4.0) = floor(-2.1) = -3.0 This is equivalent to the '//' operator in Python 3.0 and above.
>
> **Note:** `x` and `y` must have the same type, and the result will have the same type as well.
>
| Args |
| `x` | `Tensor` numerator of real numeric type. |
| `y` | `Tensor` denominator of real numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` rounded toward -infinity. |
| Raises |
| `TypeError` | If the inputs are complex. |
### `__ge__`
```
__ge__(
y, name=None
)
```
Returns the truth value of (x >= y) element-wise.
>
> **Note:** [`math.greater_equal`](https://www.tensorflow.org/api_docs/python/tf/math/greater_equal) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
#### Example:
```
x = tf.constant([5, 4, 6, 7])
y = tf.constant([5, 2, 5, 10])
tf.math.greater_equal(x, y) ==> [True, True, True, False]
x = tf.constant([5, 4, 6, 7])
y = tf.constant([5])
tf.math.greater_equal(x, y) ==> [True, False, True, True]
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `bool`. |
### `__getitem__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/array_ops.py#L1308-L1351)
```
__getitem__(
slice_spec
)
```
Creates a slice helper object given a variable.
This allows creating a sub-tensor from part of the current contents of a variable. See [`tf.Tensor.**getitem**`](../../tensor#__getitem__) for detailed examples of slicing.
This function in addition also allows assignment to a sliced range. This is similar to `__setitem__` functionality in Python. However, the syntax is different so that the user can capture the assignment operation for grouping or passing to `sess.run()`. For example,
```
import tensorflow as tf
A = tf.Variable([[1,2,3], [4,5,6], [7,8,9]], dtype=tf.float32)
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
print(sess.run(A[:2, :2])) # => [[1,2], [4,5]]
op = A[:2,:2].assign(22. * tf.ones((2, 2)))
print(sess.run(op)) # => [[22, 22, 3], [22, 22, 6], [7,8,9]]
```
Note that assignments currently do not support NumPy broadcasting semantics.
| Args |
| `var` | An `ops.Variable` object. |
| `slice_spec` | The arguments to [`Tensor.**getitem**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__getitem__). |
| Returns |
| The appropriate slice of "tensor", based on "slice\_spec". As an operator. The operator also has a `assign()` method that can be used to generate an assignment operator. |
| Raises |
| `ValueError` | If a slice range is negative size. |
| `TypeError` | TypeError: If the slice indices aren't int, slice, ellipsis, tf.newaxis or int32/int64 tensors. |
### `__gt__`
```
__gt__(
y, name=None
)
```
Returns the truth value of (x > y) element-wise.
>
> **Note:** [`math.greater`](https://www.tensorflow.org/api_docs/python/tf/math/greater) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
#### Example:
```
x = tf.constant([5, 4, 6])
y = tf.constant([5, 2, 5])
tf.math.greater(x, y) ==> [False, True, True]
x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.greater(x, y) ==> [False, False, True]
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `bool`. |
### `__invert__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1859-L1862)
```
__invert__(
name=None
)
```
### `__iter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1105-L1107)
```
__iter__()
```
When executing eagerly, iterates over the value of the variable.
### `__le__`
```
__le__(
y, name=None
)
```
Returns the truth value of (x <= y) element-wise.
>
> **Note:** [`math.less_equal`](https://www.tensorflow.org/api_docs/python/tf/math/less_equal) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
#### Example:
```
x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less_equal(x, y) ==> [True, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 6])
tf.math.less_equal(x, y) ==> [True, True, True]
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `bool`. |
### `__lt__`
```
__lt__(
y, name=None
)
```
Returns the truth value of (x < y) element-wise.
>
> **Note:** [`math.less`](https://www.tensorflow.org/api_docs/python/tf/math/less) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
#### Example:
```
x = tf.constant([5, 4, 6])
y = tf.constant([5])
tf.math.less(x, y) ==> [False, True, False]
x = tf.constant([5, 4, 6])
y = tf.constant([5, 6, 7])
tf.math.less(x, y) ==> [False, True, True]
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `bool`. |
### `__matmul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__matmul__(
y
)
```
Multiplies matrix `a` by matrix `b`, producing `a` \* `b`.
The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication dimensions, and any further outer dimensions specify matching batch size.
Both matrices must be of the same type. The supported types are: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.
Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to `True`. These are `False` by default.
If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes `bfloat16` or `float32`.
A simple 2-D tensor matrix multiplication:
```
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
a # 2-D tensor
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
b # 2-D tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[ 7, 8],
[ 9, 10],
[11, 12]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 58, 64],
[139, 154]], dtype=int32)>
```
A batch matrix multiplication with batch shape [2]:
```
a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
a # 3-D tensor
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]], dtype=int32)>
b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2])
b # 3-D tensor
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[13, 14],
[15, 16],
[17, 18]],
[[19, 20],
[21, 22],
[23, 24]]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[ 94, 100],
[229, 244]],
[[508, 532],
[697, 730]]], dtype=int32)>
```
Since python >= 3.5 the @ operator is supported (see [PEP 465](https://www.python.org/dev/peps/pep-0465/)). In TensorFlow, it simply calls the [`tf.matmul()`](../../linalg/matmul) function, so the following lines are equivalent:
```
d = a @ b @ [[10], [11]]
d = tf.matmul(tf.matmul(a, b), [[10], [11]])
```
| Args |
| `a` | [`tf.Tensor`](../../tensor) of type `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128` and rank > 1. |
| `b` | [`tf.Tensor`](../../tensor) with same type and rank as `a`. |
| `transpose_a` | If `True`, `a` is transposed before multiplication. |
| `transpose_b` | If `True`, `b` is transposed before multiplication. |
| `adjoint_a` | If `True`, `a` is conjugated and transposed before multiplication. |
| `adjoint_b` | If `True`, `b` is conjugated and transposed before multiplication. |
| `a_is_sparse` | If `True`, `a` is treated as a sparse matrix. Notice, this **does not support [`tf.sparse.SparseTensor`](../../sparse/sparsetensor)**, it just makes optimizations that assume most values in `a` are zero. See [`tf.sparse.sparse_dense_matmul`](../../sparse/sparse_dense_matmul) for some support for [`tf.sparse.SparseTensor`](../../sparse/sparsetensor) multiplication. |
| `b_is_sparse` | If `True`, `b` is treated as a sparse matrix. Notice, this **does not support [`tf.sparse.SparseTensor`](../../sparse/sparsetensor)**, it just makes optimizations that assume most values in `a` are zero. See [`tf.sparse.sparse_dense_matmul`](../../sparse/sparse_dense_matmul) for some support for [`tf.sparse.SparseTensor`](../../sparse/sparsetensor) multiplication. |
| `output_type` | The output datatype if needed. Defaults to None in which case the output\_type is the same as input type. Currently only works when input tensors are type (u)int8 and output\_type can be int32. |
| `name` | Name for the operation (optional). |
| Returns |
| A [`tf.Tensor`](../../tensor) of the same type as `a` and `b` where each inner-most matrix is the product of the corresponding matrices in `a` and `b`, e.g. if all transpose or adjoint attributes are `False`: `output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j])`, for all indices `i`, `j`. |
| `Note` | This is matrix product, not element-wise product. |
| Raises |
| `ValueError` | If `transpose_a` and `adjoint_a`, or `transpose_b` and `adjoint_b` are both set to `True`. |
| `TypeError` | If output\_type is specified but the types of `a`, `b` and `output_type` is not (u)int8, (u)int8 and int32. |
### `__mod__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__mod__(
y
)
```
Returns element-wise remainder of division. When `x < 0` xor `y < 0` is
true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`.
>
> **Note:** [`math.floormod`](https://www.tensorflow.org/api_docs/python/tf/math/floormod) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
| Args |
| `x` | A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `bfloat16`, `half`, `float32`, `float64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `x`. |
### `__mul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__mul__(
y
)
```
Dispatches cwise mul for "Dense*Dense" and "Dense*Sparse".
### `__ne__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/variables.py#L1097-L1103)
```
__ne__(
other
)
```
Compares two variables element-wise for equality.
### `__neg__`
```
__neg__(
name=None
)
```
Computes numerical negative value element-wise.
I.e., \(y = -x\).
| Args |
| `x` | A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `x`. |
### `__or__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__or__(
y
)
```
### `__pow__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__pow__(
y
)
```
Computes the power of one value to another.
Given a tensor `x` and a tensor `y`, this operation computes \(x^y\) for corresponding elements in `x` and `y`. For example:
```
x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
```
| Args |
| `x` | A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, or `complex128`. |
| `y` | A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, or `complex128`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. |
### `__radd__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__radd__(
x
)
```
The operation invoked by the [`Tensor.**add**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__add__) operator.
#### Purpose in the API:
This method is exposed in TensorFlow's API so that library developers can register dispatching for [`Tensor.**add**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__add__) to allow it to handle custom composite tensors & other custom objects.
The API symbol is not intended to be called by users directly and does appear in TensorFlow's generated documentation.
| Args |
| `x` | The left-hand side of the `+` operator. |
| `y` | The right-hand side of the `+` operator. |
| `name` | an optional name for the operation. |
| Returns |
| The result of the elementwise `+` operation. |
### `__rand__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rand__(
x
)
```
### `__rdiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rdiv__(
x
)
```
Divides x / y elementwise (using Python 2 division operator semantics). (deprecated)
#### Migrate to TF2
This function is deprecated in TF2. Prefer using the Tensor division operator, [`tf.divide`](../../math/divide), or [`tf.math.divide`](../../math/divide), which obey the Python 3 division operator semantics.
#### Description
This function divides `x` and `y`, forcing Python 2 semantics. That is, if `x` and `y` are both integers then the result will be an integer. This is in contrast to Python 3, where division with `/` is always a float while division with `//` is always an integer.
| Args |
| `x` | `Tensor` numerator of real numeric type. |
| `y` | `Tensor` denominator of real numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` returns the quotient of x and y. |
### `__rfloordiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rfloordiv__(
x
)
```
Divides `x / y` elementwise, rounding toward the most negative integer.
Mathematically, this is equivalent to floor(x / y). For example: floor(8.4 / 4.0) = floor(2.1) = 2.0 floor(-8.4 / 4.0) = floor(-2.1) = -3.0 This is equivalent to the '//' operator in Python 3.0 and above.
>
> **Note:** `x` and `y` must have the same type, and the result will have the same type as well.
>
| Args |
| `x` | `Tensor` numerator of real numeric type. |
| `y` | `Tensor` denominator of real numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` rounded toward -infinity. |
| Raises |
| `TypeError` | If the inputs are complex. |
### `__rmatmul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rmatmul__(
x
)
```
Multiplies matrix `a` by matrix `b`, producing `a` \* `b`.
The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication dimensions, and any further outer dimensions specify matching batch size.
Both matrices must be of the same type. The supported types are: `bfloat16`, `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, `complex128`.
Either matrix can be transposed or adjointed (conjugated and transposed) on the fly by setting one of the corresponding flag to `True`. These are `False` by default.
If one or both of the matrices contain a lot of zeros, a more efficient multiplication algorithm can be used by setting the corresponding `a_is_sparse` or `b_is_sparse` flag to `True`. These are `False` by default. This optimization is only available for plain matrices (rank-2 tensors) with datatypes `bfloat16` or `float32`.
A simple 2-D tensor matrix multiplication:
```
a = tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
a # 2-D tensor
<tf.Tensor: shape=(2, 3), dtype=int32, numpy=
array([[1, 2, 3],
[4, 5, 6]], dtype=int32)>
b = tf.constant([7, 8, 9, 10, 11, 12], shape=[3, 2])
b # 2-D tensor
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[ 7, 8],
[ 9, 10],
[11, 12]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2), dtype=int32, numpy=
array([[ 58, 64],
[139, 154]], dtype=int32)>
```
A batch matrix multiplication with batch shape [2]:
```
a = tf.constant(np.arange(1, 13, dtype=np.int32), shape=[2, 2, 3])
a # 3-D tensor
<tf.Tensor: shape=(2, 2, 3), dtype=int32, numpy=
array([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]], dtype=int32)>
b = tf.constant(np.arange(13, 25, dtype=np.int32), shape=[2, 3, 2])
b # 3-D tensor
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[13, 14],
[15, 16],
[17, 18]],
[[19, 20],
[21, 22],
[23, 24]]], dtype=int32)>
c = tf.matmul(a, b)
c # `a` * `b`
<tf.Tensor: shape=(2, 2, 2), dtype=int32, numpy=
array([[[ 94, 100],
[229, 244]],
[[508, 532],
[697, 730]]], dtype=int32)>
```
Since python >= 3.5 the @ operator is supported (see [PEP 465](https://www.python.org/dev/peps/pep-0465/)). In TensorFlow, it simply calls the [`tf.matmul()`](../../linalg/matmul) function, so the following lines are equivalent:
```
d = a @ b @ [[10], [11]]
d = tf.matmul(tf.matmul(a, b), [[10], [11]])
```
| Args |
| `a` | [`tf.Tensor`](../../tensor) of type `float16`, `float32`, `float64`, `int32`, `complex64`, `complex128` and rank > 1. |
| `b` | [`tf.Tensor`](../../tensor) with same type and rank as `a`. |
| `transpose_a` | If `True`, `a` is transposed before multiplication. |
| `transpose_b` | If `True`, `b` is transposed before multiplication. |
| `adjoint_a` | If `True`, `a` is conjugated and transposed before multiplication. |
| `adjoint_b` | If `True`, `b` is conjugated and transposed before multiplication. |
| `a_is_sparse` | If `True`, `a` is treated as a sparse matrix. Notice, this **does not support [`tf.sparse.SparseTensor`](../../sparse/sparsetensor)**, it just makes optimizations that assume most values in `a` are zero. See [`tf.sparse.sparse_dense_matmul`](../../sparse/sparse_dense_matmul) for some support for [`tf.sparse.SparseTensor`](../../sparse/sparsetensor) multiplication. |
| `b_is_sparse` | If `True`, `b` is treated as a sparse matrix. Notice, this **does not support [`tf.sparse.SparseTensor`](../../sparse/sparsetensor)**, it just makes optimizations that assume most values in `a` are zero. See [`tf.sparse.sparse_dense_matmul`](../../sparse/sparse_dense_matmul) for some support for [`tf.sparse.SparseTensor`](../../sparse/sparsetensor) multiplication. |
| `output_type` | The output datatype if needed. Defaults to None in which case the output\_type is the same as input type. Currently only works when input tensors are type (u)int8 and output\_type can be int32. |
| `name` | Name for the operation (optional). |
| Returns |
| A [`tf.Tensor`](../../tensor) of the same type as `a` and `b` where each inner-most matrix is the product of the corresponding matrices in `a` and `b`, e.g. if all transpose or adjoint attributes are `False`: `output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j])`, for all indices `i`, `j`. |
| `Note` | This is matrix product, not element-wise product. |
| Raises |
| `ValueError` | If `transpose_a` and `adjoint_a`, or `transpose_b` and `adjoint_b` are both set to `True`. |
| `TypeError` | If output\_type is specified but the types of `a`, `b` and `output_type` is not (u)int8, (u)int8 and int32. |
### `__rmod__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rmod__(
x
)
```
Returns element-wise remainder of division. When `x < 0` xor `y < 0` is
true, this follows Python semantics in that the result here is consistent with a flooring divide. E.g. `floor(x / y) * y + mod(x, y) = x`.
>
> **Note:** [`math.floormod`](https://www.tensorflow.org/api_docs/python/tf/math/floormod) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
| Args |
| `x` | A `Tensor`. Must be one of the following types: `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `bfloat16`, `half`, `float32`, `float64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `x`. |
### `__rmul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rmul__(
x
)
```
Dispatches cwise mul for "Dense*Dense" and "Dense*Sparse".
### `__ror__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__ror__(
x
)
```
### `__rpow__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rpow__(
x
)
```
Computes the power of one value to another.
Given a tensor `x` and a tensor `y`, this operation computes \(x^y\) for corresponding elements in `x` and `y`. For example:
```
x = tf.constant([[2, 2], [3, 3]])
y = tf.constant([[8, 16], [2, 3]])
tf.pow(x, y) # [[256, 65536], [9, 27]]
```
| Args |
| `x` | A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, or `complex128`. |
| `y` | A `Tensor` of type `float16`, `float32`, `float64`, `int32`, `int64`, `complex64`, or `complex128`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. |
### `__rsub__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rsub__(
x
)
```
Returns x - y element-wise.
>
> **Note:** [`tf.subtract`](../../math/subtract) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
Both input and output have a range `(-inf, inf)`.
Example usages below.
Subtract operation between an array and a scalar:
```
x = [1, 2, 3, 4, 5]
y = 1
tf.subtract(x, y)
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
tf.subtract(y, x)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 0, -1, -2, -3, -4], dtype=int32)>
```
Note that binary `-` operator can be used instead:
```
x = tf.convert_to_tensor([1, 2, 3, 4, 5])
y = tf.convert_to_tensor(1)
x - y
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
```
Subtract operation between an array and a tensor of same shape:
```
x = [1, 2, 3, 4, 5]
y = tf.constant([5, 4, 3, 2, 1])
tf.subtract(y, x)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 4, 2, 0, -2, -4], dtype=int32)>
```
For example,
```
x = tf.constant([1, 2], dtype=tf.int8)
y = [2**8 + 1, 2**8 + 2]
tf.subtract(x, y)
<tf.Tensor: shape=(2,), dtype=int8, numpy=array([0, 0], dtype=int8)>
```
When subtracting two input values of different shapes, [`tf.subtract`](../../math/subtract) follows the [general broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules) . The two input array shapes are compared element-wise. Starting with the trailing dimensions, the two dimensions either have to be equal or one of them needs to be `1`.
For example,
```
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(2, 1, 3)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 3), dtype=float64, numpy=
array([[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]])>
```
Example with inputs of different dimensions:
```
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(1, 6)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 6), dtype=float64, numpy=
array([[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]])>
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `x`. |
### `__rtruediv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rtruediv__(
x
)
```
Divides x / y elementwise (using Python 3 division operator semantics).
>
> **Note:** Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
>
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal `x / y` division in Python 3 and in Python 2.7 with `from __future__ import division`. If you want integer division that rounds down, use `x // y` or `tf.math.floordiv`.
`x` and `y` must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32` and `int64` (matching the behavior of Numpy).
| Args |
| `x` | `Tensor` numerator of numeric type. |
| `y` | `Tensor` denominator of numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` evaluated in floating point. |
| Raises |
| `TypeError` | If `x` and `y` have different dtypes. |
### `__rxor__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1435-L1441)
```
__rxor__(
x
)
```
### `__sub__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__sub__(
y
)
```
Returns x - y element-wise.
>
> **Note:** [`tf.subtract`](../../math/subtract) supports broadcasting. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
Both input and output have a range `(-inf, inf)`.
Example usages below.
Subtract operation between an array and a scalar:
```
x = [1, 2, 3, 4, 5]
y = 1
tf.subtract(x, y)
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
tf.subtract(y, x)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 0, -1, -2, -3, -4], dtype=int32)>
```
Note that binary `-` operator can be used instead:
```
x = tf.convert_to_tensor([1, 2, 3, 4, 5])
y = tf.convert_to_tensor(1)
x - y
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([0, 1, 2, 3, 4], dtype=int32)>
```
Subtract operation between an array and a tensor of same shape:
```
x = [1, 2, 3, 4, 5]
y = tf.constant([5, 4, 3, 2, 1])
tf.subtract(y, x)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 4, 2, 0, -2, -4], dtype=int32)>
```
For example,
```
x = tf.constant([1, 2], dtype=tf.int8)
y = [2**8 + 1, 2**8 + 2]
tf.subtract(x, y)
<tf.Tensor: shape=(2,), dtype=int8, numpy=array([0, 0], dtype=int8)>
```
When subtracting two input values of different shapes, [`tf.subtract`](../../math/subtract) follows the [general broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html#general-broadcasting-rules) . The two input array shapes are compared element-wise. Starting with the trailing dimensions, the two dimensions either have to be equal or one of them needs to be `1`.
For example,
```
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(2, 1, 3)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 3), dtype=float64, numpy=
array([[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]],
[[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]]])>
```
Example with inputs of different dimensions:
```
x = np.ones(6).reshape(2, 3, 1)
y = np.ones(6).reshape(1, 6)
tf.subtract(x, y)
<tf.Tensor: shape=(2, 3, 6), dtype=float64, numpy=
array([[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]]])>
```
| Args |
| `x` | A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `uint16`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `uint32`, `uint64`. |
| `y` | A `Tensor`. Must have the same type as `x`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `x`. |
### `__truediv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__truediv__(
y
)
```
Divides x / y elementwise (using Python 3 division operator semantics).
>
> **Note:** Prefer using the Tensor operator or tf.divide which obey Python division operator semantics.
>
This function forces Python 3 division operator semantics where all integer arguments are cast to floating types first. This op is generated by normal `x / y` division in Python 3 and in Python 2.7 with `from __future__ import division`. If you want integer division that rounds down, use `x // y` or `tf.math.floordiv`.
`x` and `y` must have the same numeric type. If the inputs are floating point, the output will have the same type. If the inputs are integral, the inputs are cast to `float32` for `int8` and `int16` and `float64` for `int32` and `int64` (matching the behavior of Numpy).
| Args |
| `x` | `Tensor` numerator of numeric type. |
| `y` | `Tensor` denominator of numeric type. |
| `name` | A name for the operation (optional). |
| Returns |
| `x / y` evaluated in floating point. |
| Raises |
| `TypeError` | If `x` and `y` have different dtypes. |
### `__xor__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/math_ops.py#L1398-L1424)
```
__xor__(
y
)
```
| programming_docs |
tensorflow tf.compat.v1.random_uniform_initializer tf.compat.v1.random\_uniform\_initializer
=========================================
Initializer that generates tensors with a uniform distribution.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.random_uniform`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/random_uniform_initializer)
```
tf.compat.v1.random_uniform_initializer(
minval=0.0,
maxval=None,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy compat.v1 API, this symbol is compatible with eager execution and [`tf.function`](../../function).
To switch to TF2, switch to using either [`tf.initializers.RandomUniform`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/RandomUniform) or [`tf.keras.initializers.RandomUniform`](../../keras/initializers/randomuniform) (neither from [`compat.v1`](../v1)) and pass the dtype when calling the initializer. Keep in mind that the default minval, maxval and the behavior of fixed seeds have changed.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.random_uniform_initializer(
minval=minval,
maxval=maxval,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.initializers.RandomUniform(
minval=minval,
maxval=maxval,
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `minval` | `minval` | Default changes from 0 to -0.05 |
| `maxval` | `maxval` | Default changes from 1.0 to 0.05 |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
| Args |
| `minval` | A python scalar or a scalar tensor. Lower bound of the range of random values to generate. |
| `maxval` | A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L477-L483)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L471-L475)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.get_collection tf.compat.v1.get\_collection
============================
Wrapper for [`Graph.get_collection()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_collection) using the default graph.
```
tf.compat.v1.get_collection(
key, scope=None
)
```
See [`tf.Graph.get_collection`](../../graph#get_collection) for more details.
| Args |
| `key` | The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. |
| `scope` | (Optional.) If supplied, the resulting list is filtered to include only items whose `name` attribute matches using `re.match`. Items without a `name` attribute are never returned if a scope is supplied and the choice or `re.match` means that a `scope` without special tokens filters by prefix. |
| Returns |
| The list of values in the collection with the given `name`, or an empty list if no value has been added to that collection. The list contains the values in the order under which they were collected. |
eager compatibility
-------------------
Collections are not supported when eager execution is enabled.
tensorflow tf.compat.v1.assert_positive tf.compat.v1.assert\_positive
=============================
Assert the condition `x > 0` holds element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_positive`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_positive)
```
tf.compat.v1.assert_positive(
x, data=None, summarize=None, message=None, name=None
)
```
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.debugging.assert_positive(x, y)]):
output = tf.reduce_sum(x)
```
Positive means, for every element `x[i]` of `x`, we have `x[i] > 0`. If `x` is empty this is trivially satisfied.
| Args |
| `x` | Numeric `Tensor`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_positive". |
| Returns |
| Op that raises `InvalidArgumentError` if `x > 0` is False. |
| Raises |
| `InvalidArgumentError` | if the check can be performed immediately and `x > 0` is False. The check can be performed immediately during eager execution or if `x` is statically known. |
eager compatibility
-------------------
returns None
tensorflow tf.compat.v1.enable_control_flow_v2 tf.compat.v1.enable\_control\_flow\_v2
======================================
Use control flow v2.
```
tf.compat.v1.enable_control_flow_v2()
```
control flow v2 (cfv2) is an improved version of control flow in TensorFlow with support for higher order derivatives. Enabling cfv2 will change the graph/function representation of control flow, e.g., [`tf.while_loop`](../../while_loop) and [`tf.cond`](../../cond) will generate functional `While` and `If` ops instead of low-level `Switch`, `Merge` etc. ops. Note: Importing and running graphs exported with old control flow will still be supported.
Calling tf.enable\_control\_flow\_v2() lets you opt-in to this TensorFlow 2.0 feature.
>
> **Note:** v2 control flow is always enabled inside of tf.function. Calling this function is not required.
>
tensorflow tf.compat.v1.convert_to_tensor_or_indexed_slices tf.compat.v1.convert\_to\_tensor\_or\_indexed\_slices
=====================================================
Converts the given object to a `Tensor` or an `IndexedSlices`.
```
tf.compat.v1.convert_to_tensor_or_indexed_slices(
value, dtype=None, name=None
)
```
If `value` is an `IndexedSlices` or `SparseTensor` it is returned unmodified. Otherwise, it is converted to a `Tensor` using `convert_to_tensor()`.
| Args |
| `value` | An `IndexedSlices`, `SparseTensor`, or an object that can be consumed by `convert_to_tensor()`. |
| `dtype` | (Optional.) The required `DType` of the returned `Tensor` or `IndexedSlices`. |
| `name` | (Optional.) A name to use if a new `Tensor` is created. |
| Returns |
| A `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`. |
| Raises |
| `ValueError` | If `dtype` does not match the element type of `value`. |
tensorflow tf.compat.v1.disable_v2_tensorshape tf.compat.v1.disable\_v2\_tensorshape
=====================================
Disables the V2 TensorShape behavior and reverts to V1 behavior.
```
tf.compat.v1.disable_v2_tensorshape()
```
See docstring for `enable_v2_tensorshape` for details about the new behavior.
tensorflow Module: tf.compat.v1.mlir Module: tf.compat.v1.mlir
=========================
Public API for tf.mlir namespace.
Modules
-------
[`experimental`](mlir/experimental) module: Public API for tf.mlir.experimental namespace.
tensorflow tf.compat.v1.quantize_v2 tf.compat.v1.quantize\_v2
=========================
Please use [`tf.quantization.quantize`](../../quantization/quantize) instead.
```
tf.compat.v1.quantize_v2(
input,
min_range,
max_range,
T,
mode='MIN_COMBINED',
name=None,
round_mode='HALF_AWAY_FROM_ZERO',
narrow_range=False,
axis=None,
ensure_minimum_range=0.01
)
```
tensorflow tf.compat.v1.Event tf.compat.v1.Event
==================
A ProtocolMessage
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.summary.Event`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/Event)
| Attributes |
| `file_version` | `string file_version` |
| `graph_def` | `bytes graph_def` |
| `log_message` | `LogMessage log_message` |
| `meta_graph_def` | `bytes meta_graph_def` |
| `session_log` | `SessionLog session_log` |
| `step` | `int64 step` |
| `summary` | `Summary summary` |
| `tagged_run_metadata` | `TaggedRunMetadata tagged_run_metadata` |
| `wall_time` | `double wall_time` |
tensorflow tf.compat.v1.uniform_unit_scaling_initializer tf.compat.v1.uniform\_unit\_scaling\_initializer
================================================
Initializer that generates tensors without scaling variance.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.uniform_unit_scaling`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/uniform_unit_scaling_initializer)
```
tf.compat.v1.uniform_unit_scaling_initializer(
factor=1.0,
seed=None,
dtype=tf.dtypes.float32
)
```
When initializing a deep network, it is in principle advantageous to keep the scale of the input variance constant, so it does not explode or diminish by reaching the final layer. If the input is `x` and the operation `x * W`, and we want to initialize `W` uniformly at random, we need to pick `W` from
```
[-sqrt(3) / sqrt(dim), sqrt(3) / sqrt(dim)]
```
to keep the scale intact, where `dim = W.shape[0]` (the size of the input). A similar calculation for convolutional networks gives an analogous result with `dim` equal to the product of the first 3 dimensions. When nonlinearities are present, we need to multiply this by a constant `factor`. See (Sussillo et al., 2014) for deeper motivation, experiments and the calculation of constants. In section 2.3 there, the constants were numerically computed: for a linear layer it's 1.0, relu: ~1.43, tanh: ~1.15.
| Args |
| `factor` | Float. A multiplicative factor by which the values will be scaled. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
#### References:
[Sussillo et al., 2014](https://arxiv.org/abs/1412.6558) ([pdf](http://arxiv.org/pdf/1412.6558.pdf))
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L736-L737)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L717-L734)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow Module: tf.compat.v1.random Module: tf.compat.v1.random
===========================
Public API for tf.random namespace.
Modules
-------
[`experimental`](random/experimental) module: Public API for tf.random.experimental namespace.
Classes
-------
[`class Algorithm`](../../random/algorithm): An enumeration.
[`class Generator`](../../random/generator): Random-number generator.
Functions
---------
[`all_candidate_sampler(...)`](../../random/all_candidate_sampler): Generate the set of all classes.
[`categorical(...)`](../../random/categorical): Draws samples from a categorical distribution.
[`create_rng_state(...)`](../../random/create_rng_state): Creates a RNG state from an integer or a vector.
[`fixed_unigram_candidate_sampler(...)`](../../random/fixed_unigram_candidate_sampler): Samples a set of classes using the provided (fixed) base distribution.
[`gamma(...)`](../../random/gamma): Draws `shape` samples from each of the given Gamma distribution(s).
[`get_global_generator(...)`](../../random/get_global_generator): Retrieves the global generator.
[`get_seed(...)`](get_seed): Returns the local seeds an operation should use given an op-specific seed.
[`learned_unigram_candidate_sampler(...)`](../../random/learned_unigram_candidate_sampler): Samples a set of classes from a distribution learned during training.
[`log_uniform_candidate_sampler(...)`](../../random/log_uniform_candidate_sampler): Samples a set of classes using a log-uniform (Zipfian) base distribution.
[`multinomial(...)`](multinomial): Draws samples from a multinomial distribution. (deprecated)
[`normal(...)`](../../random/normal): Outputs random values from a normal distribution.
[`poisson(...)`](random_poisson): Draws `shape` samples from each of the given Poisson distribution(s).
[`set_global_generator(...)`](../../random/set_global_generator): Replaces the global generator with another `Generator` object.
[`set_random_seed(...)`](set_random_seed): Sets the graph-level random seed for the default graph.
[`shuffle(...)`](../../random/shuffle): Randomly shuffles a tensor along its first dimension.
[`stateless_binomial(...)`](../../random/stateless_binomial): Outputs deterministic pseudorandom values from a binomial distribution.
[`stateless_categorical(...)`](../../random/stateless_categorical): Draws deterministic pseudorandom samples from a categorical distribution.
[`stateless_gamma(...)`](../../random/stateless_gamma): Outputs deterministic pseudorandom values from a gamma distribution.
[`stateless_multinomial(...)`](random/stateless_multinomial): Draws deterministic pseudorandom samples from a multinomial distribution. (deprecated)
[`stateless_normal(...)`](../../random/stateless_normal): Outputs deterministic pseudorandom values from a normal distribution.
[`stateless_parameterized_truncated_normal(...)`](../../random/stateless_parameterized_truncated_normal): Outputs random values from a truncated normal distribution.
[`stateless_poisson(...)`](../../random/stateless_poisson): Outputs deterministic pseudorandom values from a Poisson distribution.
[`stateless_truncated_normal(...)`](../../random/stateless_truncated_normal): Outputs deterministic pseudorandom values, truncated normally distributed.
[`stateless_uniform(...)`](../../random/stateless_uniform): Outputs deterministic pseudorandom values from a uniform distribution.
[`truncated_normal(...)`](../../random/truncated_normal): Outputs random values from a truncated normal distribution.
[`uniform(...)`](../../random/uniform): Outputs random values from a uniform distribution.
[`uniform_candidate_sampler(...)`](../../random/uniform_candidate_sampler): Samples a set of classes using a uniform base distribution.
tensorflow tf.compat.v1.make_template tf.compat.v1.make\_template
===========================
Given an arbitrary function, wrap it so that it does variable sharing.
```
tf.compat.v1.make_template(
name_,
func_,
create_scope_now_=False,
unique_name_=None,
custom_getter_=None,
**kwargs
)
```
Migrate to TF2
--------------
[`tf.compat.v1.make_template`](make_template) is a legacy API that is only compatible with eager execution enabled and [`tf.function`](../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables). See the model mapping migration guide section on `make_template` for more info:
<https://www.tensorflow.org/guide/migrate/model_mapping#using_tfcompatv1make_template_in_the_decorated_method>
Even if you use legacy apis for `variable_scope`-based variable reuse, we recommend using [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables) directly and not using [`tf.compat.v1.make_template`](make_template), as it interoperates with eager execution in a simpler and more predictable fashion than `make_template`.
The TF2 API approach would be tracking your variables using [`tf.Module`](../../module)s or Keras layers and models rather than relying on `make_template`.
Description
-----------
This wraps `func_` in a Template and partially evaluates it. Templates are functions that create variables the first time they are called and reuse them thereafter. In order for `func_` to be compatible with a `Template` it must have the following properties:
* The function should create all trainable variables and any variables that should be reused by calling [`tf.compat.v1.get_variable`](get_variable). If a trainable variable is created using [`tf.Variable`](../../variable), then a ValueError will be thrown. Variables that are intended to be locals can be created by specifying [`tf.Variable(..., trainable=false)`](../../variable).
* The function may use variable scopes and other templates internally to create and reuse variables, but it shouldn't use [`tf.compat.v1.global_variables`](global_variables) to capture variables that are defined outside of the scope of the function.
* Internal scopes and variable names should not depend on any arguments that are not supplied to `make_template`. In general you will get a ValueError telling you that you are trying to reuse a variable that doesn't exist if you make a mistake.
In the following example, both `z` and `w` will be scaled by the same `y`. It is important to note that if we didn't assign `scalar_name` and used a different name for z and w that a `ValueError` would be thrown because it couldn't reuse the variable.
```
def my_op(x, scalar_name):
var1 = tf.compat.v1.get_variable(scalar_name,
shape=[],
initializer=tf.compat.v1.constant_initializer(1))
return x * var1
scale_by_y = tf.compat.v1.make_template('scale_by_y', my_op, scalar_name='y')
z = scale_by_y(input1)
w = scale_by_y(input2)
```
As a safe-guard, the returned function will raise a `ValueError` after the first call if trainable variables are created by calling [`tf.Variable`](../../variable).
If all of these are true, then 2 properties are enforced by the template:
1. Calling the same template multiple times will share all non-local variables.
2. Two different templates are guaranteed to be unique, unless you reenter the same variable scope as the initial definition of a template and redefine it. An examples of this exception:
```
def my_op(x, scalar_name):
var1 = tf.compat.v1.get_variable(scalar_name,
shape=[],
initializer=tf.compat.v1.constant_initializer(1))
return x * var1
with tf.compat.v1.variable_scope('scope') as vs:
scale_by_y = tf.compat.v1.make_template('scale_by_y', my_op,
scalar_name='y')
z = scale_by_y(input1)
w = scale_by_y(input2)
# Creates a template that reuses the variables above.
with tf.compat.v1.variable_scope(vs, reuse=True):
scale_by_y2 = tf.compat.v1.make_template('scale_by_y', my_op,
scalar_name='y')
z2 = scale_by_y2(input1)
w2 = scale_by_y2(input2)
```
Depending on the value of `create_scope_now_`, the full variable scope may be captured either at the time of first call or at the time of construction. If this option is set to True, then all Tensors created by repeated calls to the template will have an extra trailing \_N+1 to their name, as the first time the scope is entered in the Template constructor no Tensors are created.
>
> **Note:** `name_`, `func_` and `create_scope_now_` have a trailing underscore to reduce the likelihood of collisions with kwargs.
>
| Args |
| `name_` | A name for the scope created by this template. If necessary, the name will be made unique by appending `_N` to the name. |
| `func_` | The function to wrap. |
| `create_scope_now_` | Boolean controlling whether the scope should be created when the template is constructed or when the template is called. Default is False, meaning the scope is created when the template is called. |
| `unique_name_` | When used, it overrides name\_ and is not made unique. If a template of the same scope/unique\_name already exists and reuse is false, an error is raised. Defaults to None. |
| `custom_getter_` | Optional custom getter for variables used in `func_`. See the [`tf.compat.v1.get_variable`](get_variable) `custom_getter` documentation for more information. |
| `**kwargs` | Keyword arguments to apply to `func_`. |
| Returns |
| A function to encapsulate a set of variables which should be created once and reused. An enclosing scope will be created either when `make_template` is called or when the result is called, depending on the value of `create_scope_now_`. Regardless of the value, the first time the template is called it will enter the scope with no reuse, and call `func_` to create variables, which are guaranteed to be unique. All subsequent calls will re-enter the scope and reuse those variables. |
| Raises |
| `ValueError` | if `name_` is None. |
| programming_docs |
tensorflow tf.compat.v1.arg_min tf.compat.v1.arg\_min
=====================
Returns the index with the smallest value across dimensions of a tensor.
```
tf.compat.v1.arg_min(
input,
dimension,
output_type=tf.dtypes.int64,
name=None
)
```
Note that in case of ties the identity of the return value is not guaranteed.
#### Usage:
```
import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.math.argmin(input = a)
c = tf.keras.backend.eval(b)
# c = 0
# here a[0] = 1 which is the smallest element of a across axis 0
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. |
| `dimension` | A `Tensor`. Must be one of the following types: `int32`, `int64`. int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which dimension of the input Tensor to reduce across. For vectors, use dimension = 0. |
| `output_type` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.int32, tf.int64`. Defaults to [`tf.int64`](../../../tf#int64). |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `output_type`. |
tensorflow tf.compat.v1.to_double tf.compat.v1.to\_double
=======================
Casts a tensor to type `float64`. (deprecated)
```
tf.compat.v1.to_double(
x, name='ToDouble'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.double)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_double(tf.constant(3.14, dtype=tf.float32))
<tf.Tensor: shape=(), dtype=float64, numpy=3.14>
```
After:
```
tf.cast(tf.constant(3.14, dtype=tf.float32), tf.double)
<tf.Tensor: shape=(), dtype=float64, numpy=3.14>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `float64`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `float64`. |
tensorflow tf.compat.v1.assert_integer tf.compat.v1.assert\_integer
============================
Assert that `x` is of integer dtype.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_integer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_integer)
```
tf.compat.v1.assert_integer(
x, message=None, name=None
)
```
Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_integer(x)]):
output = tf.reduce_sum(x)
```
| Args |
| `x` | `Tensor` whose basetype is integer and is not quantized. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_integer". |
| Raises |
| `TypeError` | If `x.dtype` is anything other than non-quantized integer. |
| Returns |
| A `no_op` that does nothing. Type can be determined statically. |
tensorflow Module: tf.compat.v1.test Module: tf.compat.v1.test
=========================
Testing.
Classes
-------
[`class Benchmark`](../../test/benchmark): Abstract class that provides helpers for TensorFlow benchmarks.
[`class StubOutForTesting`](test/stuboutfortesting): Support class for stubbing methods out for unit testing.
[`class TestCase`](../../test/testcase): Base class for tests that need to test TensorFlow.
Functions
---------
[`assert_equal_graph_def(...)`](test/assert_equal_graph_def): Asserts that two `GraphDef`s are (mostly) the same.
[`benchmark_config(...)`](../../test/benchmark_config): Returns a tf.compat.v1.ConfigProto for disabling the dependency optimizer.
[`compute_gradient(...)`](test/compute_gradient): Computes and returns the theoretical and numerical Jacobian. (deprecated)
[`compute_gradient_error(...)`](test/compute_gradient_error): Computes the gradient error. (deprecated)
[`create_local_cluster(...)`](../../test/create_local_cluster): Create and start local servers and return the associated `Server` objects.
[`disable_with_predicate(...)`](../../test/disable_with_predicate): Disables the test if pred is true.
[`get_temp_dir(...)`](test/get_temp_dir): Returns a temporary directory for use during tests.
[`gpu_device_name(...)`](../../test/gpu_device_name): Returns the name of a GPU device if available or a empty string.
[`is_built_with_cuda(...)`](../../test/is_built_with_cuda): Returns whether TensorFlow was built with CUDA (GPU) support.
[`is_built_with_gpu_support(...)`](../../test/is_built_with_gpu_support): Returns whether TensorFlow was built with GPU (CUDA or ROCm) support.
[`is_built_with_rocm(...)`](../../test/is_built_with_rocm): Returns whether TensorFlow was built with ROCm (GPU) support.
[`is_built_with_xla(...)`](../../test/is_built_with_xla): Returns whether TensorFlow was built with XLA support.
[`is_gpu_available(...)`](../../test/is_gpu_available): Returns whether TensorFlow can access a GPU. (deprecated)
[`main(...)`](../../test/main): Runs all unit tests.
[`test_src_dir_path(...)`](test/test_src_dir_path): Creates an absolute test srcdir path given a relative path.
[`with_eager_op_as_function(...)`](../../test/with_eager_op_as_function): Adds methods that call original methods with eager\_op\_as\_function enabled.
tensorflow tf.compat.v1.scatter_nd_add tf.compat.v1.scatter\_nd\_add
=============================
Applies sparse addition to individual values or slices in a Variable.
```
tf.compat.v1.scatter_nd_add(
ref, indices, updates, use_locking=False, name=None
)
```
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`. It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]]
```
For example, say we want to add 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that addition would look like this:
```
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
add = tf.compat.v1.scatter_nd_add(ref, indices, updates)
with tf.compat.v1.Session() as sess:
print sess.run(add)
```
The resulting update to ref would look like this:
```
[1, 13, 3, 14, 14, 6, 7, 20]
```
See [`tf.scatter_nd`](../../scatter_nd) for more details about how to make updates to slices.
| Args |
| `ref` | A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. A mutable Tensor. Should be from a Variable node. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into ref. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A tensor of updated values to add to ref. |
| `use_locking` | An optional `bool`. Defaults to `False`. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| A mutable `Tensor`. Has the same type as `ref`. |
tensorflow tf.compat.v1.scatter_mul tf.compat.v1.scatter\_mul
=========================
Multiplies sparse updates into a variable reference.
```
tf.compat.v1.scatter_mul(
ref, indices, updates, use_locking=False, name=None
)
```
This operation computes
```
# Scalar indices
ref[indices, ...] *= updates[...]
# Vector indices (for each i)
ref[indices[i], ...] *= updates[i, ...]
# High rank indices (for each i, ..., j)
ref[indices[i, ..., j], ...] *= updates[i, ..., j, ...]
```
This operation outputs `ref` after the update is done. This makes it easier to chain operations that need to use the reset value.
Duplicate entries are handled correctly: if multiple `indices` reference the same location, their contributions multiply.
Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.
| Args |
| `ref` | A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. Should be from a `Variable` node. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into the first dimension of `ref`. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A tensor of updated values to multiply to `ref`. |
| `use_locking` | An optional `bool`. Defaults to `False`. If True, the operation will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| A mutable `Tensor`. Has the same type as `ref`. |
tensorflow Module: tf.compat.v1.keras Module: tf.compat.v1.keras
==========================
Implementation of the Keras API, the high-level API of TensorFlow.
Detailed documentation and user guides are available at [keras.io](https://keras.io).
Modules
-------
[`activations`](keras/activations) module: Built-in activation functions.
[`applications`](keras/applications) module: Keras Applications are premade architectures with pre-trained weights.
[`backend`](keras/backend) module: Keras backend API.
[`callbacks`](keras/callbacks) module: Callbacks: utilities called at certain points during model training.
[`constraints`](keras/constraints) module: Constraints: functions that impose constraints on weight values.
[`datasets`](keras/datasets) module: Small NumPy datasets for debugging/testing.
[`estimator`](keras/estimator) module: Keras estimator API.
[`experimental`](keras/experimental) module: Public API for tf.keras.experimental namespace.
[`initializers`](keras/initializers) module: Keras initializer serialization / deserialization.
[`layers`](keras/layers) module: Keras layers API.
[`losses`](keras/losses) module: Built-in loss functions.
[`metrics`](keras/metrics) module: All Keras metrics.
[`mixed_precision`](keras/mixed_precision) module: Keras mixed precision API.
[`models`](keras/models) module: Keras models API.
[`optimizers`](keras/optimizers) module: Built-in optimizer classes.
[`preprocessing`](keras/preprocessing) module: Utilities to preprocess data before training.
[`regularizers`](keras/regularizers) module: Built-in regularizers.
[`utils`](keras/utils) module: Public Keras utilities.
[`wrappers`](keras/wrappers) module: Public API for tf.keras.wrappers namespace.
Classes
-------
[`class Model`](../../keras/model): `Model` groups layers into an object with training and inference features.
[`class Sequential`](../../keras/sequential): `Sequential` groups a linear stack of layers into a [`tf.keras.Model`](../../keras/model).
Functions
---------
[`Input(...)`](../../keras/input): `Input()` is used to instantiate a Keras tensor.
tensorflow tf.compat.v1.reset_default_graph tf.compat.v1.reset\_default\_graph
==================================
Clears the default graph stack and resets the global default graph.
```
tf.compat.v1.reset_default_graph()
```
Migrate to TF2
--------------
`reset_default_graph` does not work with either eager execution or [`tf.function`](../../function), and you should not invoke it directly. To migrate code that uses Graph-related functions to TF2, rewrite the code without them. See the [migration guide](https://www.tensorflow.org/guide/migrate) for more description about the behavior and semantic changes between Tensorflow 1 and Tensorflow 2.
Description
-----------
>
> **Note:** The default graph is a property of the current thread. This function applies only to the current thread. Calling this function while a [`tf.compat.v1.Session`](session) or [`tf.compat.v1.InteractiveSession`](interactivesession) is active will result in undefined behavior. Using any previously created [`tf.Operation`](../../operation) or [`tf.Tensor`](../../tensor) objects after calling this function will result in undefined behavior.
>
| Raises |
| `AssertionError` | If this function is called within a nested graph. |
tensorflow Module: tf.compat.v1.experimental Module: tf.compat.v1.experimental
=================================
Public API for tf.experimental namespace.
Classes
-------
[`class BatchableExtensionType`](../../experimental/batchableextensiontype): An ExtensionType that can be batched and unbatched.
[`class DynamicRaggedShape`](../../experimental/dynamicraggedshape): The shape of a ragged or dense tensor.
[`class ExtensionType`](../../experimental/extensiontype): Base class for TensorFlow `ExtensionType` classes.
[`class ExtensionTypeBatchEncoder`](../../experimental/extensiontypebatchencoder): Class used to encode and decode extension type values for batching.
[`class Optional`](../../experimental/optional): Represents a value that may or may not be present.
[`class RowPartition`](../../experimental/rowpartition): Partitioning of a sequence of values into contiguous subsequences ("rows").
Functions
---------
[`async_clear_error(...)`](../../experimental/async_clear_error): Clear pending operations and error statuses in async execution.
[`async_scope(...)`](../../experimental/async_scope): Context manager for grouping async operations.
[`dispatch_for_api(...)`](../../experimental/dispatch_for_api): Decorator that overrides the default implementation for a TensorFlow API.
[`dispatch_for_binary_elementwise_apis(...)`](../../experimental/dispatch_for_binary_elementwise_apis): Decorator to override default implementation for binary elementwise APIs.
[`dispatch_for_unary_elementwise_apis(...)`](../../experimental/dispatch_for_unary_elementwise_apis): Decorator to override default implementation for unary elementwise APIs.
[`function_executor_type(...)`](../../experimental/function_executor_type): Context manager for setting the executor of eager defined functions.
[`output_all_intermediates(...)`](experimental/output_all_intermediates): Whether to output all intermediates from functional control flow ops.
[`register_filesystem_plugin(...)`](../../experimental/register_filesystem_plugin): Loads a TensorFlow FileSystem plugin.
[`unregister_dispatch_for(...)`](../../experimental/unregister_dispatch_for): Unregisters a function that was registered with `@dispatch_for_*`.
tensorflow tf.compat.v1.local_variables_initializer tf.compat.v1.local\_variables\_initializer
==========================================
Returns an Op that initializes all local variables.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.local_variables`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/local_variables_initializer)
```
tf.compat.v1.local_variables_initializer()
```
Migrate to TF2
--------------
In TF2, variables are initialized immediately when they are created. There is no longer a need to run variable initializers before using them.
Description
-----------
This is just a shortcut for `variables_initializer(local_variables())`
| Returns |
| An Op that initializes all local variables in the graph. |
tensorflow Module: tf.compat.v1.autograph Module: tf.compat.v1.autograph
==============================
Conversion of eager-style Python into TensorFlow graph code.
>
> **Note:** In TensorFlow 2.0, AutoGraph is automatically applied when using [`tf.function`](../../function). This module contains lower-level APIs for advanced use.
>
AutoGraph transforms a subset of Python which operates on TensorFlow objects into equivalent TensorFlow graph code. When executing the graph, it has the same effect as if you ran the original code in eager mode. Python code which doesn't operate on TensorFlow objects remains functionally unchanged, but keep in mind that [`tf.function`](../../function) only executes such code at trace time, and generally will not be consistent with eager execution.
For more information, see the [AutoGraph reference documentation](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/autograph/g3doc/reference/index.md), and the [tf.function guide](https://www.tensorflow.org/guide/function#autograph_transformations).
Modules
-------
[`experimental`](autograph/experimental) module: Public API for tf.autograph.experimental namespace.
Functions
---------
[`set_verbosity(...)`](../../autograph/set_verbosity): Sets the AutoGraph verbosity level.
[`to_code(...)`](autograph/to_code): Returns the source code generated by AutoGraph, as a string.
[`to_graph(...)`](autograph/to_graph): Converts a Python entity into a TensorFlow graph.
[`trace(...)`](../../autograph/trace): Traces argument information at compilation time.
tensorflow Module: tf.compat.v1.python_io Module: tf.compat.v1.python\_io
===============================
Python functions for directly manipulating TFRecord-formatted files.
Classes
-------
[`class TFRecordCompressionType`](io/tfrecordcompressiontype): The type of compression for the record.
[`class TFRecordOptions`](../../io/tfrecordoptions): Options used for manipulating TFRecord files.
[`class TFRecordWriter`](../../io/tfrecordwriter): A class to write records to a TFRecords file.
Functions
---------
[`tf_record_iterator(...)`](io/tf_record_iterator): An iterator that read the records from a TFRecords file. (deprecated)
tensorflow tf.compat.v1.reduce_all tf.compat.v1.reduce\_all
========================
Computes [`tf.math.logical_and`](../../math/logical_and) of elements across dimensions of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.reduce_all`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_all)
```
tf.compat.v1.reduce_all(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None
)
```
This is the reduction operation for the elementwise [`tf.math.logical_and`](../../math/logical_and) op.
Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned.
#### For example:
```
x = tf.constant([[True, True], [False, False]])
tf.math.reduce_all(x)
<tf.Tensor: shape=(), dtype=bool, numpy=False>
tf.math.reduce_all(x, 0)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([False, False])>
tf.math.reduce_all(x, 1)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>
```
| Args |
| `input_tensor` | The boolean tensor to reduce. |
| `axis` | The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `name` | A name for the operation (optional). |
| `reduction_indices` | The old (deprecated) name for axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced tensor. |
numpy compatibility
-------------------
Equivalent to np.all
| programming_docs |
tensorflow tf.compat.v1.sparse_segment_sqrt_n tf.compat.v1.sparse\_segment\_sqrt\_n
=====================================
Computes the sum along sparse segments of a tensor divided by the sqrt(N).
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.segment_sqrt_n`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_segment_sqrt_n)
```
tf.compat.v1.sparse_segment_sqrt_n(
data, indices, segment_ids, name=None, num_segments=None
)
```
`N` is the size of the segment being reduced.
| Args |
| `data` | A `Tensor` with data that will be assembled in the output. |
| `indices` | A 1-D `Tensor` with indices into `data`. Has same rank as `segment_ids`. |
| `segment_ids` | A 1-D `Tensor` with indices into the output `Tensor`. Values should be sorted and can be repeated. |
| `name` | A name for the operation (optional). |
| `num_segments` | An optional int32 scalar. Indicates the size of the output `Tensor`. |
| Returns |
| A `tensor` of the shape as data, except for dimension 0 which has size `k`, the number of segments specified via `num_segments` or inferred for the last element in `segments_ids`. |
tensorflow tf.compat.v1.batch_to_space_nd tf.compat.v1.batch\_to\_space\_nd
=================================
BatchToSpace for N-D tensors of type T.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.manip.batch_to_space_nd`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/batch_to_space_nd)
```
tf.compat.v1.batch_to_space_nd(
input, block_shape, crops, name=None
)
```
This operation reshapes the "batch" dimension 0 into `M + 1` dimensions of shape `block_shape + [batch]`, interleaves these blocks back into the grid defined by the spatial dimensions `[1, ..., M]`, to obtain a result with the same rank as the input. The spatial dimensions of this intermediate result are then optionally cropped according to `crops` to produce the output. This is the reverse of SpaceToBatch. See below for a precise description.
| Args |
| `input` | A `Tensor`. N-D with shape `input_shape = [batch] + spatial_shape + remaining_shape`, where spatial\_shape has M dimensions. |
| `block_shape` | A `Tensor`. Must be one of the following types: `int32`, `int64`. 1-D with shape `[M]`, all values must be >= 1. |
| `crops` | A `Tensor`. Must be one of the following types: `int32`, `int64`. 2-D with shape `[M, 2]`, all values must be >= 0. `crops[i] = [crop_start, crop_end]` specifies the amount to crop from input dimension `i + 1`, which corresponds to spatial dimension `i`. It is required that `crop_start[i] + crop_end[i] <= block_shape[i] * input_shape[i + 1]`. This operation is equivalent to the following steps:1. Reshape `input` to `reshaped` of shape: [block\_shape[0], ..., block\_shape[M-1], batch / prod(block\_shape), input\_shape[1], ..., input\_shape[N-1]]
2. Permute dimensions of `reshaped` to produce `permuted` of shape [batch / prod(block\_shape), input\_shape[1], block\_shape[0], ..., input\_shape[M], block\_shape[M-1], input\_shape[M+1], ..., input\_shape[N-1]]
3. Reshape `permuted` to produce `reshaped_permuted` of shape [batch / prod(block\_shape), input\_shape[1] \* block\_shape[0], ..., input\_shape[M] \* block\_shape[M-1], input\_shape[M+1], ..., input\_shape[N-1]]
4. Crop the start and end of dimensions `[1, ..., M]` of `reshaped_permuted` according to `crops` to produce the output of shape: [batch / prod(block\_shape), input\_shape[1] \* block\_shape[0] - crops[0,0] - crops[0,1], ..., input\_shape[M] \* block\_shape[M-1] - crops[M-1,0] - crops[M-1,1], input\_shape[M+1], ..., input\_shape[N-1]]
Some examples: (1) For the following input of shape `[4, 1, 1, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:
```
[[[[1]]], [[[2]]], [[[3]]], [[[4]]]]
```
The output tensor has shape `[1, 2, 2, 1]` and value:
```
x = [[[[1], [2]], [[3], [4]]]]
```
(2) For the following input of shape `[4, 1, 1, 3]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:
```
[[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]]
```
The output tensor has shape `[1, 2, 2, 3]` and value:
```
x = [[[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]]]
```
(3) For the following input of shape `[4, 2, 2, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [0, 0]]`:
```
x = [[[[1], [3]], [[9], [11]]],
[[[2], [4]], [[10], [12]]],
[[[5], [7]], [[13], [15]]],
[[[6], [8]], [[14], [16]]]]
```
The output tensor has shape `[1, 4, 4, 1]` and value:
```
x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]],
[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
```
(4) For the following input of shape `[8, 1, 3, 1]`, `block_shape = [2, 2]`, and `crops = [[0, 0], [2, 0]]`:
```
x = [[[[0], [1], [3]]], [[[0], [9], [11]]],
[[[0], [2], [4]]], [[[0], [10], [12]]],
[[[0], [5], [7]]], [[[0], [13], [15]]],
[[[0], [6], [8]]], [[[0], [14], [16]]]]
```
The output tensor has shape `[2, 2, 4, 1]` and value:
```
x = [[[[1], [2], [3], [4]],
[[5], [6], [7], [8]]],
[[[9], [10], [11], [12]],
[[13], [14], [15], [16]]]]
```
|
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow Module: tf.compat.v1.dtypes Module: tf.compat.v1.dtypes
===========================
Public API for tf.dtypes namespace.
Classes
-------
[`class DType`](../../dtypes/dtype): Represents the type of the elements in a `Tensor`.
Functions
---------
[`as_dtype(...)`](../../dtypes/as_dtype): Converts the given `type_value` to a `DType`.
[`as_string(...)`](../../strings/as_string): Converts each entry in the given tensor to strings.
[`cast(...)`](../../cast): Casts a tensor to a new type.
[`complex(...)`](../../dtypes/complex): Converts two real numbers to a complex number.
[`saturate_cast(...)`](../../dtypes/saturate_cast): Performs a safe saturating cast of `value` to `dtype`.
| Other Members |
| QUANTIZED\_DTYPES |
```
{
tf.qint16,
tf.qint16_ref,
tf.qint32,
tf.qint32_ref,
tf.qint8,
tf.qint8_ref,
tf.quint16,
tf.quint16_ref,
tf.quint8,
tf.quint8_ref
}
```
|
| bfloat16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 16-bit bfloat (brain floating point). |
| bool | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Boolean. |
| complex128 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 128-bit complex. |
| complex64 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 64-bit complex. |
| double | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 64-bit (double precision) floating-point. |
| float16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 16-bit (half precision) floating-point. |
| float32 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 32-bit (single precision) floating-point. |
| float64 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 64-bit (double precision) floating-point. |
| half | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) 16-bit (half precision) floating-point. |
| int16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed 16-bit integer. |
| int32 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed 32-bit integer. |
| int64 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed 64-bit integer. |
| int8 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed 8-bit integer. |
| qint16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed quantized 16-bit integer. |
| qint32 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) signed quantized 32-bit integer. |
| qint8 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Signed quantized 8-bit integer. |
| quint16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned quantized 16-bit integer. |
| quint8 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned quantized 8-bit integer. |
| resource | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Handle to a mutable, dynamically allocated resource. |
| string | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Variable-length string, represented as byte array. |
| uint16 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned 16-bit (word) integer. |
| uint32 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned 32-bit (dword) integer. |
| uint64 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned 64-bit (qword) integer. |
| uint8 | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Unsigned 8-bit (byte) integer. |
| variant | Instance of [`tf.dtypes.DType`](../../dtypes/dtype) Data of arbitrary type (known at runtime). |
tensorflow tf.compat.v1.transpose tf.compat.v1.transpose
======================
Transposes `a`.
```
tf.compat.v1.transpose(
a, perm=None, name='transpose', conjugate=False
)
```
Permutes the dimensions according to `perm`.
The returned tensor's dimension i will correspond to the input dimension `perm[i]`. If `perm` is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors. If conjugate is True and `a.dtype` is either `complex64` or `complex128` then the values of `a` are conjugated and transposed.
#### For example:
```
x = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.transpose(x) # [[1, 4]
# [2, 5]
# [3, 6]]
# Equivalently
tf.transpose(x, perm=[1, 0]) # [[1, 4]
# [2, 5]
# [3, 6]]
# If x is complex, setting conjugate=True gives the conjugate transpose
x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j],
[4 + 4j, 5 + 5j, 6 + 6j]])
tf.transpose(x, conjugate=True) # [[1 - 1j, 4 - 4j],
# [2 - 2j, 5 - 5j],
# [3 - 3j, 6 - 6j]]
# 'perm' is more useful for n-dimensional tensors, for n > 2
x = tf.constant([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
# Take the transpose of the matrices in dimension-0
# (this common operation has a shorthand `linalg.matrix_transpose`)
tf.transpose(x, perm=[0, 2, 1]) # [[[1, 4],
# [2, 5],
# [3, 6]],
# [[7, 10],
# [8, 11],
# [9, 12]]]
```
| Args |
| `a` | A `Tensor`. |
| `perm` | A permutation of the dimensions of `a`. |
| `name` | A name for the operation (optional). |
| `conjugate` | Optional bool. Setting it to `True` is mathematically equivalent to tf.math.conj(tf.transpose(input)). |
| Returns |
| A transposed `Tensor`. |
numpy compatibility
-------------------
In `numpy` transposes are memory-efficient constant time operations as they simply return a new view of the same data with adjusted `strides`.
TensorFlow does not support strides, so `transpose` returns a new tensor with the items permuted.
tensorflow tf.compat.v1.model_variables tf.compat.v1.model\_variables
=============================
Returns all variables in the MODEL\_VARIABLES collection.
```
tf.compat.v1.model_variables(
scope=None
)
```
| Args |
| `scope` | (Optional.) A string. If supplied, the resulting list is filtered to include only items whose `name` attribute matches `scope` using `re.match`. Items without a `name` attribute are never returned if a scope is supplied. The choice of `re.match` means that a `scope` without special tokens filters by prefix. |
| Returns |
| A list of local Variable objects. |
tensorflow tf.compat.v1.InteractiveSession tf.compat.v1.InteractiveSession
===============================
A TensorFlow `Session` for use in interactive contexts, such as a shell.
```
tf.compat.v1.InteractiveSession(
target='', graph=None, config=None
)
```
The only difference with a regular `Session` is that an `InteractiveSession` installs itself as the default session on construction. The methods [`tf.Tensor.eval`](../../tensor#eval) and [`tf.Operation.run`](../../operation#run) will use that session to run ops.
This is convenient in interactive shells and [IPython notebooks](http://ipython.org), as it avoids having to pass an explicit `Session` object to run ops.
#### For example:
```
sess = tf.compat.v1.InteractiveSession()
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# We can just use 'c.eval()' without passing 'sess'
print(c.eval())
sess.close()
```
Note that a regular session installs itself as the default session when it is created in a `with` statement. The common usage in non-interactive programs is to follow that pattern:
```
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
with tf.compat.v1.Session():
# We can also use 'c.eval()' here.
print(c.eval())
```
| Args |
| `target` | (Optional.) The execution engine to connect to. Defaults to using an in-process engine. |
| `graph` | (Optional.) The `Graph` to be launched (described above). |
| `config` | (Optional) `ConfigProto` proto used to configure the session. |
| Attributes |
| `graph` | The graph that was launched in this session. |
| `graph_def` | A serializable version of the underlying TensorFlow graph. |
| `sess_str` | The TensorFlow process to which this session will connect. |
Methods
-------
### `as_default`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L803-L856)
```
as_default()
```
Returns a context manager that makes this object the default session.
Use with the `with` keyword to specify that calls to [`tf.Operation.run`](../../operation#run) or [`tf.Tensor.eval`](../../tensor#eval) should be executed in this session.
```
c = tf.constant(..)
sess = tf.compat.v1.Session()
with sess.as_default():
assert tf.compat.v1.get_default_session() is sess
print(c.eval())
```
To get the current default session, use [`tf.compat.v1.get_default_session`](get_default_session).
>
> **Note:** The `as_default` context manager *does not* close the session when you exit the context, and you must close the session explicitly.
>
```
c = tf.constant(...)
sess = tf.compat.v1.Session()
with sess.as_default():
print(c.eval())
# ...
with sess.as_default():
print(c.eval())
sess.close()
```
Alternatively, you can use `with tf.compat.v1.Session():` to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised.
>
> **Note:** The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function.
>
>
> **Note:** Entering a `with sess.as_default():` block does not affect the current default graph. If you are using multiple graphs, and `sess.graph` is different from the value of [`tf.compat.v1.get_default_graph`](get_default_graph), you must explicitly enter a `with sess.graph.as_default():` block to make `sess.graph` the default graph.
>
| Returns |
| A context manager using this session as the default session. |
### `close`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1788-L1801)
```
close()
```
Closes an `InteractiveSession`.
### `list_devices`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L716-L752)
```
list_devices()
```
Lists available devices in this session.
```
devices = sess.list_devices()
for d in devices:
print(d.name)
```
#### Where:
Each element in the list has the following properties
* **`name`**: A string with the full name of the device. ex: `/job:worker/replica:0/task:3/device:CPU:0`
* **`device_type`**: The type of the device (e.g. `CPU`, `GPU`, `TPU`.)
* **`memory_limit`**: The maximum amount of memory available on the device. Note: depending on the device, it is possible the usable memory could be substantially less.
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If it encounters an error (e.g. session is in an invalid state, or network errors occur). |
| Returns |
| A list of devices in the session. |
### `make_callable`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1196-L1320)
```
make_callable(
fetches, feed_list=None, accept_options=False
)
```
Returns a Python callable that runs a particular step.
The returned callable will take `len(feed_list)` arguments whose types must be compatible feed values for the respective elements of `feed_list`. For example, if element `i` of `feed_list` is a [`tf.Tensor`](../../tensor), the `i`th argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See `tf.Session.run` for details of the allowable feed key and value types.
The returned callable will have the same return type as `tf.Session.run(fetches, ...)`. For example, if `fetches` is a [`tf.Tensor`](../../tensor), the callable will return a numpy ndarray; if `fetches` is a [`tf.Operation`](../../operation), it will return `None`.
| Args |
| `fetches` | A value or list of values to fetch. See `tf.Session.run` for details of the allowable fetch types. |
| `feed_list` | (Optional.) A list of `feed_dict` keys. See `tf.Session.run` for details of the allowable feed key types. |
| `accept_options` | (Optional.) If `True`, the returned `Callable` will be able to accept [`tf.compat.v1.RunOptions`](runoptions) and [`tf.compat.v1.RunMetadata`](runmetadata) as optional keyword arguments `options` and `run_metadata`, respectively, with the same syntax and semantics as `tf.Session.run`, which is useful for certain use cases (profiling and debugging) but will result in measurable slowdown of the `Callable`'s performance. Default: `False`. |
| Returns |
| A function that when called will execute the step defined by `feed_list` and `fetches` in this session. |
| Raises |
| `TypeError` | If `fetches` or `feed_list` cannot be interpreted as arguments to `tf.Session.run`. |
### `partial_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L979-L1024)
```
partial_run(
handle, fetches, feed_dict=None
)
```
Continues the execution with more feeds and fetches.
This is EXPERIMENTAL and subject to change.
To use partial execution, a user first calls `partial_run_setup()` and then a sequence of `partial_run()`. `partial_run_setup` specifies the list of feeds and fetches that will be used in the subsequent `partial_run` calls.
The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. See run() for more information.
Below is a simple example:
```
a = array_ops.placeholder(dtypes.float32, shape=[])
b = array_ops.placeholder(dtypes.float32, shape=[])
c = array_ops.placeholder(dtypes.float32, shape=[])
r1 = math_ops.add(a, b)
r2 = math_ops.multiply(r1, c)
h = sess.partial_run_setup([r1, r2], [a, b, c])
res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})
res = sess.partial_run(h, r2, feed_dict={c: res})
```
| Args |
| `handle` | A handle for a sequence of partial runs. |
| `fetches` | A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (see documentation for `run`). |
| `feed_dict` | A dictionary that maps graph elements to values (described above). |
| Returns |
| Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (see documentation for `run`). |
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses on error. |
### `partial_run_setup`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1026-L1101)
```
partial_run_setup(
fetches, feeds=None
)
```
Sets up a graph with feeds and fetches for partial run.
This is EXPERIMENTAL and subject to change.
Note that contrary to `run`, `feeds` only specifies the graph elements. The tensors will be supplied by the subsequent `partial_run` calls.
| Args |
| `fetches` | A single graph element, or a list of graph elements. |
| `feeds` | A single graph element, or a list of graph elements. |
| Returns |
| A handle for partial run. |
| Raises |
| `RuntimeError` | If this `Session` is in an invalid state (e.g. has been closed). |
| `TypeError` | If `fetches` or `feed_dict` keys are of an inappropriate type. |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses if a TensorFlow error happens. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L858-L977)
```
run(
fetches, feed_dict=None, options=None, run_metadata=None
)
```
Runs operations and evaluates tensors in `fetches`.
This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every `Operation` and evaluate every `Tensor` in `fetches`, substituting the values in `feed_dict` for the corresponding input values.
The `fetches` argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types:
* A [`tf.Operation`](../../operation). The corresponding fetched value will be `None`.
* A [`tf.Tensor`](../../tensor). The corresponding fetched value will be a numpy ndarray containing the value of that tensor.
* A [`tf.sparse.SparseTensor`](../../sparse/sparsetensor). The corresponding fetched value will be a [`tf.compat.v1.SparseTensorValue`](sparsetensorvalue) containing the value of that sparse tensor.
* A `get_tensor_handle` op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.
* A `string` which is the name of a tensor or operation in the graph.
The value returned by `run()` has the same shape as the `fetches` argument, where the leaves are replaced by the corresponding values returned by TensorFlow.
#### Example:
```
a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
# 'fetches' can be a singleton
v = session.run(a)
# v is the numpy array [10, 20]
# 'fetches' can be a list.
v = session.run([a, b])
# v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the
# 1-D array [1.0, 2.0]
# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
MyData = collections.namedtuple('MyData', ['a', 'b'])
v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
# v is a dict with
# v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and
# 'b' (the numpy array [1.0, 2.0])
# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
# [10, 20].
```
The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. Each key in `feed_dict` can be one of the following types:
* If the key is a [`tf.Tensor`](../../tensor), the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same `dtype` as that tensor. Additionally, if the key is a [`tf.compat.v1.placeholder`](placeholder), the shape of the value will be checked for compatibility with the placeholder.
* If the key is a [`tf.sparse.SparseTensor`](../../sparse/sparsetensor), the value should be a [`tf.compat.v1.SparseTensorValue`](sparsetensorvalue).
* If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value should be a nested tuple with the same structure that maps to their corresponding values as above.
Each value in `feed_dict` must be convertible to a numpy array of the dtype of the corresponding key.
The optional `options` argument expects a [`RunOptions`] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).
The optional `run_metadata` argument expects a [`RunMetadata`] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in `options`, the profiled info will be collected into this argument and passed back.
| Args |
| `fetches` | A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above). |
| `feed_dict` | A dictionary that maps graph elements to values (described above). |
| `options` | A [`RunOptions`] protocol buffer |
| `run_metadata` | A [`RunMetadata`] protocol buffer |
| Returns |
| Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (described above). Order in which `fetches` operations are evaluated inside the call is undefined. |
| Raises |
| `RuntimeError` | If this `Session` is in an invalid state (e.g. has been closed). |
| `TypeError` | If `fetches` or `feed_dict` keys are of an inappropriate type. |
| `ValueError` | If `fetches` or `feed_dict` keys are invalid or refer to a `Tensor` that doesn't exist. |
| programming_docs |
tensorflow tf.compat.v1.Dimension tf.compat.v1.Dimension
======================
Represents the value of one dimension in a TensorShape.
```
tf.compat.v1.Dimension(
value
)
```
Migrate to TF2
--------------
In TF2, members of a `TensorShape` object are integers. The `Dimension` class is not part of TF2's data model.
Please refer to the [TensorShape section of the migration guide](https://www.tensorflow.org/guide/migrate/index#tensorshape) on common code patterns adapting Dimension objects to a TF2 syntax.
Description
-----------
| Attributes |
| `value` | The value of this dimension, or None if it is unknown. |
Methods
-------
### `assert_is_compatible_with`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L287-L299)
```
assert_is_compatible_with(
other
)
```
Raises an exception if `other` is not compatible with this Dimension.
| Args |
| `other` | Another Dimension. |
| Raises |
| `ValueError` | If `self` and `other` are not compatible (see is\_compatible\_with). |
### `is_compatible_with`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L271-L285)
```
is_compatible_with(
other
)
```
Returns true if `other` is compatible with this Dimension.
Two known Dimensions are compatible if they have the same value. An unknown Dimension is compatible with all other Dimensions.
| Args |
| `other` | Another Dimension. |
| Returns |
| True if this Dimension and `other` are compatible. |
### `merge_with`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L301-L336)
```
merge_with(
other
)
```
Returns a Dimension that combines the information in `self` and `other`.
Dimensions are combined as follows:
```
tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(n)) ==
tf.compat.v1.Dimension(n)
tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(None)) ==
tf.compat.v1.Dimension(n)
tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(n)) ==
tf.compat.v1.Dimension(n)
# equivalent to tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None).merge_with(tf.compat.v1.Dimension(None))
# raises ValueError for n != m
tf.compat.v1.Dimension(n) .merge_with(tf.compat.v1.Dimension(m))
```
| Args |
| `other` | Another Dimension. |
| Returns |
| A Dimension containing the combined information of `self` and `other`. |
| Raises |
| `ValueError` | If `self` and `other` are not compatible (see is\_compatible\_with). |
### `__add__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L338-L367)
```
__add__(
other
)
```
Returns the sum of `self` and `other`.
Dimensions are summed as follows:
```
tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m + n)
tf.compat.v1.Dimension(m) + tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(n) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) + tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
```
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the sum of `self` and `other`. |
### `__bool__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L249-L251)
```
__bool__()
```
Equivalent to `bool(self.value)`.
### `__div__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L515-L529)
```
__div__(
other
)
```
This function exists only for backwards compatibility purposes; new code should use `__floordiv__` via the syntax `x // y`. Using `x // y` communicates clearly that the result rounds down, and is forward compatible to Python 3.
| Args |
| `other` | Another `Dimension`. |
| Returns |
| A `Dimension` whose value is the integer quotient of `self` and `other`. |
### `__eq__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L229-L237)
```
__eq__(
other
)
```
Returns true if `other` has the same known value as this Dimension.
### `__floordiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L469-L498)
```
__floordiv__(
other
)
```
Returns the quotient of `self` and `other` rounded down.
Dimensions are divided as follows:
```
tf.compat.v1.Dimension(m) // tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m // n)
tf.compat.v1.Dimension(m) // tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(n) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) // tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
```
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A `Dimension` whose value is the integer quotient of `self` and `other`. |
### `__ge__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L694-L717)
```
__ge__(
other
)
```
Returns True if `self` is known to be greater than or equal to `other`.
Dimensions are compared as follows:
```
(tf.compat.v1.Dimension(m) >= tf.compat.v1.Dimension(n)) == (m >= n)
(tf.compat.v1.Dimension(m) >= tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(n)) == None
(tf.compat.v1.Dimension(None) >= tf.compat.v1.Dimension(None)) == None
```
| Args |
| `other` | Another Dimension. |
| Returns |
| The value of `self.value >= other.value` if both are known, otherwise None. |
### `__gt__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L669-L692)
```
__gt__(
other
)
```
Returns True if `self` is known to be greater than `other`.
Dimensions are compared as follows:
```
(tf.compat.v1.Dimension(m) > tf.compat.v1.Dimension(n)) == (m > n)
(tf.compat.v1.Dimension(m) > tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(n)) == None
(tf.compat.v1.Dimension(None) > tf.compat.v1.Dimension(None)) == None
```
| Args |
| `other` | Another Dimension. |
| Returns |
| The value of `self.value > other.value` if both are known, otherwise None. |
### `__le__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L644-L667)
```
__le__(
other
)
```
Returns True if `self` is known to be less than or equal to `other`.
Dimensions are compared as follows:
```
(tf.compat.v1.Dimension(m) <= tf.compat.v1.Dimension(n)) == (m <= n)
(tf.compat.v1.Dimension(m) <= tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(n)) == None
(tf.compat.v1.Dimension(None) <= tf.compat.v1.Dimension(None)) == None
```
| Args |
| `other` | Another Dimension. |
| Returns |
| The value of `self.value <= other.value` if both are known, otherwise None. |
### `__lt__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L619-L642)
```
__lt__(
other
)
```
Returns True if `self` is known to be less than `other`.
Dimensions are compared as follows:
```
(tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(n)) == (m < n)
(tf.compat.v1.Dimension(m) < tf.compat.v1.Dimension(None)) == None
(tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(n)) == None
(tf.compat.v1.Dimension(None) < tf.compat.v1.Dimension(None)) == None
```
| Args |
| `other` | Another Dimension. |
| Returns |
| The value of `self.value < other.value` if both are known, otherwise None. |
### `__mod__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L579-L605)
```
__mod__(
other
)
```
Returns `self` modulo `other`.
Dimension modulo are computed as follows:
```
tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m % n)
tf.compat.v1.Dimension(m) % tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(n) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) % tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
```
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is `self` modulo `other`. |
### `__mul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L426-L456)
```
__mul__(
other
)
```
Returns the product of `self` and `other`.
Dimensions are summed as follows:
```
tf.compat.v1.Dimension(m) * tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m * n)
tf.compat.v1.Dimension(m) * tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(n) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) * tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
```
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the product of `self` and `other`. |
### `__ne__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L239-L247)
```
__ne__(
other
)
```
Returns true if `other` has a different known value from `self`.
### `__radd__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L369-L378)
```
__radd__(
other
)
```
Returns the sum of `other` and `self`.
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the sum of `self` and `other`. |
### `__rdiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L531-L545)
```
__rdiv__(
other
)
```
Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of: `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`, this function will explicitly call for usage of `//` instead.
| Args |
| `other` | Another `Dimension`. |
| Raises |
| TypeError. |
### `__rfloordiv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L500-L513)
```
__rfloordiv__(
other
)
```
Returns the quotient of `other` and `self` rounded down.
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A `Dimension` whose value is the integer quotient of `self` and `other`. |
### `__rmod__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L607-L617)
```
__rmod__(
other
)
```
Returns `other` modulo `self`.
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is `other` modulo `self`. |
### `__rmul__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L458-L467)
```
__rmul__(
other
)
```
Returns the product of `self` and `other`.
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the product of `self` and `other`. |
### `__rsub__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L411-L424)
```
__rsub__(
other
)
```
Returns the subtraction of `self` from `other`.
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the subtraction of `self` from `other`. |
### `__rtruediv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L563-L577)
```
__rtruediv__(
other
)
```
Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of: `TypeError: unsupported operand type(s) for /: 'int' and 'Dimension'`, this function will explicitly call for usage of `//` instead.
| Args |
| `other` | Another `Dimension`. |
| Raises |
| TypeError. |
### `__sub__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L380-L409)
```
__sub__(
other
)
```
Returns the subtraction of `other` from `self`.
Dimensions are subtracted as follows:
```
tf.compat.v1.Dimension(m) - tf.compat.v1.Dimension(n) ==
tf.compat.v1.Dimension(m - n)
tf.compat.v1.Dimension(m) - tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(n) # equiv. to
tf.compat.v1.Dimension(None)
tf.compat.v1.Dimension(None) - tf.compat.v1.Dimension(None) # equiv. to
tf.compat.v1.Dimension(None)
```
| Args |
| `other` | Another Dimension, or a value accepted by `as_dimension`. |
| Returns |
| A Dimension whose value is the subtraction of `other` from `self`. |
### `__truediv__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/tensor_shape.py#L547-L561)
```
__truediv__(
other
)
```
Use `__floordiv__` via `x // y` instead.
This function exists only to have a better error message. Instead of: `TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'`, this function will explicitly call for usage of `//` instead.
| Args |
| `other` | Another `Dimension`. |
| Raises |
| TypeError. |
tensorflow tf.compat.v1.py_func tf.compat.v1.py\_func
=====================
Wraps a python function and uses it as a TensorFlow op.
```
tf.compat.v1.py_func(
func, inp, Tout, stateful=True, name=None
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but [`tf.numpy_function`](../../numpy_function) is a near-exact replacement, just drop the `stateful` argument (all [`tf.numpy_function`](../../numpy_function) calls are considered stateful). It is compatible with eager execution and [`tf.function`](../../function).
[`tf.py_function`](../../py_function) is a close but not an exact replacement, passing TensorFlow tensors to the wrapped function instead of NumPy arrays, which provides gradients and can take advantage of accelerators.
Before:
```
def fn_using_numpy(x):
x[0] = 0.
return x
tf.compat.v1.py_func(fn_using_numpy, inp=[tf.constant([1., 2.])],
Tout=tf.float32, stateful=False)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)>
```
After:
```
tf.numpy_function(fn_using_numpy, inp=[tf.constant([1., 2.])],
Tout=tf.float32)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)>
```
Description
-----------
Given a python function `func`, which takes numpy arrays as its arguments and returns numpy arrays as its outputs, wrap this function as an operation in a TensorFlow graph. The following snippet constructs a simple TensorFlow graph that invokes the `np.sinh()` NumPy function as a operation in the graph:
```
def my_func(x):
# x will be a numpy array with the contents of the placeholder below
return np.sinh(x)
input = tf.compat.v1.placeholder(tf.float32)
y = tf.compat.v1.py_func(my_func, [input], tf.float32)
```
>
> **Note:** The [`tf.compat.v1.py_func()`](py_func) operation has the following known limitations:
>
* The body of the function (i.e. `func`) will not be serialized in a `GraphDef`. Therefore, you should not use this function if you need to serialize your model and restore it in a different environment.
* The operation must run in the same address space as the Python program that calls [`tf.compat.v1.py_func()`](py_func). If you are using distributed TensorFlow, you must run a [`tf.distribute.Server`](../../distribute/server) in the same process as the program that calls [`tf.compat.v1.py_func()`](py_func) and you must pin the created operation to a device in that server (e.g. using `with tf.device():`).
>
> **Note:** It produces tensors of unknown shape and rank as shape inference does not work on arbitrary Python code. If you need the shape, you need to set it based on statically available information.
>
E.g.
```
import tensorflow as tf
import numpy as np
def make_synthetic_data(i):
return np.cast[np.uint8](i) * np.ones([20,256,256,3],
dtype=np.float32) / 10.
def preprocess_fn(i):
ones = tf.py_function(make_synthetic_data,[i],tf.float32)
ones.set_shape(tf.TensorShape([None, None, None, None]))
ones = tf.image.resize(ones, [224,224])
return ones
ds = tf.data.Dataset.range(10)
ds = ds.map(preprocess_fn)
```
| Args |
| `func` | A Python function, which accepts `ndarray` objects as arguments and returns a list of `ndarray` objects (or a single `ndarray`). This function must accept as many arguments as there are tensors in `inp`, and these argument types will match the corresponding [`tf.Tensor`](../../tensor) objects in `inp`. The returns `ndarray`s must match the number and types defined `Tout`. Important Note: Input and output numpy `ndarray`s of `func` are not guaranteed to be copies. In some cases their underlying memory will be shared with the corresponding TensorFlow tensors. In-place modification or storing `func` input or return values in python datastructures without explicit (np.)copy can have non-deterministic consequences. |
| `inp` | A list of `Tensor` objects. |
| `Tout` | A list or tuple of tensorflow data types or a single tensorflow data type if there is only one, indicating what `func` returns. |
| `stateful` | (Boolean.) If True, the function should be considered stateful. If a function is stateless, when given the same input it will return the same output and have no observable side effects. Optimizations such as common subexpression elimination are only performed on stateless operations. |
| `name` | A name for the operation (optional). |
| Returns |
| A list of `Tensor` or a single `Tensor` which `func` computes. |
tensorflow tf.compat.v1.scatter_update tf.compat.v1.scatter\_update
============================
Applies sparse updates to a variable reference.
```
tf.compat.v1.scatter_update(
ref, indices, updates, use_locking=True, name=None
)
```
This operation computes
```
# Scalar indices
ref[indices, ...] = updates[...]
# Vector indices (for each i)
ref[indices[i], ...] = updates[i, ...]
# High rank indices (for each i, ..., j)
ref[indices[i, ..., j], ...] = updates[i, ..., j, ...]
```
This operation outputs `ref` after the update is done. This makes it easier to chain operations that need to use the reset value.
If values in `ref` is to be updated more than once, because there are duplicate entries in `indices`, the order at which the updates happen for each value is undefined.
Requires `updates.shape = indices.shape + ref.shape[1:]`.
| Args |
| `ref` | A `Variable`. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into the first dimension of `ref`. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A tensor of updated values to store in `ref`. |
| `use_locking` | An optional `bool`. Defaults to `True`. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| Same as `ref`. Returned as a convenience for operations that want to use the updated values after the update is done. |
| programming_docs |
tensorflow tf.compat.v1.arg_max tf.compat.v1.arg\_max
=====================
Returns the index with the largest value across dimensions of a tensor.
```
tf.compat.v1.arg_max(
input,
dimension,
output_type=tf.dtypes.int64,
name=None
)
```
Note that in case of ties the identity of the return value is not guaranteed.
#### Usage:
```
import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.math.argmax(input = a)
c = tf.keras.backend.eval(b)
# c = 4
# here a[4] = 166.32 which is the largest element of a across axis 0
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. |
| `dimension` | A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. int16, int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which dimension of the input Tensor to reduce across. For vectors, use dimension = 0. |
| `output_type` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.int16, tf.uint16, tf.int32, tf.int64`. Defaults to [`tf.int64`](../../../tf#int64). |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `output_type`. |
tensorflow tf.compat.v1.gather tf.compat.v1.gather
===================
Gather slices from params axis `axis` according to indices. (deprecated arguments)
```
tf.compat.v1.gather(
params, indices, validate_indices=None, name=None, axis=None, batch_dims=0
)
```
Gather slices from `params` axis `axis` according to `indices`. `indices` must be an integer tensor of any dimension (often 1-D).
[`Tensor.**getitem**`](https://www.tensorflow.org/api_docs/python/tf/Tensor#__getitem__) works for scalars, [`tf.newaxis`](../../../tf#newaxis), and [python slices](https://numpy.org/doc/stable/reference/arrays.indexing.html#basic-slicing-and-indexing)
[`tf.gather`](../../gather) extends indexing to handle tensors of indices.
In the simplest case it's identical to scalar indexing:
```
params = tf.constant(['p0', 'p1', 'p2', 'p3', 'p4', 'p5'])
params[3].numpy()
b'p3'
tf.gather(params, 3).numpy()
b'p3'
```
The most common case is to pass a single axis tensor of indices (this can't be expressed as a python slice because the indices are not sequential):
```
indices = [2, 0, 2, 5]
tf.gather(params, indices).numpy()
array([b'p2', b'p0', b'p2', b'p5'], dtype=object)
```
The indices can have any shape. When the `params` has 1 axis, the output shape is equal to the input shape:
```
tf.gather(params, [[2, 0], [2, 5]]).numpy()
array([[b'p2', b'p0'],
[b'p2', b'p5']], dtype=object)
```
The `params` may also have any shape. `gather` can select slices across any axis depending on the `axis` argument (which defaults to 0). Below it is used to gather first rows, then columns from a matrix:
```
params = tf.constant([[0, 1.0, 2.0],
[10.0, 11.0, 12.0],
[20.0, 21.0, 22.0],
[30.0, 31.0, 32.0]])
tf.gather(params, indices=[3,1]).numpy()
array([[30., 31., 32.],
[10., 11., 12.]], dtype=float32)
tf.gather(params, indices=[2,1], axis=1).numpy()
array([[ 2., 1.],
[12., 11.],
[22., 21.],
[32., 31.]], dtype=float32)
```
More generally: The output shape has the same shape as the input, with the indexed-axis replaced by the shape of the indices.
```
def result_shape(p_shape, i_shape, axis=0):
return p_shape[:axis] + i_shape + p_shape[axis+1:]
result_shape([1, 2, 3], [], axis=1)
[1, 3]
result_shape([1, 2, 3], [7], axis=1)
[1, 7, 3]
result_shape([1, 2, 3], [7, 5], axis=1)
[1, 7, 5, 3]
```
Here are some examples:
```
params.shape.as_list()
[4, 3]
indices = tf.constant([[0, 2]])
tf.gather(params, indices=indices, axis=0).shape.as_list()
[1, 2, 3]
tf.gather(params, indices=indices, axis=1).shape.as_list()
[4, 1, 2]
```
```
params = tf.random.normal(shape=(5, 6, 7, 8))
indices = tf.random.uniform(shape=(10, 11), maxval=7, dtype=tf.int32)
result = tf.gather(params, indices, axis=2)
result.shape.as_list()
[5, 6, 10, 11, 8]
```
This is because each index takes a slice from `params`, and places it at the corresponding location in the output. For the above example
```
# For any location in indices
a, b = 0, 1
tf.reduce_all(
# the corresponding slice of the result
result[:, :, a, b, :] ==
# is equal to the slice of `params` along `axis` at the index.
params[:, :, indices[a, b], :]
).numpy()
True
```
### Batching:
The `batch_dims` argument lets you gather different items from each element of a batch.
Using `batch_dims=1` is equivalent to having an outer loop over the first axis of `params` and `indices`:
```
params = tf.constant([
[0, 0, 1, 0, 2],
[3, 0, 0, 0, 4],
[0, 5, 0, 6, 0]])
indices = tf.constant([
[2, 4],
[0, 4],
[1, 3]])
```
```
tf.gather(params, indices, axis=1, batch_dims=1).numpy()
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)
```
#### This is equivalent to:
```
def manually_batched_gather(params, indices, axis):
batch_dims=1
result = []
for p,i in zip(params, indices):
r = tf.gather(p, i, axis=axis-batch_dims)
result.append(r)
return tf.stack(result)
manually_batched_gather(params, indices, axis=1).numpy()
array([[1, 2],
[3, 4],
[5, 6]], dtype=int32)
```
Higher values of `batch_dims` are equivalent to multiple nested loops over the outer axes of `params` and `indices`. So the overall shape function is
```
def batched_result_shape(p_shape, i_shape, axis=0, batch_dims=0):
return p_shape[:axis] + i_shape[batch_dims:] + p_shape[axis+1:]
batched_result_shape(
p_shape=params.shape.as_list(),
i_shape=indices.shape.as_list(),
axis=1,
batch_dims=1)
[3, 2]
```
```
tf.gather(params, indices, axis=1, batch_dims=1).shape.as_list()
[3, 2]
```
This comes up naturally if you need to use the indices of an operation like [`tf.argsort`](../../argsort), or [`tf.math.top_k`](../../math/top_k) where the last dimension of the indices indexes into the last dimension of input, at the corresponding location. In this case you can use `tf.gather(values, indices, batch_dims=-1)`.
#### See also:
* [`tf.Tensor.**getitem**`](../../tensor#__getitem__): The direct tensor index operation (`t[]`), handles scalars and python-slices `tensor[..., 7, 1:-1]`
* `tf.scatter`: A collection of operations similar to `__setitem__` (`t[i] = x`)
* [`tf.gather_nd`](../../gather_nd): An operation similar to [`tf.gather`](../../gather) but gathers across multiple axis at once (it can gather elements of a matrix instead of rows or columns)
* [`tf.boolean_mask`](../../boolean_mask), [`tf.where`](../../where): Binary indexing.
* [`tf.slice`](../../slice) and [`tf.strided_slice`](../../strided_slice): For lower level access to the implementation of `__getitem__`'s python-slice handling (`t[1:-1:2]`)
| Args |
| `params` | The `Tensor` from which to gather values. Must be at least rank `axis + 1`. |
| `indices` | The index `Tensor`. Must be one of the following types: `int32`, `int64`. The values must be in range `[0, params.shape[axis])`. |
| `validate_indices` | Deprecated, does nothing. Indices are always validated on CPU, never validated on GPU.
|
| `axis` | A `Tensor`. Must be one of the following types: `int32`, `int64`. The `axis` in `params` to gather `indices` from. Must be greater than or equal to `batch_dims`. Defaults to the first non-batch dimension. Supports negative indexes. |
| `batch_dims` | An `integer`. The number of batch dimensions. Must be less than or equal to `rank(indices)`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `params`. |
tensorflow tf.compat.v1.multinomial tf.compat.v1.multinomial
========================
Draws samples from a multinomial distribution. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.random.multinomial`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/multinomial)
```
tf.compat.v1.multinomial(
logits, num_samples, seed=None, name=None, output_dtype=None
)
```
#### Example:
```
# samples has shape [1, 5], where each value is either 0 or 1 with equal
# probability.
samples = tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5)
```
| Args |
| `logits` | 2-D Tensor with shape `[batch_size, num_classes]`. Each slice `[i, :]` represents the unnormalized log-probabilities for all classes. |
| `num_samples` | 0-D. Number of independent samples to draw for each row slice. |
| `seed` | A Python integer. Used to create a random seed for the distribution. See [`tf.random.set_seed`](../../random/set_seed) for behavior. |
| `name` | Optional name for the operation. |
| `output_dtype` | The integer type of the output: `int32` or `int64`. Defaults to `int64`. |
| Returns |
| The drawn samples of shape `[batch_size, num_samples]`. |
tensorflow Module: tf.compat.v1.lite Module: tf.compat.v1.lite
=========================
Public API for tf.lite namespace.
Modules
-------
[`constants`](lite/constants) module: Public API for tf.lite.constants namespace.
[`experimental`](lite/experimental) module: Public API for tf.lite.experimental namespace.
Classes
-------
[`class Interpreter`](../../lite/interpreter): Interpreter interface for running TensorFlow Lite models.
[`class OpHint`](lite/ophint): A class that helps build tflite function invocations. (deprecated)
[`class OpsSet`](../../lite/opsset): Enum class defining the sets of ops available to generate TFLite models.
[`class Optimize`](../../lite/optimize): Enum defining the optimizations to apply when generating a tflite model.
[`class RepresentativeDataset`](../../lite/representativedataset): Representative dataset used to optimize the model.
[`class TFLiteConverter`](lite/tfliteconverter): Convert a TensorFlow model into `output_format`.
[`class TargetSpec`](../../lite/targetspec): Specification of target device used to optimize the model.
[`class TocoConverter`](lite/tococonverter): Convert a TensorFlow model into `output_format`.
Functions
---------
[`toco_convert(...)`](lite/toco_convert): Convert a TensorFlow GraphDef to TFLite. (deprecated)
tensorflow Module: tf.compat.v1.profiler Module: tf.compat.v1.profiler
=============================
Public API for tf.profiler namespace.
Classes
-------
[`class AdviceProto`](profiler/adviceproto): A ProtocolMessage
[`class GraphNodeProto`](profiler/graphnodeproto): A ProtocolMessage
[`class MultiGraphNodeProto`](profiler/multigraphnodeproto): A ProtocolMessage
[`class OpLogProto`](profiler/oplogproto): A ProtocolMessage
[`class ProfileOptionBuilder`](profiler/profileoptionbuilder): Option Builder for Profiling API.
[`class Profiler`](profiler/profiler): TensorFlow multi-step profiler.
Functions
---------
[`advise(...)`](profiler/advise): Auto profile and advise.
[`profile(...)`](profiler/profile): Profile model.
[`write_op_log(...)`](profiler/write_op_log): Log provided 'op\_log', and add additional model information below.
tensorflow tf.compat.v1.to_complex128 tf.compat.v1.to\_complex128
===========================
Casts a tensor to type `complex128`. (deprecated)
```
tf.compat.v1.to_complex128(
x, name='ToComplex128'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.complex128)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_complex128(tf.constant(1. + 2.j, dtype=tf.complex64))
<tf.Tensor: shape=(), dtype=complex128, numpy=(1+2j)>
```
After:
```
tf.cast(tf.constant(1. + 2.j, dtype=tf.complex64), tf.complex128)
<tf.Tensor: shape=(), dtype=complex128, numpy=(1+2j)>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `complex128`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `complex128`. |
tensorflow Module: tf.compat.v1.quantization Module: tf.compat.v1.quantization
=================================
Public API for tf.quantization namespace.
Functions
---------
[`dequantize(...)`](../../quantization/dequantize): Dequantize the 'input' tensor into a float or bfloat16 Tensor.
[`fake_quant_with_min_max_args(...)`](../../quantization/fake_quant_with_min_max_args): Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type.
[`fake_quant_with_min_max_args_gradient(...)`](../../quantization/fake_quant_with_min_max_args_gradient): Compute gradients for a FakeQuantWithMinMaxArgs operation.
[`fake_quant_with_min_max_vars(...)`](../../quantization/fake_quant_with_min_max_vars): Fake-quantize the 'inputs' tensor of type float via global float scalars
[`fake_quant_with_min_max_vars_gradient(...)`](../../quantization/fake_quant_with_min_max_vars_gradient): Compute gradients for a FakeQuantWithMinMaxVars operation.
[`fake_quant_with_min_max_vars_per_channel(...)`](../../quantization/fake_quant_with_min_max_vars_per_channel): Fake-quantize the 'inputs' tensor of type float via per-channel floats
[`fake_quant_with_min_max_vars_per_channel_gradient(...)`](../../quantization/fake_quant_with_min_max_vars_per_channel_gradient): Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation.
[`quantize(...)`](../../quantization/quantize): Quantize the 'input' tensor of type float to 'output' tensor of type 'T'.
[`quantize_and_dequantize(...)`](../../quantization/quantize_and_dequantize): Quantizes then dequantizes a tensor. (deprecated)
[`quantize_and_dequantize_v2(...)`](../../quantization/quantize_and_dequantize_v2): Quantizes then dequantizes a tensor.
[`quantized_concat(...)`](../../quantization/quantized_concat): Concatenates quantized tensors along one dimension.
tensorflow tf.compat.v1.device tf.compat.v1.device
===================
Wrapper for [`Graph.device()`](https://www.tensorflow.org/api_docs/python/tf/Graph#device) using the default graph.
```
tf.compat.v1.device(
device_name_or_function
)
```
See [`tf.Graph.device`](../../graph#device) for more details.
| Args |
| `device_name_or_function` | The device name or function to use in the context. |
| Returns |
| A context manager that specifies the default device to use for newly created ops. |
| Raises |
| `RuntimeError` | If eager execution is enabled and a function is passed in. |
tensorflow tf.compat.v1.sparse_reduce_sum tf.compat.v1.sparse\_reduce\_sum
================================
Computes [`tf.sparse.add`](../../sparse/add) of elements across dimensions of a SparseTensor. (deprecated arguments) (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.reduce_sum`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_reduce_sum)
```
tf.compat.v1.sparse_reduce_sum(
sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None
)
```
This is the reduction operation for the elementwise [`tf.sparse.add`](../../sparse/add) op.
This Op takes a SparseTensor and is the sparse counterpart to [`tf.reduce_sum()`](../../math/reduce_sum). In particular, this Op also returns a dense `Tensor` instead of a sparse one.
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, similar to the indexing rules in Python.
#### For example:
'x' represents [[1, ?, 1]
=========================
[?, 1, ?]]
==========
where ? is implicitly-zero.
===========================
```
x = tf.sparse.SparseTensor([[0, 0], [0, 2], [1, 1]], [1, 1, 1], [2, 3])
tf.sparse.reduce_sum(x)
<tf.Tensor: shape=(), dtype=int32, numpy=3>
tf.sparse.reduce_sum(x, 0)
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 1, 1], dtype=int32)>
tf.sparse.reduce_sum(x, 1) # Can also use -1 as the axis
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([2, 1], dtype=int32)>
tf.sparse.reduce_sum(x, 1, keepdims=True)
<tf.Tensor: shape=(2, 1), dtype=int32, numpy=
array([[2],
[1]], dtype=int32)>
tf.sparse.reduce_sum(x, [0, 1])
<tf.Tensor: shape=(), dtype=int32, numpy=3>
```
| Args |
| `sp_input` | The SparseTensor to reduce. Should have numeric type. |
| `axis` | The dimensions to reduce; list or scalar. If `None` (the default), reduces all dimensions. |
| `keepdims` | If true, retain reduced dimensions with length 1. |
| `reduction_axes` | Deprecated name of `axis`. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced Tensor. |
tensorflow tf.compat.v1.foldr tf.compat.v1.foldr
==================
foldr on the list of tensors unpacked from `elems` on dimension 0.
```
tf.compat.v1.foldr(
fn,
elems,
initializer=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None
)
```
This foldr operator repeatedly applies the callable `fn` to a sequence of elements from last to first. The elements are made of the tensors unpacked from `elems`. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn, and the second is the value at the current position of `elems`. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is `fn(initializer, values[0]).shape`.
This method also allows multi-arity `elems` and output of `fn`. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of `fn` may match the structure of `elems`. That is, if `elems` is `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: `fn = lambda (t1, [t2, t3, [t4, t5]]):`.
| Args |
| `fn` | The callable to be performed. |
| `elems` | A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be the first argument to `fn`. |
| `initializer` | (optional) A tensor or (possibly nested) sequence of tensors, as the initial value for the accumulator. |
| `parallel_iterations` | (optional) The number of iterations allowed to run in parallel. |
| `back_prop` | (optional) True enables support for back propagation. |
| `swap_memory` | (optional) True enables GPU-CPU memory swapping. |
| `name` | (optional) Name prefix for the returned tensors. |
| Returns |
| A tensor or (possibly nested) sequence of tensors, resulting from applying `fn` consecutively to the list of tensors unpacked from `elems`, from last to first. |
| Raises |
| `TypeError` | if `fn` is not callable. |
#### Example:
```
elems = [1, 2, 3, 4, 5, 6]
sum = foldr(lambda a, x: a + x, elems)
# sum == 21
```
tensorflow tf.compat.v1.GPUOptions tf.compat.v1.GPUOptions
=======================
A ProtocolMessage
| Attributes |
| `allocator_type` | `string allocator_type` |
| `allow_growth` | `bool allow_growth` |
| `deferred_deletion_bytes` | `int64 deferred_deletion_bytes` |
| `experimental` | `Experimental experimental` |
| `force_gpu_compatible` | `bool force_gpu_compatible` |
| `per_process_gpu_memory_fraction` | `double per_process_gpu_memory_fraction` |
| `polling_active_delay_usecs` | `int32 polling_active_delay_usecs` |
| `polling_inactive_delay_msecs` | `int32 polling_inactive_delay_msecs` |
| `visible_device_list` | `string visible_device_list` |
Child Classes
-------------
[`class Experimental`](gpuoptions/experimental)
| programming_docs |
tensorflow tf.compat.v1.global_variables tf.compat.v1.global\_variables
==============================
Returns global variables.
```
tf.compat.v1.global_variables(
scope=None
)
```
Migrate to TF2
--------------
Not compatible with eager execution and [`tf.function`](../../function). In particular, Graph collections are deprecated in TF2. Instead please create a [tf.Module](https://www.tensorflow.org/guide/intro_to_modules) container for all your model state, including variables. You can then list all the variables in your [`tf.Module`](../../module) through the `variables` attribute.
Description
-----------
Global variables are variables that are shared across machines in a distributed environment. The `Variable()` constructor or `get_variable()` automatically adds new variables to the graph collection `GraphKeys.GLOBAL_VARIABLES`. This convenience function returns the contents of that collection.
An alternative to global variables are local variables. See [`tf.compat.v1.local_variables`](local_variables)
| Args |
| `scope` | (Optional.) A string. If supplied, the resulting list is filtered to include only items whose `name` attribute matches `scope` using `re.match`. Items without a `name` attribute are never returned if a scope is supplied. The choice of `re.match` means that a `scope` without special tokens filters by prefix. |
| Returns |
| A list of `Variable` objects. |
tensorflow tf.compat.v1.sparse_reduce_max_sparse tf.compat.v1.sparse\_reduce\_max\_sparse
========================================
Computes the max of elements across dimensions of a SparseTensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.reduce_max_sparse`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_reduce_max_sparse)
```
tf.compat.v1.sparse_reduce_max_sparse(
sp_input, axis=None, keepdims=None, reduction_axes=None, keep_dims=None
)
```
This Op takes a SparseTensor and is the sparse counterpart to [`tf.reduce_max()`](../../math/reduce_max). In contrast to SparseReduceSum, this Op returns a SparseTensor.
>
> **Note:** A gradient is not defined for this function, so it can't be used in training models that need gradient descent.
>
Reduces `sp_input` along the dimensions given in `reduction_axes`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each entry in `reduction_axes`. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `reduction_axes` has no entries, all dimensions are reduced, and a tensor with a single element is returned. Additionally, the axes can be negative, which are interpreted according to the indexing rules in Python.
| Args |
| `sp_input` | The SparseTensor to reduce. Should have numeric type. |
| `axis` | The dimensions to reduce; list or scalar. If `None` (the default), reduces all dimensions. |
| `keepdims` | If true, retain reduced dimensions with length 1. |
| `reduction_axes` | Deprecated name of axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced SparseTensor. |
tensorflow tf.compat.v1.variable_creator_scope tf.compat.v1.variable\_creator\_scope
=====================================
Scope which defines a variable creation function to be used by variable().
```
@tf_contextlib.contextmanager
tf.compat.v1.variable_creator_scope(
variable_creator
)
```
variable\_creator is expected to be a function with the following signature:
```
def variable_creator(next_creator, **kwargs)
```
The creator is supposed to eventually call the next\_creator to create a variable if it does want to create a variable and not call Variable or ResourceVariable directly. This helps make creators composable. A creator may choose to create multiple variables, return already existing variables, or simply register that a variable was created and defer to the next creators in line. Creators can also modify the keyword arguments seen by the next creators.
Custom getters in the variable scope will eventually resolve down to these custom creators when they do create variables.
The valid keyword arguments in kwds are:
* initial\_value: A `Tensor`, or Python object convertible to a `Tensor`, which is the initial value for the Variable. The initial value must have a shape specified unless `validate_shape` is set to False. Can also be a callable with no argument that returns the initial value when called. In that case, `dtype` must be specified. (Note that initializer functions from init\_ops.py must first be bound to a shape before being used here.)
* trainable: If `True`, the default, also adds the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This collection is used as the default list of variables to use by the `Optimizer` classes. `trainable` defaults to `True`, unless `synchronization` is set to `ON_READ`, in which case it defaults to `False`.
* collections: List of graph collections keys. The new variable is added to these collections. Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
* validate\_shape: If `False`, allows the variable to be initialized with a value of unknown shape. If `True`, the default, the shape of `initial_value` must be known.
* caching\_device: Optional device string describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements.
* name: Optional name for the variable. Defaults to `'Variable'` and gets uniquified automatically.
* dtype: If set, initial\_value will be converted to the given type. If `None`, either the datatype will be kept (if `initial_value` is a Tensor), or `convert_to_tensor` will decide.
* constraint: A constraint function to be applied to the variable after updates by some algorithms.
* use\_resource: if True, a ResourceVariable is always created.
* synchronization: Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableSynchronization`](../../variablesynchronization). By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize.
* aggregation: Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableAggregation`](../../variableaggregation).
This set may grow over time, so it's important the signature of creators is as mentioned above.
| Args |
| `variable_creator` | the passed creator |
| Yields |
| A scope in which the creator is active |
tensorflow tf.compat.v1.to_complex64 tf.compat.v1.to\_complex64
==========================
Casts a tensor to type `complex64`. (deprecated)
```
tf.compat.v1.to_complex64(
x, name='ToComplex64'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.complex64)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_complex64(tf.constant(1. + 2.j, dtype=tf.complex128))
<tf.Tensor: shape=(), dtype=complex64, numpy=(1+2j)>
```
After:
```
tf.cast(tf.constant(1. + 2.j, dtype=tf.complex128), tf.complex64)
<tf.Tensor: shape=(), dtype=complex64, numpy=(1+2j)>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `complex64`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `complex64`. |
tensorflow tf.compat.v1.batch_scatter_update tf.compat.v1.batch\_scatter\_update
===================================
Generalization of [`tf.compat.v1.scatter_update`](scatter_update) to axis different than 0. (deprecated)
```
tf.compat.v1.batch_scatter_update(
ref, indices, updates, use_locking=True, name=None
)
```
Analogous to `batch_gather`. This assumes that `ref`, `indices` and `updates` have a series of leading dimensions that are the same for all of them, and the updates are performed on the last dimension of indices. In other words, the dimensions should be the following:
`num_prefix_dims = indices.ndims - 1` `batch_dim = num_prefix_dims + 1` `updates.shape = indices.shape + var.shape[batch_dim:]`
where
`updates.shape[:num_prefix_dims]` `== indices.shape[:num_prefix_dims]` `== var.shape[:num_prefix_dims]`
And the operation performed can be expressed as:
`var[i_1, ..., i_n, indices[i_1, ..., i_n, j]] = updates[i_1, ..., i_n, j]`
When indices is a 1D tensor, this operation is equivalent to [`tf.compat.v1.scatter_update`](scatter_update).
To avoid this operation there would be 2 alternatives:
1) Reshaping the variable by merging the first `ndims` dimensions. However, this is not possible because [`tf.reshape`](../../reshape) returns a Tensor, which we cannot use [`tf.compat.v1.scatter_update`](scatter_update) on. 2) Looping over the first `ndims` of the variable and using [`tf.compat.v1.scatter_update`](scatter_update) on the subtensors that result of slicing the first dimension. This is a valid option for `ndims = 1`, but less efficient than this implementation.
See also [`tf.compat.v1.scatter_update`](scatter_update) and [`tf.compat.v1.scatter_nd_update`](scatter_nd_update).
| Args |
| `ref` | `Variable` to scatter onto. |
| `indices` | Tensor containing indices as described above. |
| `updates` | Tensor of updates to apply to `ref`. |
| `use_locking` | Boolean indicating whether to lock the writing operation. |
| `name` | Optional scope name string. |
| Returns |
| Ref to `variable` after it has been modified. |
| Raises |
| `ValueError` | If the initial `ndims` of `ref`, `indices`, and `updates` are not the same. |
tensorflow Module: tf.compat.v1.config Module: tf.compat.v1.config
===========================
Public API for tf.config namespace.
Modules
-------
[`experimental`](config/experimental) module: Public API for tf.config.experimental namespace.
[`optimizer`](config/optimizer) module: Public API for tf.config.optimizer namespace.
[`threading`](config/threading) module: Public API for tf.config.threading namespace.
Classes
-------
[`class LogicalDevice`](../../config/logicaldevice): Abstraction for a logical device initialized by the runtime.
[`class LogicalDeviceConfiguration`](../../config/logicaldeviceconfiguration): Configuration class for a logical devices.
[`class PhysicalDevice`](../../config/physicaldevice): Abstraction for a locally visible physical device.
Functions
---------
[`experimental_connect_to_cluster(...)`](../../config/experimental_connect_to_cluster): Connects to the given cluster.
[`experimental_connect_to_host(...)`](../../config/experimental_connect_to_host): Connects to a single machine to enable remote execution on it.
[`experimental_functions_run_eagerly(...)`](../../config/experimental_functions_run_eagerly): Returns the value of the `experimental_run_functions_eagerly` setting. (deprecated)
[`experimental_run_functions_eagerly(...)`](../../config/experimental_run_functions_eagerly): Enables / disables eager execution of [`tf.function`](../../function)s. (deprecated)
[`functions_run_eagerly(...)`](../../config/functions_run_eagerly): Returns the value of the `run_functions_eagerly` setting.
[`get_logical_device_configuration(...)`](../../config/get_logical_device_configuration): Get the virtual device configuration for a [`tf.config.PhysicalDevice`](../../config/physicaldevice).
[`get_soft_device_placement(...)`](../../config/get_soft_device_placement): Return status of soft device placement flag.
[`get_visible_devices(...)`](../../config/get_visible_devices): Get the list of visible physical devices.
[`list_logical_devices(...)`](../../config/list_logical_devices): Return a list of logical devices created by runtime.
[`list_physical_devices(...)`](../../config/list_physical_devices): Return a list of physical devices visible to the host runtime.
[`run_functions_eagerly(...)`](../../config/run_functions_eagerly): Enables / disables eager execution of [`tf.function`](../../function)s.
[`set_logical_device_configuration(...)`](../../config/set_logical_device_configuration): Set the logical device configuration for a [`tf.config.PhysicalDevice`](../../config/physicaldevice).
[`set_soft_device_placement(...)`](../../config/set_soft_device_placement): Enable or disable soft device placement.
[`set_visible_devices(...)`](../../config/set_visible_devices): Set the list of visible devices.
tensorflow tf.compat.v1.assert_negative tf.compat.v1.assert\_negative
=============================
Assert the condition `x < 0` holds element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_negative`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_negative)
```
tf.compat.v1.assert_negative(
x, data=None, summarize=None, message=None, name=None
)
```
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.debugging.assert_negative(x, y)]):
output = tf.reduce_sum(x)
```
Negative means, for every element `x[i]` of `x`, we have `x[i] < 0`. If `x` is empty this is trivially satisfied.
| Args |
| `x` | Numeric `Tensor`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_negative". |
| Returns |
| Op that raises `InvalidArgumentError` if `x < 0` is False. |
| Raises |
| `InvalidArgumentError` | if the check can be performed immediately and `x < 0` is False. The check can be performed immediately during eager execution or if `x` is statically known. |
eager compatibility
-------------------
returns None
tensorflow Module: tf.compat.v1.user_ops Module: tf.compat.v1.user\_ops
==============================
Public API for tf.user\_ops namespace.
Functions
---------
[`my_fact(...)`](user_ops/my_fact): Example of overriding the generated code for an Op.
tensorflow tf.compat.v1.report_uninitialized_variables tf.compat.v1.report\_uninitialized\_variables
=============================================
Adds ops to list the names of uninitialized variables.
```
tf.compat.v1.report_uninitialized_variables(
var_list=None, name='report_uninitialized_variables'
)
```
When run, it returns a 1-D tensor containing the names of uninitialized variables if there are any, or an empty array if there are none.
| Args |
| `var_list` | List of `Variable` objects to check. Defaults to the value of `global_variables() + local_variables()` |
| `name` | Optional name of the `Operation`. |
| Returns |
| A 1-D tensor containing names of the uninitialized variables, or an empty 1-D tensor if there are no variables or no uninitialized variables. |
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.reduce_any tf.compat.v1.reduce\_any
========================
Computes [`tf.math.logical_or`](../../math/logical_or) of elements across dimensions of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.reduce_any`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_any)
```
tf.compat.v1.reduce_any(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None
)
```
This is the reduction operation for the elementwise [`tf.math.logical_or`](../../math/logical_or) op.
Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned.
#### For example:
```
x = tf.constant([[True, True], [False, False]])
tf.reduce_any(x)
<tf.Tensor: shape=(), dtype=bool, numpy=True>
tf.reduce_any(x, 0)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, True])>
tf.reduce_any(x, 1)
<tf.Tensor: shape=(2,), dtype=bool, numpy=array([ True, False])>
```
| Args |
| `input_tensor` | The boolean tensor to reduce. |
| `axis` | The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `name` | A name for the operation (optional). |
| `reduction_indices` | The old (deprecated) name for axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced tensor. |
numpy compatibility
-------------------
Equivalent to np.any
tensorflow tf.compat.v1.enable_v2_tensorshape tf.compat.v1.enable\_v2\_tensorshape
====================================
In TensorFlow 2.0, iterating over a TensorShape instance returns values.
```
tf.compat.v1.enable_v2_tensorshape()
```
This enables the new behavior.
Concretely, `tensor_shape[i]` returned a Dimension instance in V1, but it V2 it returns either an integer, or None.
#### Examples:
```
#######################
# If you had this in V1:
value = tensor_shape[i].value
# Do this in V2 instead:
value = tensor_shape[i]
#######################
# If you had this in V1:
for dim in tensor_shape:
value = dim.value
print(value)
# Do this in V2 instead:
for value in tensor_shape:
print(value)
#######################
# If you had this in V1:
dim = tensor_shape[i]
dim.assert_is_compatible_with(other_shape) # or using any other shape method
# Do this in V2 instead:
if tensor_shape.rank is None:
dim = Dimension(None)
else:
dim = tensor_shape.dims[i]
dim.assert_is_compatible_with(other_shape) # or using any other shape method
# The V2 suggestion above is more explicit, which will save you from
# the following trap (present in V1):
# you might do in-place modifications to `dim` and expect them to be reflected
# in `tensor_shape[i]`, but they would not be.
```
tensorflow Module: tf.compat.v1.types Module: tf.compat.v1.types
==========================
Public TensorFlow type definitions.
For details, see <https://github.com/tensorflow/community/blob/master/rfcs/20200211-tf-types.md>
Modules
-------
[`experimental`](types/experimental) module: Public API for tf.types.experimental namespace.
tensorflow tf.compat.v1.placeholder_with_default tf.compat.v1.placeholder\_with\_default
=======================================
A placeholder op that passes through `input` when its output is not fed.
```
tf.compat.v1.placeholder_with_default(
input, shape, name=None
)
```
Migrate to TF2
--------------
This API is strongly discouraged for use with eager execution and [`tf.function`](../../function). The primary use of this API is for testing computation wrapped within a [`tf.function`](../../function) where the input tensors might not have statically known fully-defined shapes. The same can be achieved by creating a [concrete function](https://www.tensorflow.org/guide/function#obtaining_concrete_functions) from the [`tf.function`](../../function) with a [`tf.TensorSpec`](../../tensorspec) input which has partially defined shapes. For example, the code
```
@tf.function
def f():
x = tf.compat.v1.placeholder_with_default(
tf.constant([[1., 2., 3.], [4., 5., 6.]]), [None, 3])
y = tf.constant([[1.],[2.], [3.]])
z = tf.matmul(x, y)
assert z.shape[0] == None
assert z.shape[1] == 1
```
```
f()
```
can easily be replaced by
```
@tf.function
def f(x):
y = tf.constant([[1.],[2.], [3.]])
z = tf.matmul(x, y)
assert z.shape[0] == None
assert z.shape[1] == 1
```
```
g = f.get_concrete_function(tf.TensorSpec([None, 3]))
```
You can learn more about [`tf.function`](../../function) at [Better performance with tf.function](https://www.tensorflow.org/guide/function).
Description
-----------
| Args |
| `input` | A `Tensor`. The default value to produce when output is not fed. |
| `shape` | A [`tf.TensorShape`](../../tensorshape) or list of `int`s. The (possibly partial) shape of the tensor. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
| programming_docs |
tensorflow Module: tf.compat.v1.xla Module: tf.compat.v1.xla
========================
Public API for tf.xla namespace.
Modules
-------
[`experimental`](xla/experimental) module: Public API for tf.xla.experimental namespace.
tensorflow tf.compat.v1.truncated_normal_initializer tf.compat.v1.truncated\_normal\_initializer
===========================================
Initializer that generates a truncated normal distribution.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.truncated_normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/truncated_normal_initializer)
```
tf.compat.v1.truncated_normal_initializer(
mean=0.0,
stddev=1.0,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../function).
To switch to TF2, switch to using either [`tf.initializers.truncated_normal`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/TruncatedNormal) or [`tf.keras.initializers.TruncatedNormal`](../../keras/initializers/truncatednormal) (neither from [`compat.v1`](../v1)) and pass the dtype when calling the initializer. Keep in mind that the default stddev and the behavior of fixed seeds have changed.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.truncated_normal_initializer(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.initializers.truncated_normal(
mean=mean,
seed=seed,
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | Default changes from 1.0 to 0.05 |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
These values are similar to values from a `random_normal_initializer` except that values more than two standard deviations from the mean are discarded and re-drawn. This is the recommended initializer for neural network weights and filters.
| Args |
| `mean` | a python scalar or a scalar tensor. Mean of the random values to generate. |
| `stddev` | a python scalar or a scalar tensor. Standard deviation of the random values to generate. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L663-L669)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L657-L661)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.extract_image_patches tf.compat.v1.extract\_image\_patches
====================================
Extract `patches` from `images` and put them in the "depth" output dimension.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.image.extract_image_patches`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/extract_image_patches)
```
tf.compat.v1.extract_image_patches(
images,
ksizes=None,
strides=None,
rates=None,
padding=None,
name=None,
sizes=None
)
```
| Args |
| `images` | A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `int8`, `int16`, `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `complex64`, `complex128`, `bool`. 4-D Tensor with shape `[batch, in_rows, in_cols, depth]`. |
| `ksizes` | A list of `ints` that has length `>= 4`. The size of the sliding window for each dimension of `images`. |
| `strides` | A list of `ints` that has length `>= 4`. How far the centers of two consecutive patches are in the images. Must be: `[1, stride_rows, stride_cols, 1]`. |
| `rates` | A list of `ints` that has length `>= 4`. Must be: `[1, rate_rows, rate_cols, 1]`. This is the input stride, specifying how far two consecutive patch samples are in the input. Equivalent to extracting patches with `patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1)`, followed by subsampling them spatially by a factor of `rates`. This is equivalent to `rate` in dilated (a.k.a. Atrous) convolutions. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `images`. |
tensorflow tf.compat.v1.trainable_variables tf.compat.v1.trainable\_variables
=================================
Returns all variables created with `trainable=True`.
```
tf.compat.v1.trainable_variables(
scope=None
)
```
Migrate to TF2
--------------
Not compatible with eager execution and [`tf.function`](../../function). In particular, Graph collections are deprecated in TF2. Instead please create a [`tf.Module`](../../module) container for all your model state, including variables. You can then list all the trainable variables in your [`tf.Module`](../../module) through the `trainable_variables` attribute.
Description
-----------
When passed `trainable=True`, the `Variable()` constructor automatically adds new variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES`. This convenience function returns the contents of that collection.
| Args |
| `scope` | (Optional.) A string. If supplied, the resulting list is filtered to include only items whose `name` attribute matches `scope` using `re.match`. Items without a `name` attribute are never returned if a scope is supplied. The choice of `re.match` means that a `scope` without special tokens filters by prefix. |
| Returns |
| A list of Variable objects. |
tensorflow tf.compat.v1.confusion_matrix tf.compat.v1.confusion\_matrix
==============================
Computes the confusion matrix from predictions and labels.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.confusion_matrix`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/confusion_matrix)
```
tf.compat.v1.confusion_matrix(
labels,
predictions,
num_classes=None,
dtype=tf.dtypes.int32,
name=None,
weights=None
)
```
The matrix columns represent the prediction labels and the rows represent the real labels. The confusion matrix is always a 2-D array of shape `[n, n]`, where `n` is the number of valid labels for a given classification task. Both prediction and labels must be 1-D arrays of the same shape in order for this function to work.
If `num_classes` is `None`, then `num_classes` will be set to one plus the maximum value in either predictions or labels. Class labels are expected to start at 0. For example, if `num_classes` is 3, then the possible labels would be `[0, 1, 2]`.
If `weights` is not `None`, then each prediction contributes its corresponding weight to the total value of the confusion matrix cell.
#### For example:
```
tf.math.confusion_matrix([1, 2, 4], [2, 2, 4]) ==>
[[0 0 0 0 0]
[0 0 1 0 0]
[0 0 1 0 0]
[0 0 0 0 0]
[0 0 0 0 1]]
```
Note that the possible labels are assumed to be `[0, 1, 2, 3, 4]`, resulting in a 5x5 confusion matrix.
| Args |
| `labels` | 1-D `Tensor` of real labels for the classification task. |
| `predictions` | 1-D `Tensor` of predictions for a given classification. |
| `num_classes` | The possible number of labels the classification task can have. If this value is not provided, it will be calculated using both predictions and labels array. |
| `dtype` | Data type of the confusion matrix. |
| `name` | Scope name. |
| `weights` | An optional `Tensor` whose shape matches `predictions`. |
| Returns |
| A `Tensor` of type `dtype` with shape `[n, n]` representing the confusion matrix, where `n` is the number of possible labels in the classification task. |
| Raises |
| `ValueError` | If both predictions and labels are not 1-D vectors and have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`. |
tensorflow Module: tf.compat.v1.errors Module: tf.compat.v1.errors
===========================
Exception types for TensorFlow errors.
Classes
-------
[`class AbortedError`](../../errors/abortederror): The operation was aborted, typically due to a concurrent action.
[`class AlreadyExistsError`](../../errors/alreadyexistserror): Raised when an entity that we attempted to create already exists.
[`class CancelledError`](../../errors/cancellederror): Raised when an operation or step is cancelled.
[`class DataLossError`](../../errors/datalosserror): Raised when unrecoverable data loss or corruption is encountered.
[`class DeadlineExceededError`](../../errors/deadlineexceedederror): Raised when a deadline expires before an operation could complete.
[`class FailedPreconditionError`](../../errors/failedpreconditionerror): Operation was rejected because the system is not in a state to execute it.
[`class InternalError`](../../errors/internalerror): Raised when the system experiences an internal error.
[`class InvalidArgumentError`](../../errors/invalidargumenterror): Raised when an operation receives an invalid argument.
[`class NotFoundError`](../../errors/notfounderror): Raised when a requested entity (e.g., a file or directory) was not found.
[`class OpError`](../../errors/operror): The base class for TensorFlow exceptions.
[`class OutOfRangeError`](../../errors/outofrangeerror): Raised when an operation iterates past the valid input range.
[`class PermissionDeniedError`](../../errors/permissiondeniederror): Raised when the caller does not have permission to run an operation.
[`class ResourceExhaustedError`](../../errors/resourceexhaustederror): Some resource has been exhausted.
[`class UnauthenticatedError`](../../errors/unauthenticatederror): The request does not have valid authentication credentials.
[`class UnavailableError`](../../errors/unavailableerror): Raised when the runtime is currently unavailable.
[`class UnimplementedError`](../../errors/unimplementederror): Raised when an operation has not been implemented.
[`class UnknownError`](../../errors/unknownerror): Unknown error.
[`class raise_exception_on_not_ok_status`](errors/raise_exception_on_not_ok_status): Context manager to check for C API status.
Functions
---------
[`error_code_from_exception_type(...)`](errors/error_code_from_exception_type)
[`exception_type_from_error_code(...)`](errors/exception_type_from_error_code)
| Other Members |
| ABORTED | `10` |
| ALREADY\_EXISTS | `6` |
| CANCELLED | `1` |
| DATA\_LOSS | `15` |
| DEADLINE\_EXCEEDED | `4` |
| FAILED\_PRECONDITION | `9` |
| INTERNAL | `13` |
| INVALID\_ARGUMENT | `3` |
| NOT\_FOUND | `5` |
| OK | `0` |
| OUT\_OF\_RANGE | `11` |
| PERMISSION\_DENIED | `7` |
| RESOURCE\_EXHAUSTED | `8` |
| UNAUTHENTICATED | `16` |
| UNAVAILABLE | `14` |
| UNIMPLEMENTED | `12` |
| UNKNOWN | `2` |
tensorflow Module: tf.compat.v1.feature_column Module: tf.compat.v1.feature\_column
====================================
Public API for tf.feature\_column namespace.
Functions
---------
[`bucketized_column(...)`](../../feature_column/bucketized_column): Represents discretized dense input bucketed by `boundaries`.
[`categorical_column_with_hash_bucket(...)`](../../feature_column/categorical_column_with_hash_bucket): Represents sparse feature where ids are set by hashing.
[`categorical_column_with_identity(...)`](../../feature_column/categorical_column_with_identity): A `CategoricalColumn` that returns identity values.
[`categorical_column_with_vocabulary_file(...)`](feature_column/categorical_column_with_vocabulary_file): A `CategoricalColumn` with a vocabulary file.
[`categorical_column_with_vocabulary_list(...)`](../../feature_column/categorical_column_with_vocabulary_list): A `CategoricalColumn` with in-memory vocabulary.
[`crossed_column(...)`](../../feature_column/crossed_column): Returns a column for performing crosses of categorical features.
[`embedding_column(...)`](../../feature_column/embedding_column): `DenseColumn` that converts from sparse, categorical input.
[`indicator_column(...)`](../../feature_column/indicator_column): Represents multi-hot representation of given categorical column.
[`input_layer(...)`](feature_column/input_layer): Returns a dense `Tensor` as input layer based on given `feature_columns`.
[`linear_model(...)`](feature_column/linear_model): Returns a linear prediction `Tensor` based on given `feature_columns`.
[`make_parse_example_spec(...)`](feature_column/make_parse_example_spec): Creates parsing spec dictionary from input feature\_columns.
[`numeric_column(...)`](../../feature_column/numeric_column): Represents real valued or numerical features.
[`sequence_categorical_column_with_hash_bucket(...)`](../../feature_column/sequence_categorical_column_with_hash_bucket): A sequence of categorical terms where ids are set by hashing.
[`sequence_categorical_column_with_identity(...)`](../../feature_column/sequence_categorical_column_with_identity): Returns a feature column that represents sequences of integers.
[`sequence_categorical_column_with_vocabulary_file(...)`](../../feature_column/sequence_categorical_column_with_vocabulary_file): A sequence of categorical terms where ids use a vocabulary file.
[`sequence_categorical_column_with_vocabulary_list(...)`](../../feature_column/sequence_categorical_column_with_vocabulary_list): A sequence of categorical terms where ids use an in-memory list.
[`sequence_numeric_column(...)`](../../feature_column/sequence_numeric_column): Returns a feature column that represents sequences of numeric data.
[`shared_embedding_columns(...)`](feature_column/shared_embedding_columns): List of dense columns that convert from sparse, categorical input.
[`weighted_categorical_column(...)`](../../feature_column/weighted_categorical_column): Applies weight values to a `CategoricalColumn`.
tensorflow tf.compat.v1.TFRecordReader tf.compat.v1.TFRecordReader
===========================
A Reader that outputs the records from a TFRecords file.
Inherits From: [`ReaderBase`](readerbase)
```
tf.compat.v1.TFRecordReader(
name=None, options=None
)
```
See ReaderBase for supported methods.
| Args |
| `name` | A name for the operation (optional). |
| `options` | A TFRecordOptions object (optional). |
| Attributes |
| `reader_ref` | Op that implements the reader. |
| `supports_serialize` | Whether the Reader implementation can serialize its state. |
Methods
-------
### `num_records_produced`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L328-L346)
```
num_records_produced(
name=None
)
```
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `num_work_units_completed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L348-L362)
```
num_work_units_completed(
name=None
)
```
Returns the number of work units this reader has finished processing.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L261-L288)
```
read(
queue, name=None
)
```
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (key, value). |
| `key` | A string scalar Tensor. |
| `value` | A string scalar Tensor. |
### `read_up_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L290-L326)
```
read_up_to(
queue, num_records, name=None
)
```
Returns up to num\_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num\_records even before the last batch.
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `num_records` | Number of records to read. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (keys, values). |
| `keys` | A 1-D string Tensor. |
| `values` | A 1-D string Tensor. |
### `reset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L406-L418)
```
reset(
name=None
)
```
Restore a reader to its initial clean state.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `restore_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L381-L399)
```
restore_state(
state, name=None
)
```
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
| Args |
| `state` | A string Tensor. Result of a SerializeState of a Reader with matching type. |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `serialize_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L364-L379)
```
serialize_state(
name=None
)
```
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A string Tensor. |
eager compatibility
-------------------
Readers are not compatible with eager execution. Instead, please use [`tf.data`](../../data) to get data into your model.
| programming_docs |
tensorflow tf.compat.v1.add_check_numerics_ops tf.compat.v1.add\_check\_numerics\_ops
======================================
Connect a [`tf.debugging.check_numerics`](../../debugging/check_numerics) to every floating point tensor.
```
tf.compat.v1.add_check_numerics_ops()
```
`check_numerics` operations themselves are added for each `half`, `float`, or `double` tensor in the current default graph. For all ops in the graph, the `check_numerics` op for all of its (`half`, `float`, or `double`) inputs is guaranteed to run before the `check_numerics` op on any of its outputs.
>
> **Note:** This API is not compatible with the use of [`tf.cond`](../../cond) or [`tf.while_loop`](../../while_loop), and will raise a `ValueError` if you attempt to call it in such a graph.
>
| Returns |
| A `group` op depending on all `check_numerics` ops added. |
| Raises |
| `ValueError` | If the graph contains any numeric operations in a control flow structure. |
| `RuntimeError` | If called with eager execution enabled. |
eager compatibility
-------------------
Not compatible with eager execution. To check for `Inf`s and `NaN`s under eager execution, call [`tf.debugging.enable_check_numerics()`](../../debugging/enable_check_numerics) once before executing the checked operations.
tensorflow tf.compat.v1.get_local_variable tf.compat.v1.get\_local\_variable
=================================
Gets an existing *local* variable or creates a new one.
```
tf.compat.v1.get_local_variable(
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=False,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None,
constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../v1) api, [`tf.compat.v1.get_variable`](get_variable) is mostly compatible with eager execution and [`tf.function`](../../function) but only if you combine it with the [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables) decorator. (Though it will behave as if reuse is always set to `AUTO_REUSE`.)
See the [model migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) for more info.
If you do not combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables), `get_variable` will create a brand new variable every single time it is called and will never reuse variables, regardless of variable names or `reuse` arguments.
The TF2 equivalent of this symbol would be [`tf.Variable`](../../variable), but note that when using [`tf.Variable`](../../variable) you must make sure you track your variables (and regularizer arguments) either manually or via [`tf.Module`](../../module) or [`tf.keras.layers.Layer`](../../keras/layers/layer) mechanisms.
A section of the [migration guide](https://www.tensorflow.org/guide/migrate/model_mapping#incremental_migration_to_native_tf2) provides more details on incrementally migrating these usages to [`tf.Variable`](../../variable) as well.
>
> **Note:** The `partitioner` arg is not compatible with TF2 behaviors even when using [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables). It can be replaced by using `ParameterServerStrategy` and its partitioners. See the [multi-gpu migration guide](https://www.tensorflow.org/guide/migrate/multi_worker_cpu_gpu_training) and the ParameterServerStrategy guides it references for more info.
>
Description
-----------
Behavior is the same as in `get_variable`, except that variables are added to the `LOCAL_VARIABLES` collection and `trainable` is set to `False`. This function prefixes the name with the current variable scope and performs reuse checks. See the [Variable Scope How To](https://tensorflow.org/guide/variables) for an extensive description of how reusing works. Here is a basic example:
```
def foo():
with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v
v1 = foo() # Creates v.
v2 = foo() # Gets the same, existing v.
assert v1 == v2
```
If initializer is `None` (the default), the default initializer passed in the variable scope will be used. If that one is `None` too, a `glorot_uniform_initializer` will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape.
Similarly, if the regularizer is `None` (the default), the default regularizer passed in the variable scope will be used (if that is `None` too, then by default no regularization is performed).
If a partitioner is provided, a `PartitionedVariable` is returned. Accessing this object as a `Tensor` returns the shards concatenated along the partition axis.
Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`.
| Args |
| `name` | The name of the new or existing variable. |
| `shape` | Shape of the new or existing variable. |
| `dtype` | Type of the new or existing variable (defaults to `DT_FLOAT`). |
| `initializer` | Initializer for the variable if one is created. Can either be an initializer object or a Tensor. If it's a Tensor, its shape must be known unless validate\_shape is False. |
| `regularizer` | A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection `tf.GraphKeys.REGULARIZATION_LOSSES` and can be used for regularization. |
| `collections` | List of graph collections keys to add the Variable to. Defaults to `[GraphKeys.LOCAL_VARIABLES]` (see [`tf.Variable`](../../variable)). |
| `caching_device` | Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. |
| `partitioner` | Optional callable that accepts a fully defined `TensorShape` and `dtype` of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). |
| `validate_shape` | If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial\_value must be known. For this to be used the initializer must be a Tensor and not an initializer object. |
| `use_resource` | If False, creates a regular Variable. If true, creates an experimental ResourceVariable instead with well-defined semantics. Defaults to False (will later change to True). When eager execution is enabled this argument is always forced to be True. |
| `custom_getter` | Callable that takes as a first argument the true getter, and allows overwriting the internal get\_variable method. The signature of `custom_getter` should match that of this method, but the most future-proof version will allow for changes: `def custom_getter(getter, *args, **kwargs)`. Direct access to all `get_variable` parameters is also allowed: `def custom_getter(getter, name, *args, **kwargs)`. A simple identity custom getter that simply creates variables with modified names is:
```
def custom_getter(getter, name, *args, **kwargs):
return getter(name + '_suffix', *args, **kwargs)
```
|
| `constraint` | An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `synchronization` | Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableSynchronization`](../../variablesynchronization). By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. |
| `aggregation` | Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableAggregation`](../../variableaggregation). |
| Returns |
| The created or existing `Variable` (or `PartitionedVariable`, if a partitioner was used). |
| Raises |
| `ValueError` | when creating a new variable and shape is not declared, when violating reuse during variable creation, or when `initializer` dtype and `dtype` don't match. Reuse is set inside `variable_scope`. |
tensorflow tf.compat.v1.is_variable_initialized tf.compat.v1.is\_variable\_initialized
======================================
Tests if a variable has been initialized.
```
tf.compat.v1.is_variable_initialized(
variable
)
```
| Args |
| `variable` | A `Variable`. |
| Returns |
| Returns a scalar boolean Tensor, `True` if the variable has been initialized, `False` otherwise. |
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.SessionLog tf.compat.v1.SessionLog
=======================
A ProtocolMessage
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.summary.SessionLog`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/SessionLog)
| Attributes |
| `checkpoint_path` | `string checkpoint_path` |
| `msg` | `string msg` |
| `status` | `SessionStatus status` |
| Class Variables |
| CHECKPOINT | `3` |
| START | `1` |
| STATUS\_UNSPECIFIED | `0` |
| STOP | `2` |
| SessionStatus | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
tensorflow tf.compat.v1.DeviceSpec tf.compat.v1.DeviceSpec
=======================
Represents a (possibly partial) specification for a TensorFlow device.
Inherits From: [`DeviceSpec`](../../devicespec)
```
tf.compat.v1.DeviceSpec(
job=None, replica=None, task=None, device_type=None, device_index=None
)
```
`DeviceSpec`s are used throughout TensorFlow to describe where state is stored and computations occur. Using `DeviceSpec` allows you to parse device spec strings to verify their validity, merge them or compose them programmatically.
#### Example:
```
# Place the operations on device "GPU:0" in the "ps" job.
device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
with tf.device(device_spec.to_string()):
# Both my_var and squared_var will be placed on /job:ps/device:GPU:0.
my_var = tf.Variable(..., name="my_variable")
squared_var = tf.square(my_var)
```
With eager execution disabled (by default in TensorFlow 1.x and by calling disable\_eager\_execution() in TensorFlow 2.x), the following syntax can be used:
```
tf.compat.v1.disable_eager_execution()
# Same as previous
device_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
# No need of .to_string() method.
with tf.device(device_spec):
my_var = tf.Variable(..., name="my_variable")
squared_var = tf.square(my_var)
```
If a `DeviceSpec` is partially specified, it will be merged with other `DeviceSpec`s according to the scope in which it is defined. `DeviceSpec` components defined in inner scopes take precedence over those defined in outer scopes.
```
gpu0_spec = DeviceSpec(job="ps", device_type="GPU", device_index=0)
with tf.device(DeviceSpec(job="train").to_string()):
with tf.device(gpu0_spec.to_string()):
# Nodes created here will be assigned to /job:ps/device:GPU:0.
with tf.device(DeviceSpec(device_type="GPU", device_index=1).to_string()):
# Nodes created here will be assigned to /job:train/device:GPU:1.
```
A `DeviceSpec` consists of 5 components -- each of which is optionally specified:
* Job: The job name.
* Replica: The replica index.
* Task: The task index.
* Device type: The device type string (e.g. "CPU" or "GPU").
* Device index: The device index.
| Args |
| `job` | string. Optional job name. |
| `replica` | int. Optional replica index. |
| `task` | int. Optional task index. |
| `device_type` | Optional device type string (e.g. "CPU" or "GPU") |
| `device_index` | int. Optional device index. If left unspecified, device represents 'any' device\_index. |
| Attributes |
| `device_index` | |
| `device_type` | |
| `job` | |
| `replica` | |
| `task` | |
Methods
-------
### `from_string`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L145-L158)
```
@classmethod
from_string(
spec
)
```
Construct a `DeviceSpec` from a string.
| Args |
| `spec` | a string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional. |
| Returns |
| A DeviceSpec. |
### `make_merged_spec`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L215-L237)
```
make_merged_spec(
dev
)
```
Returns a new DeviceSpec which incorporates `dev`.
When combining specs, `dev` will take precedence over the current spec. So for instance:
```
first_spec = tf.DeviceSpec(job=0, device_type="CPU")
second_spec = tf.DeviceSpec(device_type="GPU")
combined_spec = first_spec.make_merged_spec(second_spec)
```
is equivalent to:
```
combined_spec = tf.DeviceSpec(job=0, device_type="GPU")
```
| Args |
| `dev` | a `DeviceSpec` |
| Returns |
| A new `DeviceSpec` which combines `self` and `dev` |
### `merge_from`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L466-L476)
```
merge_from(
dev
)
```
Merge the properties of "dev" into this `DeviceSpec`.
>
> **Note:** Will be removed in TensorFlow 2.x since DeviceSpecs will become immutable.
>
| Args |
| `dev` | a `DeviceSpec`. |
### `parse_from_string`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L460-L464)
```
parse_from_string(
spec
)
```
Parse a `DeviceSpec` name into its components.
**2.x behavior change**:
In TensorFlow 1.x, this function mutates its own state and returns itself. In 2.x, DeviceSpecs are immutable, and this function will return a DeviceSpec which contains the spec.
* Recommended:
```
# my_spec and my_updated_spec are unrelated.
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_updated_spec = tf.DeviceSpec.from_string("/GPU:0")
with tf.device(my_updated_spec):
...
```
* Will work in 1.x and 2.x (though deprecated in 2.x):
```
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_updated_spec = my_spec.parse_from_string("/GPU:0")
with tf.device(my_updated_spec):
...
```
* Will NOT work in 2.x:
```
my_spec = tf.DeviceSpec.from_string("/CPU:0")
my_spec.parse_from_string("/GPU:0") # <== Will not update my_spec
with tf.device(my_spec):
...
```
In general, [`DeviceSpec.from_string`](https://www.tensorflow.org/api_docs/python/tf/DeviceSpec#from_string) should completely replace [`DeviceSpec.parse_from_string`](https://www.tensorflow.org/api_docs/python/tf/DeviceSpec#parse_from_string), and [`DeviceSpec.replace`](https://www.tensorflow.org/api_docs/python/tf/DeviceSpec#replace) should completely replace setting attributes directly.
| Args |
| `spec` | an optional string of the form /job:/replica:/task:/device:CPU: or /job:/replica:/task:/device:GPU: as cpu and gpu are mutually exclusive. All entries are optional. |
| Returns |
| The `DeviceSpec`. |
| Raises |
| `ValueError` | if the spec was not valid. |
### `replace`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L239-L264)
```
replace(
**kwargs
)
```
Convenience method for making a new DeviceSpec by overriding fields.
#### For instance:
```
my_spec = DeviceSpec=(job="my_job", device="CPU")
my_updated_spec = my_spec.replace(device="GPU")
my_other_spec = my_spec.replace(device=None)
```
| Args |
| `**kwargs` | This method takes the same args as the DeviceSpec constructor |
| Returns |
| A DeviceSpec with the fields specified in kwargs overridden. |
### `to_string`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L450-L458)
```
to_string()
```
Return a string representation of this `DeviceSpec`.
| Returns |
| a string of the form /job:/replica:/task:/device::. |
### `__eq__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/device_spec.py#L395-L409)
```
__eq__(
other
)
```
Checks if the `other` DeviceSpec is same as the current instance, eg have
same value for all the internal fields.
| Args |
| `other` | Another DeviceSpec |
| Returns |
| Return `True` if `other` is also a DeviceSpec instance and has same value as the current instance. Return `False` otherwise. |
tensorflow tf.compat.v1.reduce_prod tf.compat.v1.reduce\_prod
=========================
Computes [`tf.math.multiply`](../../math/multiply) of elements across dimensions of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.reduce_prod`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_prod)
```
tf.compat.v1.reduce_prod(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None
)
```
This is the reduction operation for the elementwise [`tf.math.multiply`](../../math/multiply) op.
Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned.
#### For example:
```
x = tf.constant([[1., 2.], [3., 4.]])
tf.math.reduce_prod(x)
<tf.Tensor: shape=(), dtype=float32, numpy=24.>
tf.math.reduce_prod(x, 0)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([3., 8.], dtype=float32)>
tf.math.reduce_prod(x, 1)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 12.],
dtype=float32)>
```
| Args |
| `input_tensor` | The tensor to reduce. Should have numeric type. |
| `axis` | The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `name` | A name for the operation (optional). |
| `reduction_indices` | The old (deprecated) name for axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced tensor. |
numpy compatibility
-------------------
Equivalent to np.prod
tensorflow tf.compat.v1.to_float tf.compat.v1.to\_float
======================
Casts a tensor to type `float32`. (deprecated)
```
tf.compat.v1.to_float(
x, name='ToFloat'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.float32)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_float(tf.constant(3.14, dtype=tf.double))
<tf.Tensor: shape=(), dtype=float32, numpy=3.14>
```
After:
```
tf.cast(tf.constant(3.14, dtype=tf.double), tf.float32)
<tf.Tensor: shape=(), dtype=float32, numpy=3.14>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `float32`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `float32`. |
| programming_docs |
tensorflow tf.compat.v1.while_loop tf.compat.v1.while\_loop
========================
Repeat `body` while the condition `cond` is true.
```
tf.compat.v1.while_loop(
cond,
body,
loop_vars,
shape_invariants=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None,
maximum_iterations=None,
return_same_structure=False
)
```
`cond` is a callable returning a boolean scalar tensor. `body` is a callable returning a (possibly nested) tuple, namedtuple or list of tensors of the same arity (length and structure) and types as `loop_vars`. `loop_vars` is a (possibly nested) tuple, namedtuple or list of tensors that is passed to both `cond` and `body`. `cond` and `body` both take as many arguments as there are `loop_vars`.
In addition to regular Tensors or IndexedSlices, the body may accept and return TensorArray objects. The flows of the TensorArray objects will be appropriately forwarded between loops and during gradient calculations.
Note that `while_loop` calls `cond` and `body` *exactly once* (inside the call to `while_loop`, and not at all during `Session.run()`). `while_loop` stitches together the graph fragments created during the `cond` and `body` calls with some additional graph nodes to create the graph flow that repeats `body` until `cond` returns false.
For correctness, [`tf.while_loop()`](../../while_loop) strictly enforces shape invariants for the loop variables. A shape invariant is a (possibly partial) shape that is unchanged across the iterations of the loop. An error will be raised if the shape of a loop variable after an iteration is determined to be more general than or incompatible with its shape invariant. For example, a shape of [11, None] is more general than a shape of [11, 17], and [11, 21] is not compatible with [11, 17]. By default (if the argument `shape_invariants` is not specified), it is assumed that the initial shape of each tensor in `loop_vars` is the same in every iteration. The `shape_invariants` argument allows the caller to specify a less specific shape invariant for each loop variable, which is needed if the shape varies between iterations. The [`tf.Tensor.set_shape`](../../tensor#set_shape) function may also be used in the `body` function to indicate that the output loop variable has a particular shape. The shape invariant for SparseTensor and IndexedSlices are treated specially as follows:
a) If a loop variable is a SparseTensor, the shape invariant must be TensorShape([r]) where r is the rank of the dense tensor represented by the sparse tensor. It means the shapes of the three tensors of the SparseTensor are ([None], [None, r], [r]). NOTE: The shape invariant here is the shape of the SparseTensor.dense\_shape property. It must be the shape of a vector.
b) If a loop variable is an IndexedSlices, the shape invariant must be a shape invariant of the values tensor of the IndexedSlices. It means the shapes of the three tensors of the IndexedSlices are (shape, [shape[0]], [shape.ndims]).
`while_loop` implements non-strict semantics, enabling multiple iterations to run in parallel. The maximum number of parallel iterations can be controlled by `parallel_iterations`, which gives users some control over memory consumption and execution order. For correct programs, `while_loop` should return the same result for any parallel\_iterations > 0.
For training, TensorFlow stores the tensors that are produced in the forward inference and are needed in back propagation. These tensors are a main source of memory consumption and often cause OOM errors when training on GPUs. When the flag swap\_memory is true, we swap out these tensors from GPU to CPU. This for example allows us to train RNN models with very long sequences and large batches.
| Args |
| `cond` | A callable that represents the termination condition of the loop. |
| `body` | A callable that represents the loop body. |
| `loop_vars` | A (possibly nested) tuple, namedtuple or list of numpy array, `Tensor`, and `TensorArray` objects. |
| `shape_invariants` | The shape invariants for the loop variables. |
| `parallel_iterations` | The number of iterations allowed to run in parallel. It must be a positive integer. |
| `back_prop` | Whether backprop is enabled for this while loop. |
| `swap_memory` | Whether GPU-CPU memory swap is enabled for this loop. |
| `name` | Optional name prefix for the returned tensors. |
| `maximum_iterations` | Optional maximum number of iterations of the while loop to run. If provided, the `cond` output is AND-ed with an additional condition ensuring the number of iterations executed is no greater than `maximum_iterations`. |
| `return_same_structure` | If True, output has same structure as `loop_vars`. If eager execution is enabled, this is ignored (and always treated as True). |
| Returns |
| The output tensors for the loop variables after the loop. If `return_same_structure` is True, the return value has the same structure as `loop_vars`. If `return_same_structure` is False, the return value is a Tensor, TensorArray or IndexedSlice if the length of `loop_vars` is 1, or a list otherwise. |
| Raises |
| `TypeError` | if `cond` or `body` is not callable. |
| `ValueError` | if `loop_vars` is empty. |
#### Example:
```
i = tf.constant(0)
c = lambda i: tf.less(i, 10)
b = lambda i: tf.add(i, 1)
r = tf.while_loop(c, b, [i])
```
Example with nesting and a namedtuple:
```
import collections
Pair = collections.namedtuple('Pair', 'j, k')
ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2)))
c = lambda i, p: i < 10
b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k)))
ijk_final = tf.while_loop(c, b, ijk_0)
```
Example using shape\_invariants:
```
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 10
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
tf.while_loop(
c, b, loop_vars=[i0, m0],
shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])
```
Example which demonstrates non-strict semantics: In the following example, the final value of the counter `i` does not depend on `x`. So the `while_loop` can increment the counter parallel to updates of `x`. However, because the loop counter at one loop iteration depends on the value at the previous iteration, the loop counter itself cannot be incremented in parallel. Hence if we just want the final value of the counter (which we print on the line `print(sess.run(i))`), then `x` will never be incremented, but the counter will be updated on a single thread. Conversely, if we want the value of the output (which we print on the line `print(sess.run(out).shape)`), then the counter may be incremented on its own thread, while `x` can be incremented in parallel on a separate thread. In the extreme case, it is conceivable that the thread incrementing the counter runs until completion before `x` is incremented even a single time. The only thing that can never happen is that the thread updating `x` can never get ahead of the counter thread because the thread incrementing `x` depends on the value of the counter.
```
import tensorflow as tf
n = 10000
x = tf.constant(list(range(n)))
c = lambda i, x: i < n
b = lambda i, x: (tf.compat.v1.Print(i + 1, [i]), tf.compat.v1.Print(x + 1,
[i], "x:"))
i, out = tf.while_loop(c, b, (0, x))
with tf.compat.v1.Session() as sess:
print(sess.run(i)) # prints [0] ... [9999]
# The following line may increment the counter and x in parallel.
# The counter thread may get ahead of the other thread, but not the
# other way around. So you may see things like
# [9996] x:[9987]
# meaning that the counter thread is on iteration 9996,
# while the other thread is on iteration 9987
print(sess.run(out).shape)
```
tensorflow tf.compat.v1.RunOptions tf.compat.v1.RunOptions
=======================
A ProtocolMessage
| Attributes |
| `debug_options` | `DebugOptions debug_options` |
| `experimental` | `Experimental experimental` |
| `inter_op_thread_pool` | `int32 inter_op_thread_pool` |
| `output_partition_graphs` | `bool output_partition_graphs` |
| `report_tensor_allocations_upon_oom` | `bool report_tensor_allocations_upon_oom` |
| `timeout_in_ms` | `int64 timeout_in_ms` |
| `trace_level` | `TraceLevel trace_level` |
Child Classes
-------------
[`class Experimental`](runoptions/experimental)
| Class Variables |
| FULL\_TRACE | `3` |
| HARDWARE\_TRACE | `2` |
| NO\_TRACE | `0` |
| SOFTWARE\_TRACE | `1` |
| TraceLevel | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
tensorflow tf.compat.v1.sparse_add tf.compat.v1.sparse\_add
========================
Adds two tensors, at least one of each is a `SparseTensor`. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.add`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_add)
```
tf.compat.v1.sparse_add(
a, b, threshold=None, thresh=None
)
```
If one `SparseTensor` and one `Tensor` are passed in, returns a `Tensor`. If both arguments are `SparseTensor`s, this returns a `SparseTensor`. The order of arguments does not matter. Use vanilla [`tf.add()`](../../math/add) for adding two dense `Tensor`s.
The shapes of the two operands must match: broadcasting is not supported.
The indices of any input `SparseTensor` are assumed ordered in standard lexicographic order. If this is not the case, before this step run `SparseReorder` to restore index ordering.
If both arguments are sparse, we perform "clipping" as follows. By default, if two values sum to zero at some index, the output `SparseTensor` would still include that particular location in its index, storing a zero in the corresponding value slot. To override this, callers can specify `thresh`, indicating that if the sum has a magnitude strictly smaller than `thresh`, its corresponding value and index would then not be included. In particular, `thresh == 0.0` (default) means everything is kept and actual thresholding happens only for a positive value.
For example, suppose the logical sum of two sparse operands is (densified):
```
[ 2]
[.1 0]
[ 6 -.2]
```
Then,
* `thresh == 0` (the default): all 5 index/value pairs will be returned.
* `thresh == 0.11`: only .1 and 0 will vanish, and the remaining three index/value pairs will be returned.
* `thresh == 0.21`: .1, 0, and -.2 will vanish.
| Args |
| `a` | The first operand; `SparseTensor` or `Tensor`. |
| `b` | The second operand; `SparseTensor` or `Tensor`. At least one operand must be sparse. |
| `threshold` | An optional 0-D `Tensor` (defaults to `0`). The magnitude threshold that determines if an output value/index pair takes space. Its dtype should match that of the values if they are real; if the latter are complex64/complex128, then the dtype should be float32/float64, correspondingly. |
| `thresh` | Deprecated alias for `threshold`. |
| Returns |
| A `SparseTensor` or a `Tensor`, representing the sum. |
| Raises |
| `TypeError` | If both `a` and `b` are `Tensor`s. Use [`tf.add()`](../../math/add) instead. |
tensorflow tf.compat.v1.initialize_all_variables tf.compat.v1.initialize\_all\_variables
=======================================
See [`tf.compat.v1.global_variables_initializer`](global_variables_initializer). (deprecated)
```
tf.compat.v1.initialize_all_variables()
```
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.scatter_add tf.compat.v1.scatter\_add
=========================
Adds sparse updates to the variable referenced by `resource`.
```
tf.compat.v1.scatter_add(
ref, indices, updates, use_locking=False, name=None
)
```
This operation computes
```
# Scalar indices
ref[indices, ...] += updates[...]
# Vector indices (for each i)
ref[indices[i], ...] += updates[i, ...]
# High rank indices (for each i, ..., j)
ref[indices[i, ..., j], ...] += updates[i, ..., j, ...]
```
This operation outputs `ref` after the update is done. This makes it easier to chain operations that need to use the updated value. Duplicate entries are handled correctly: if multiple `indices` reference the same location, their contributions add.
Requires `updates.shape = indices.shape + ref.shape[1:]`.
| Args |
| `ref` | A `Variable`. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into the first dimension of `ref`. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A tensor of updated values to store in `ref`. |
| `use_locking` | An optional `bool`. Defaults to `False`. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| Same as `ref`. Returned as a convenience for operations that want to use the updated values after the update is done. |
tensorflow tf.compat.v1.assert_greater_equal tf.compat.v1.assert\_greater\_equal
===================================
Assert the condition `x >= y` holds element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_greater_equal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_greater_equal)
```
tf.compat.v1.assert_greater_equal(
x, y, data=None, summarize=None, message=None, name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.assert_greater_equal`](assert_greater_equal) is compatible with eager execution and [`tf.function`](../../function). Please use [`tf.debugging.assert_greater_equal`](../../debugging/assert_greater_equal) instead when migrating to TF2. Apart from `data`, all arguments are supported with the same argument name.
If you want to ensure the assert statements run before the potentially-invalid computation, please use [`tf.control_dependencies`](../../control_dependencies), as tf.function auto-control dependencies are insufficient for assert statements.
#### Structural Mapping to Native TF2
Before:
```
tf.compat.v1.assert_greater_equal(
x=x, y=y, data=data, summarize=summarize,
message=message, name=name)
```
After:
```
tf.debugging.assert_greater_equal(
x=x, y=y, message=message,
summarize=summarize, name=name)
```
#### TF1 & TF2 Usage Example
TF1:
```
g = tf.Graph()
with g.as_default():
a = tf.compat.v1.placeholder(tf.float32, [2])
b = tf.compat.v1.placeholder(tf.float32, [2])
result = tf.compat.v1.assert_greater_equal(a, b,
message='"a >= b" does not hold for the given inputs')
with tf.compat.v1.control_dependencies([result]):
sum_node = a + b
sess = tf.compat.v1.Session(graph=g)
val = sess.run(sum_node, feed_dict={a: [1, 2], b:[1, 0]})
```
TF2:
```
a = tf.Variable([1, 2], dtype=tf.float32)
b = tf.Variable([1, 0], dtype=tf.float32)
assert_op = tf.debugging.assert_greater_equal(a, b, message=
'"a >= b" does not hold for the given inputs')
# When working with tf.control_dependencies
with tf.control_dependencies([assert_op]):
val = a + b
```
Description
-----------
This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have `x[i] >= y[i]`. If both `x` and `y` are empty, this is trivially satisfied.
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_greater_equal(x, y)]):
output = tf.reduce_sum(x)
```
| Args |
| `x` | Numeric `Tensor`. |
| `y` | Numeric `Tensor`, same dtype as and broadcastable to `x`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_greater\_equal". |
| Returns |
| Op that raises `InvalidArgumentError` if `x >= y` is False. |
| Raises |
| `InvalidArgumentError` | if the check can be performed immediately and `x >= y` is False. The check can be performed immediately during eager execution or if `x` and `y` are statically known. |
tensorflow tf.compat.v1.GraphKeys tf.compat.v1.GraphKeys
======================
Standard names to use for graph collections.
The standard library uses various well-known names to collect and retrieve values associated with a graph. For example, the `tf.Optimizer` subclasses default to optimizing the variables collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is specified, but it is also possible to pass an explicit list of variables.
The following standard keys are defined:
* `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared across distributed environment (model variables are subset of these). See [`tf.compat.v1.global_variables`](global_variables) for more details. Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`, and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.
* `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each machine. Usually used for temporarily variables, like counters. Note: use `tf.contrib.framework.local_variable` to add to this collection.
* `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the model for inference (feed forward). Note: use `tf.contrib.framework.model_variable` to add to this collection.
* `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will be trained by an optimizer. See [`tf.compat.v1.trainable_variables`](trainable_variables) for more details.
* `SUMMARIES`: the summary `Tensor` objects that have been created in the graph. See [`tf.compat.v1.summary.merge_all`](summary/merge_all) for more details.
* `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to produce input for a computation. See [`tf.compat.v1.train.start_queue_runners`](train/start_queue_runners) for more details.
* `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also keep moving averages. See [`tf.compat.v1.moving_average_variables`](moving_average_variables) for more details.
* `REGULARIZATION_LOSSES`: regularization losses collected during graph construction.
The following standard keys are *defined*, but their collections are **not** automatically populated as many of the others are:
* `WEIGHTS`
* `BIASES`
* `ACTIVATIONS`
| Class Variables |
| ACTIVATIONS | `'activations'` |
| ASSET\_FILEPATHS | `'asset_filepaths'` |
| BIASES | `'biases'` |
| CONCATENATED\_VARIABLES | `'concatenated_variables'` |
| COND\_CONTEXT | `'cond_context'` |
| EVAL\_STEP | `'eval_step'` |
| GLOBAL\_STEP | `'global_step'` |
| GLOBAL\_VARIABLES | `'variables'` |
| INIT\_OP | `'init_op'` |
| LOCAL\_INIT\_OP | `'local_init_op'` |
| LOCAL\_RESOURCES | `'local_resources'` |
| LOCAL\_VARIABLES | `'local_variables'` |
| LOSSES | `'losses'` |
| METRIC\_VARIABLES | `'metric_variables'` |
| MODEL\_VARIABLES | `'model_variables'` |
| MOVING\_AVERAGE\_VARIABLES | `'moving_average_variables'` |
| QUEUE\_RUNNERS | `'queue_runners'` |
| READY\_FOR\_LOCAL\_INIT\_OP | `'ready_for_local_init_op'` |
| READY\_OP | `'ready_op'` |
| REGULARIZATION\_LOSSES | `'regularization_losses'` |
| RESOURCES | `'resources'` |
| SAVEABLE\_OBJECTS | `'saveable_objects'` |
| SAVERS | `'savers'` |
| SUMMARIES | `'summaries'` |
| SUMMARY\_OP | `'summary_op'` |
| TABLE\_INITIALIZERS | `'table_initializer'` |
| TRAINABLE\_RESOURCE\_VARIABLES | `'trainable_resource_variables'` |
| TRAINABLE\_VARIABLES | `'trainable_variables'` |
| TRAIN\_OP | `'train_op'` |
| UPDATE\_OPS | `'update_ops'` |
| VARIABLES | `'variables'` |
| WEIGHTS | `'weights'` |
| WHILE\_CONTEXT | `'while_context'` |
| programming_docs |
tensorflow Module: tf.compat.v1.app Module: tf.compat.v1.app
========================
Generic entry point script.
Functions
---------
[`run(...)`](app/run): Runs the program with an optional 'main' function and 'argv' list.
tensorflow tf.compat.v1.string_split tf.compat.v1.string\_split
==========================
Split elements of `source` based on `delimiter`. (deprecated arguments)
```
tf.compat.v1.string_split(
source,
sep=None,
skip_empty=True,
delimiter=None,
result_type='SparseTensor',
name=None
)
```
Let N be the size of `source` (typically N will be the batch size). Split each element of `source` based on `delimiter` and return a `SparseTensor` or `RaggedTensor` containing the split tokens. Empty tokens are ignored.
If `sep` is an empty string, each element of the `source` is split into individual strings, each containing one byte. (This includes splitting multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is treated as a set of delimiters with each considered a potential split point.
#### Examples:
```
print(tf.compat.v1.string_split(['hello world', 'a b c']))
SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...),
values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...),
dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64))
```
```
print(tf.compat.v1.string_split(['hello world', 'a b c'],
result_type="RaggedTensor"))
<tf.RaggedTensor [[b'hello', b'world'], [b'a', b'b', b'c']]>
```
| Args |
| `source` | `1-D` string `Tensor`, the strings to split. |
| `sep` | `0-D` string `Tensor`, the delimiter character, the string should be length 0 or 1. Default is ' '. |
| `skip_empty` | A `bool`. If `True`, skip the empty strings from the result. |
| `delimiter` | deprecated alias for `sep`. |
| `result_type` | The tensor type for the result: one of `"RaggedTensor"` or `"SparseTensor"`. |
| `name` | A name for the operation (optional). |
| Raises |
| `ValueError` | If delimiter is not a string. |
| Returns |
| A `SparseTensor` or `RaggedTensor` of rank `2`, the strings split according to the delimiter. The first column of the indices corresponds to the row in `source` and the second column corresponds to the index of the split component in this row. |
tensorflow tf.compat.v1.scatter_nd_update tf.compat.v1.scatter\_nd\_update
================================
Applies sparse `updates` to individual values or slices in a Variable.
```
tf.compat.v1.scatter_nd_update(
ref, indices, updates, use_locking=True, name=None
)
```
`ref` is a `Tensor` with rank `P` and `indices` is a `Tensor` of rank `Q`.
`indices` must be integer tensor, containing indices into `ref`. It must be shape `[d_0, ..., d_{Q-2}, K]` where `0 < K <= P`.
The innermost dimension of `indices` (with length `K`) corresponds to indices into elements (if `K = P`) or slices (if `K < P`) along the `K`th dimension of `ref`.
`updates` is `Tensor` of rank `Q-1+P-K` with shape:
```
[d_0, ..., d_{Q-2}, ref.shape[K], ..., ref.shape[P-1]].
```
For example, say we want to update 4 scattered elements to a rank-1 tensor to 8 elements. In Python, that update would look like this:
```
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8])
indices = tf.constant([[4], [3], [1] ,[7]])
updates = tf.constant([9, 10, 11, 12])
update = tf.compat.v1.scatter_nd_update(ref, indices, updates)
with tf.compat.v1.Session() as sess:
print sess.run(update)
```
The resulting update to ref would look like this:
```
[1, 11, 3, 10, 9, 6, 7, 12]
```
See [`tf.scatter_nd`](../../scatter_nd) for more details about how to make updates to slices.
| Args |
| `ref` | A Variable. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into ref. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A Tensor. Must have the same type as ref. A tensor of updated values to add to ref. |
| `use_locking` | An optional `bool`. Defaults to `True`. An optional bool. Defaults to True. If True, the assignment will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| The value of the variable after the update. |
tensorflow tf.compat.v1.argmin tf.compat.v1.argmin
===================
Returns the index with the smallest value across axes of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.argmin`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/argmin)
```
tf.compat.v1.argmin(
input,
axis=None,
name=None,
dimension=None,
output_type=tf.dtypes.int64
)
```
Note that in case of ties the identity of the return value is not guaranteed.
#### Usage:
```
import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.math.argmin(input = a)
c = tf.keras.backend.eval(b)
# c = 0
# here a[0] = 1 which is the smallest element of a across axis 0
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. |
| `axis` | A `Tensor`. Must be one of the following types: `int32`, `int64`. int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which axis of the input Tensor to reduce across. For vectors, use axis = 0. |
| `output_type` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.int32, tf.int64`. Defaults to [`tf.int64`](../../../tf#int64). |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `output_type`. |
tensorflow tf.compat.v1.assign_add tf.compat.v1.assign\_add
========================
Update `ref` by adding `value` to it.
```
tf.compat.v1.assign_add(
ref, value, use_locking=None, name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.assign_add`](assign_add) is mostly compatible with eager execution and [`tf.function`](../../function).
To switch to the native TF2 style, one could use method 'assign\_add' of [`tf.Variable`](../../variable):
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `ref` | `self` | In `assign_add()` method |
| `value` | `value` | In `assign_add()` method |
| `use_locking` | `use_locking` | In `assign_add()` method |
| `name` | `name` | In `assign_add()` method |
| - | `read_value` | Set to True to replicate behavior (True is default) |
#### Before & After Usage Example
Before:
```
with tf.Graph().as_default():
with tf.compat.v1.Session() as sess:
a = tf.compat.v1.Variable(0, dtype=tf.int64)
sess.run(a.initializer)
update_op = tf.compat.v1.assign_add(a, 1)
res_a = sess.run(update_op)
res_a
1
```
After:
```
b = tf.Variable(0, dtype=tf.int64)
res_b = b.assign_add(1)
res_b.numpy()
1
```
Description
-----------
This operation outputs `ref` after the update is done. This makes it easier to chain operations that need to use the reset value. Unlike [`tf.math.add`](../../math/add), this op does not broadcast. `ref` and `value` must have the same shape.
| Args |
| `ref` | A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int64`, `int32`, `uint8`, `uint16`, `int16`, `int8`, `complex64`, `complex128`, `qint8`, `quint8`, `qint32`, `half`. Should be from a `Variable` node. |
| `value` | A `Tensor`. Must have the same shape and dtype as `ref`. The value to be added to the variable. |
| `use_locking` | An optional `bool`. Defaults to `False`. If True, the addition will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| Same as `ref`. Returned as a convenience for operations that want to use the new value after the variable has been updated. |
tensorflow tf.compat.v1.reduce_sum tf.compat.v1.reduce\_sum
========================
Computes the sum of elements across dimensions of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.reduce_sum`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_sum)
```
tf.compat.v1.reduce_sum(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None
)
```
This is the reduction operation for the elementwise [`tf.math.add`](../../math/add) op.
Reduces `input_tensor` along the dimensions given in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each of the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned.
#### For example:
```
# x has a shape of (2, 3) (two rows and three columns):
x = tf.constant([[1, 1, 1], [1, 1, 1]])
x.numpy()
array([[1, 1, 1],
[1, 1, 1]], dtype=int32)
# sum all the elements
# 1 + 1 + 1 + 1 + 1+ 1 = 6
tf.reduce_sum(x).numpy()
6
# reduce along the first dimension
# the result is [1, 1, 1] + [1, 1, 1] = [2, 2, 2]
tf.reduce_sum(x, 0).numpy()
array([2, 2, 2], dtype=int32)
# reduce along the second dimension
# the result is [1, 1] + [1, 1] + [1, 1] = [3, 3]
tf.reduce_sum(x, 1).numpy()
array([3, 3], dtype=int32)
# keep the original dimensions
tf.reduce_sum(x, 1, keepdims=True).numpy()
array([[3],
[3]], dtype=int32)
# reduce along both dimensions
# the result is 1 + 1 + 1 + 1 + 1 + 1 = 6
# or, equivalently, reduce along rows, then reduce the resultant array
# [1, 1, 1] + [1, 1, 1] = [2, 2, 2]
# 2 + 2 + 2 = 6
tf.reduce_sum(x, [0, 1]).numpy()
6
```
| Args |
| `input_tensor` | The tensor to reduce. Should have numeric type. |
| `axis` | The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `name` | A name for the operation (optional). |
| `reduction_indices` | The old (deprecated) name for axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced tensor, of the same dtype as the input\_tensor. |
numpy compatibility
-------------------
Equivalent to np.sum apart the fact that numpy upcast uint8 and int32 to int64 while tensorflow returns the same dtype as the input.
tensorflow tf.compat.v1.variable_op_scope tf.compat.v1.variable\_op\_scope
================================
```
@tf_contextlib.contextmanager
tf.compat.v1.variable_op_scope(
values,
name_or_scope,
default_name=None,
initializer=None,
regularizer=None,
caching_device=None,
partitioner=None,
custom_getter=None,
reuse=None,
dtype=None,
use_resource=None,
constraint=None
)
```
tensorflow tf.compat.v1.initialize_all_tables tf.compat.v1.initialize\_all\_tables
====================================
Returns an Op that initializes all tables of the default graph. (deprecated)
```
tf.compat.v1.initialize_all_tables(
name='init_all_tables'
)
```
| Args |
| `name` | Optional name for the initialization op. |
| Returns |
| An Op that initializes all tables. Note that if there are not tables the returned Op is a NoOp. |
tensorflow tf.compat.v1.string_to_number tf.compat.v1.string\_to\_number
===============================
Converts each string in the input Tensor to the specified numeric type.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.strings.to_number`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/string_to_number)
```
tf.compat.v1.string_to_number(
string_tensor=None,
out_type=tf.dtypes.float32,
name=None,
input=None
)
```
(Note that int32 overflow results in an error while float overflow results in a rounded value.)
#### Example:
```
strings = ["5.0", "3.0", "7.0"]
tf.strings.to_number(strings)
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([5., 3., 7.], dtype=float32)>
```
| Args |
| `string_tensor` | A `Tensor` of type `string`. |
| `out_type` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.float32, tf.float64, tf.int32, tf.int64`. Defaults to [`tf.float32`](../../../tf#float32). The numeric type to interpret each string in `string_tensor` as. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `out_type`. |
tensorflow tf.compat.v1.pad tf.compat.v1.pad
================
Pads a tensor.
```
tf.compat.v1.pad(
tensor, paddings, mode='CONSTANT', name=None, constant_values=0
)
```
This operation pads a `tensor` according to the `paddings` you specify. `paddings` is an integer tensor with shape `[n, 2]`, where n is the rank of `tensor`. For each dimension D of `input`, `paddings[D, 0]` indicates how many values to add before the contents of `tensor` in that dimension, and `paddings[D, 1]` indicates how many values to add after the contents of `tensor` in that dimension. If `mode` is "REFLECT" then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than `tensor.dim_size(D) - 1`. If `mode` is "SYMMETRIC" then both `paddings[D, 0]` and `paddings[D, 1]` must be no greater than `tensor.dim_size(D)`.
The padded size of each dimension D of the output is:
`paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1]`
#### For example:
```
t = tf.constant([[1, 2, 3], [4, 5, 6]])
paddings = tf.constant([[1, 1,], [2, 2]])
# 'constant_values' is 0.
# rank of 't' is 2.
tf.pad(t, paddings, "CONSTANT") # [[0, 0, 0, 0, 0, 0, 0],
# [0, 0, 1, 2, 3, 0, 0],
# [0, 0, 4, 5, 6, 0, 0],
# [0, 0, 0, 0, 0, 0, 0]]
tf.pad(t, paddings, "REFLECT") # [[6, 5, 4, 5, 6, 5, 4],
# [3, 2, 1, 2, 3, 2, 1],
# [6, 5, 4, 5, 6, 5, 4],
# [3, 2, 1, 2, 3, 2, 1]]
tf.pad(t, paddings, "SYMMETRIC") # [[2, 1, 1, 2, 3, 3, 2],
# [2, 1, 1, 2, 3, 3, 2],
# [5, 4, 4, 5, 6, 6, 5],
# [5, 4, 4, 5, 6, 6, 5]]
```
| Args |
| `tensor` | A `Tensor`. |
| `paddings` | A `Tensor` of type `int32`. |
| `mode` | One of "CONSTANT", "REFLECT", or "SYMMETRIC" (case-insensitive) |
| `name` | A name for the operation (optional). |
| `constant_values` | In "CONSTANT" mode, the scalar pad value to use. Must be same type as `tensor`. |
| Returns |
| A `Tensor`. Has the same type as `tensor`. |
| Raises |
| `ValueError` | When mode is not one of "CONSTANT", "REFLECT", or "SYMMETRIC". |
tensorflow tf.compat.v1.to_int64 tf.compat.v1.to\_int64
======================
Casts a tensor to type `int64`. (deprecated)
```
tf.compat.v1.to_int64(
x, name='ToInt64'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.int64)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_int64(tf.constant(1, dtype=tf.int32))
<tf.Tensor: shape=(), dtype=int64, numpy=1>
```
After:
```
tf.cast(tf.constant(1, dtype=tf.int32), tf.int64)
<tf.Tensor: shape=(), dtype=int64, numpy=1>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `int64`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `int64`. |
tensorflow tf.compat.v1.WholeFileReader tf.compat.v1.WholeFileReader
============================
A Reader that outputs the entire contents of a file as a value.
Inherits From: [`ReaderBase`](readerbase)
```
tf.compat.v1.WholeFileReader(
name=None
)
```
To use, enqueue filenames in a Queue. The output of Read will be a filename (key) and the contents of that file (value).
See ReaderBase for supported methods.
| Args |
| `name` | A name for the operation (optional). |
| Attributes |
| `reader_ref` | Op that implements the reader. |
| `supports_serialize` | Whether the Reader implementation can serialize its state. |
Methods
-------
### `num_records_produced`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L328-L346)
```
num_records_produced(
name=None
)
```
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `num_work_units_completed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L348-L362)
```
num_work_units_completed(
name=None
)
```
Returns the number of work units this reader has finished processing.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L261-L288)
```
read(
queue, name=None
)
```
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (key, value). |
| `key` | A string scalar Tensor. |
| `value` | A string scalar Tensor. |
### `read_up_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L290-L326)
```
read_up_to(
queue, num_records, name=None
)
```
Returns up to num\_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num\_records even before the last batch.
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `num_records` | Number of records to read. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (keys, values). |
| `keys` | A 1-D string Tensor. |
| `values` | A 1-D string Tensor. |
### `reset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L406-L418)
```
reset(
name=None
)
```
Restore a reader to its initial clean state.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `restore_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L381-L399)
```
restore_state(
state, name=None
)
```
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
| Args |
| `state` | A string Tensor. Result of a SerializeState of a Reader with matching type. |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `serialize_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L364-L379)
```
serialize_state(
name=None
)
```
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A string Tensor. |
eager compatibility
-------------------
Readers are not compatible with eager execution. Instead, please use [`tf.data`](../../data) to get data into your model.
| programming_docs |
tensorflow tf.compat.v1.min_max_variable_partitioner tf.compat.v1.min\_max\_variable\_partitioner
============================================
Partitioner to allocate minimum size per slice.
```
tf.compat.v1.min_max_variable_partitioner(
max_partitions=1,
axis=0,
min_slice_size=(256 << 10),
bytes_per_string_element=16
)
```
Returns a partitioner that partitions the variable of given shape and dtype such that each partition has a minimum of `min_slice_size` slice of the variable. The maximum number of such partitions (upper bound) is given by `max_partitions`.
| Args |
| `max_partitions` | Upper bound on the number of partitions. Defaults to 1. |
| `axis` | Axis along which to partition the variable. Defaults to 0. |
| `min_slice_size` | Minimum size of the variable slice per partition. Defaults to 256K. |
| `bytes_per_string_element` | If the `Variable` is of type string, this provides an estimate of how large each scalar in the `Variable` is. |
| Returns |
| A partition function usable as the `partitioner` argument to `variable_scope` and `get_variable`. |
tensorflow Module: tf.compat.v1.saved_model Module: tf.compat.v1.saved\_model
=================================
Public API for tf.saved\_model namespace.
Modules
-------
[`builder`](saved_model/builder) module: SavedModel builder.
[`constants`](saved_model/constants) module: Constants for SavedModel save and restore operations.
[`experimental`](saved_model/experimental) module: Public API for tf.saved\_model.experimental namespace.
[`loader`](saved_model/loader) module: Loader functionality for SavedModel with hermetic, language-neutral exports.
[`main_op`](saved_model/main_op) module: SavedModel main op.
[`signature_constants`](saved_model/signature_constants) module: Signature constants for SavedModel save and restore operations.
[`signature_def_utils`](saved_model/signature_def_utils) module: SignatureDef utility functions.
[`tag_constants`](saved_model/tag_constants) module: Common tags used for graphs in SavedModel.
[`utils`](saved_model/utils) module: SavedModel utility functions.
Classes
-------
[`class Asset`](../../saved_model/asset): Represents a file asset to hermetically include in a SavedModel.
[`class Builder`](saved_model/builder): Builds the `SavedModel` protocol buffer and saves variables and assets.
[`class SaveOptions`](../../saved_model/saveoptions): Options for saving to SavedModel.
Functions
---------
[`build_signature_def(...)`](saved_model/build_signature_def): Utility function to build a SignatureDef protocol buffer.
[`build_tensor_info(...)`](saved_model/build_tensor_info): Utility function to build TensorInfo proto from a Tensor. (deprecated)
[`classification_signature_def(...)`](saved_model/classification_signature_def): Creates classification signature from given examples and predictions.
[`contains_saved_model(...)`](saved_model/contains_saved_model): Checks whether the provided export directory could contain a SavedModel.
[`get_tensor_from_tensor_info(...)`](saved_model/get_tensor_from_tensor_info): Returns the Tensor or CompositeTensor described by a TensorInfo proto. (deprecated)
[`is_valid_signature(...)`](saved_model/is_valid_signature): Determine whether a SignatureDef can be served by TensorFlow Serving.
[`load(...)`](saved_model/load): Loads the model from a SavedModel as specified by tags. (deprecated)
[`load_v2(...)`](../../saved_model/load): Load a SavedModel from `export_dir`.
[`main_op_with_restore(...)`](saved_model/main_op_with_restore): Returns a main op to init variables, tables and restore the graph. (deprecated)
[`maybe_saved_model_directory(...)`](saved_model/contains_saved_model): Checks whether the provided export directory could contain a SavedModel.
[`predict_signature_def(...)`](saved_model/predict_signature_def): Creates prediction signature from given inputs and outputs.
[`regression_signature_def(...)`](saved_model/regression_signature_def): Creates regression signature from given examples and predictions.
[`save(...)`](../../saved_model/save): Exports a [tf.Module](https://www.tensorflow.org/api_docs/python/tf/Module) (and subclasses) `obj` to [SavedModel format](https://www.tensorflow.org/guide/saved_model#the_savedmodel_format_on_disk).
[`simple_save(...)`](saved_model/simple_save): Convenience function to build a SavedModel suitable for serving. (deprecated)
| Other Members |
| ASSETS\_DIRECTORY | `'assets'` |
| ASSETS\_KEY | `'saved_model_assets'` |
| CLASSIFY\_INPUTS | `'inputs'` |
| CLASSIFY\_METHOD\_NAME | `'tensorflow/serving/classify'` |
| CLASSIFY\_OUTPUT\_CLASSES | `'classes'` |
| CLASSIFY\_OUTPUT\_SCORES | `'scores'` |
| DEBUG\_DIRECTORY | `'debug'` |
| DEBUG\_INFO\_FILENAME\_PB | `'saved_model_debug_info.pb'` |
| DEFAULT\_SERVING\_SIGNATURE\_DEF\_KEY | `'serving_default'` |
| GPU | `'gpu'` |
| LEGACY\_INIT\_OP\_KEY | `'legacy_init_op'` |
| MAIN\_OP\_KEY | `'saved_model_main_op'` |
| PREDICT\_INPUTS | `'inputs'` |
| PREDICT\_METHOD\_NAME | `'tensorflow/serving/predict'` |
| PREDICT\_OUTPUTS | `'outputs'` |
| REGRESS\_INPUTS | `'inputs'` |
| REGRESS\_METHOD\_NAME | `'tensorflow/serving/regress'` |
| REGRESS\_OUTPUTS | `'outputs'` |
| SAVED\_MODEL\_FILENAME\_PB | `'saved_model.pb'` |
| SAVED\_MODEL\_FILENAME\_PBTXT | `'saved_model.pbtxt'` |
| SAVED\_MODEL\_SCHEMA\_VERSION | `1` |
| SERVING | `'serve'` |
| TPU | `'tpu'` |
| TRAINING | `'train'` |
| VARIABLES\_DIRECTORY | `'variables'` |
| VARIABLES\_FILENAME | `'variables'` |
tensorflow tf.compat.v1.Session tf.compat.v1.Session
====================
A class for running TensorFlow operations.
```
tf.compat.v1.Session(
target='', graph=None, config=None
)
```
Migrate to TF2
--------------
`Session` does not work with either eager execution or [`tf.function`](../../function), and you should not invoke it directly. To migrate code that uses sessions to TF2, rewrite the code without it. See the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls.
Description
-----------
A `Session` object encapsulates the environment in which `Operation` objects are executed, and `Tensor` objects are evaluated. For example:
```
tf.compat.v1.disable_eager_execution() # need to disable eager in TF2.x
# Build a graph.
a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
# Launch the graph in a session.
sess = tf.compat.v1.Session()
# Evaluate the tensor `c`.
print(sess.run(c)) # prints 30.0
```
A session may own resources, such as [`tf.Variable`](../../variable), [`tf.queue.QueueBase`](../../queue/queuebase), and [`tf.compat.v1.ReaderBase`](readerbase). It is important to release these resources when they are no longer required. To do this, either invoke the `tf.Session.close` method on the session, or use the session as a context manager. The following two examples are equivalent:
```
# Using the `close()` method.
sess = tf.compat.v1.Session()
sess.run(...)
sess.close()
# Using the context manager.
with tf.compat.v1.Session() as sess:
sess.run(...)
```
The [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) protocol buffer exposes various configuration options for a session. For example, to create a session that uses soft constraints for device placement, and log the resulting placement decisions, create a session as follows:
```
# Launch the graph in a session that allows soft device placement and
# logs the placement decisions.
sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(
allow_soft_placement=True,
log_device_placement=True))
```
| Args |
| `target` | (Optional.) The execution engine to connect to. Defaults to using an in-process engine. See [Distributed TensorFlow](https://tensorflow.org/deploy/distributed) for more examples. |
| `graph` | (Optional.) The `Graph` to be launched (described above). |
| `config` | (Optional.) A [`ConfigProto`](https://www.tensorflow.org/code/tensorflow/core/protobuf/config.proto) protocol buffer with configuration options for the session. |
| Attributes |
| `graph` | The graph that was launched in this session. |
| `graph_def` | A serializable version of the underlying TensorFlow graph. |
| `sess_str` | The TensorFlow process to which this session will connect. |
Methods
-------
### `as_default`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L803-L856)
```
as_default()
```
Returns a context manager that makes this object the default session.
Use with the `with` keyword to specify that calls to [`tf.Operation.run`](../../operation#run) or [`tf.Tensor.eval`](../../tensor#eval) should be executed in this session.
```
c = tf.constant(..)
sess = tf.compat.v1.Session()
with sess.as_default():
assert tf.compat.v1.get_default_session() is sess
print(c.eval())
```
To get the current default session, use [`tf.compat.v1.get_default_session`](get_default_session).
>
> **Note:** The `as_default` context manager *does not* close the session when you exit the context, and you must close the session explicitly.
>
```
c = tf.constant(...)
sess = tf.compat.v1.Session()
with sess.as_default():
print(c.eval())
# ...
with sess.as_default():
print(c.eval())
sess.close()
```
Alternatively, you can use `with tf.compat.v1.Session():` to create a session that is automatically closed on exiting the context, including when an uncaught exception is raised.
>
> **Note:** The default session is a property of the current thread. If you create a new thread, and wish to use the default session in that thread, you must explicitly add a `with sess.as_default():` in that thread's function.
>
>
> **Note:** Entering a `with sess.as_default():` block does not affect the current default graph. If you are using multiple graphs, and `sess.graph` is different from the value of [`tf.compat.v1.get_default_graph`](get_default_graph), you must explicitly enter a `with sess.graph.as_default():` block to make `sess.graph` the default graph.
>
| Returns |
| A context manager using this session as the default session. |
### `close`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L754-L765)
```
close()
```
Closes this session.
Calling this method frees all resources associated with the session.
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses if an error occurs while closing the TensorFlow session. |
### `list_devices`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L716-L752)
```
list_devices()
```
Lists available devices in this session.
```
devices = sess.list_devices()
for d in devices:
print(d.name)
```
#### Where:
Each element in the list has the following properties
* **`name`**: A string with the full name of the device. ex: `/job:worker/replica:0/task:3/device:CPU:0`
* **`device_type`**: The type of the device (e.g. `CPU`, `GPU`, `TPU`.)
* **`memory_limit`**: The maximum amount of memory available on the device. Note: depending on the device, it is possible the usable memory could be substantially less.
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If it encounters an error (e.g. session is in an invalid state, or network errors occur). |
| Returns |
| A list of devices in the session. |
### `make_callable`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1196-L1320)
```
make_callable(
fetches, feed_list=None, accept_options=False
)
```
Returns a Python callable that runs a particular step.
The returned callable will take `len(feed_list)` arguments whose types must be compatible feed values for the respective elements of `feed_list`. For example, if element `i` of `feed_list` is a [`tf.Tensor`](../../tensor), the `i`th argument to the returned callable must be a numpy ndarray (or something convertible to an ndarray) with matching element type and shape. See `tf.Session.run` for details of the allowable feed key and value types.
The returned callable will have the same return type as `tf.Session.run(fetches, ...)`. For example, if `fetches` is a [`tf.Tensor`](../../tensor), the callable will return a numpy ndarray; if `fetches` is a [`tf.Operation`](../../operation), it will return `None`.
| Args |
| `fetches` | A value or list of values to fetch. See `tf.Session.run` for details of the allowable fetch types. |
| `feed_list` | (Optional.) A list of `feed_dict` keys. See `tf.Session.run` for details of the allowable feed key types. |
| `accept_options` | (Optional.) If `True`, the returned `Callable` will be able to accept [`tf.compat.v1.RunOptions`](runoptions) and [`tf.compat.v1.RunMetadata`](runmetadata) as optional keyword arguments `options` and `run_metadata`, respectively, with the same syntax and semantics as `tf.Session.run`, which is useful for certain use cases (profiling and debugging) but will result in measurable slowdown of the `Callable`'s performance. Default: `False`. |
| Returns |
| A function that when called will execute the step defined by `feed_list` and `fetches` in this session. |
| Raises |
| `TypeError` | If `fetches` or `feed_list` cannot be interpreted as arguments to `tf.Session.run`. |
### `partial_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L979-L1024)
```
partial_run(
handle, fetches, feed_dict=None
)
```
Continues the execution with more feeds and fetches.
This is EXPERIMENTAL and subject to change.
To use partial execution, a user first calls `partial_run_setup()` and then a sequence of `partial_run()`. `partial_run_setup` specifies the list of feeds and fetches that will be used in the subsequent `partial_run` calls.
The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. See run() for more information.
Below is a simple example:
```
a = array_ops.placeholder(dtypes.float32, shape=[])
b = array_ops.placeholder(dtypes.float32, shape=[])
c = array_ops.placeholder(dtypes.float32, shape=[])
r1 = math_ops.add(a, b)
r2 = math_ops.multiply(r1, c)
h = sess.partial_run_setup([r1, r2], [a, b, c])
res = sess.partial_run(h, r1, feed_dict={a: 1, b: 2})
res = sess.partial_run(h, r2, feed_dict={c: res})
```
| Args |
| `handle` | A handle for a sequence of partial runs. |
| `fetches` | A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (see documentation for `run`). |
| `feed_dict` | A dictionary that maps graph elements to values (described above). |
| Returns |
| Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (see documentation for `run`). |
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses on error. |
### `partial_run_setup`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1026-L1101)
```
partial_run_setup(
fetches, feeds=None
)
```
Sets up a graph with feeds and fetches for partial run.
This is EXPERIMENTAL and subject to change.
Note that contrary to `run`, `feeds` only specifies the graph elements. The tensors will be supplied by the subsequent `partial_run` calls.
| Args |
| `fetches` | A single graph element, or a list of graph elements. |
| `feeds` | A single graph element, or a list of graph elements. |
| Returns |
| A handle for partial run. |
| Raises |
| `RuntimeError` | If this `Session` is in an invalid state (e.g. has been closed). |
| `TypeError` | If `fetches` or `feed_dict` keys are of an inappropriate type. |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses if a TensorFlow error happens. |
### `reset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1660-L1692)
```
@staticmethod
reset(
target, containers=None, config=None
)
```
Resets resource containers on `target`, and close all connected sessions.
A resource container is distributed across all workers in the same cluster as `target`. When a resource container on `target` is reset, resources associated with that container will be cleared. In particular, all Variables in the container will become undefined: they lose their values and shapes.
#### NOTE:
(i) reset() is currently only implemented for distributed sessions. (ii) Any sessions on the master named by `target` will be closed.
If no resource containers are provided, all containers are reset.
| Args |
| `target` | The execution engine to connect to. |
| `containers` | A list of resource container name strings, or `None` if all of all the containers are to be reset. |
| `config` | (Optional.) Protocol buffer with configuration options. |
| Raises |
| [`tf.errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Or one of its subclasses if an error occurs while resetting containers. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L858-L977)
```
run(
fetches, feed_dict=None, options=None, run_metadata=None
)
```
Runs operations and evaluates tensors in `fetches`.
This method runs one "step" of TensorFlow computation, by running the necessary graph fragment to execute every `Operation` and evaluate every `Tensor` in `fetches`, substituting the values in `feed_dict` for the corresponding input values.
The `fetches` argument may be a single graph element, or an arbitrarily nested list, tuple, namedtuple, dict, or OrderedDict containing graph elements at its leaves. A graph element can be one of the following types:
* A [`tf.Operation`](../../operation). The corresponding fetched value will be `None`.
* A [`tf.Tensor`](../../tensor). The corresponding fetched value will be a numpy ndarray containing the value of that tensor.
* A [`tf.sparse.SparseTensor`](../../sparse/sparsetensor). The corresponding fetched value will be a [`tf.compat.v1.SparseTensorValue`](sparsetensorvalue) containing the value of that sparse tensor.
* A `get_tensor_handle` op. The corresponding fetched value will be a numpy ndarray containing the handle of that tensor.
* A `string` which is the name of a tensor or operation in the graph.
The value returned by `run()` has the same shape as the `fetches` argument, where the leaves are replaced by the corresponding values returned by TensorFlow.
#### Example:
```
a = tf.constant([10, 20])
b = tf.constant([1.0, 2.0])
# 'fetches' can be a singleton
v = session.run(a)
# v is the numpy array [10, 20]
# 'fetches' can be a list.
v = session.run([a, b])
# v is a Python list with 2 numpy arrays: the 1-D array [10, 20] and the
# 1-D array [1.0, 2.0]
# 'fetches' can be arbitrary lists, tuples, namedtuple, dicts:
MyData = collections.namedtuple('MyData', ['a', 'b'])
v = session.run({'k1': MyData(a, b), 'k2': [b, a]})
# v is a dict with
# v['k1'] is a MyData namedtuple with 'a' (the numpy array [10, 20]) and
# 'b' (the numpy array [1.0, 2.0])
# v['k2'] is a list with the numpy array [1.0, 2.0] and the numpy array
# [10, 20].
```
The optional `feed_dict` argument allows the caller to override the value of tensors in the graph. Each key in `feed_dict` can be one of the following types:
* If the key is a [`tf.Tensor`](../../tensor), the value may be a Python scalar, string, list, or numpy ndarray that can be converted to the same `dtype` as that tensor. Additionally, if the key is a [`tf.compat.v1.placeholder`](placeholder), the shape of the value will be checked for compatibility with the placeholder.
* If the key is a [`tf.sparse.SparseTensor`](../../sparse/sparsetensor), the value should be a [`tf.compat.v1.SparseTensorValue`](sparsetensorvalue).
* If the key is a nested tuple of `Tensor`s or `SparseTensor`s, the value should be a nested tuple with the same structure that maps to their corresponding values as above.
Each value in `feed_dict` must be convertible to a numpy array of the dtype of the corresponding key.
The optional `options` argument expects a [`RunOptions`] proto. The options allow controlling the behavior of this particular step (e.g. turning tracing on).
The optional `run_metadata` argument expects a [`RunMetadata`] proto. When appropriate, the non-Tensor output of this step will be collected there. For example, when users turn on tracing in `options`, the profiled info will be collected into this argument and passed back.
| Args |
| `fetches` | A single graph element, a list of graph elements, or a dictionary whose values are graph elements or lists of graph elements (described above). |
| `feed_dict` | A dictionary that maps graph elements to values (described above). |
| `options` | A [`RunOptions`] protocol buffer |
| `run_metadata` | A [`RunMetadata`] protocol buffer |
| Returns |
| Either a single value if `fetches` is a single graph element, or a list of values if `fetches` is a list, or a dictionary with the same keys as `fetches` if that is a dictionary (described above). Order in which `fetches` operations are evaluated inside the call is undefined. |
| Raises |
| `RuntimeError` | If this `Session` is in an invalid state (e.g. has been closed). |
| `TypeError` | If `fetches` or `feed_dict` keys are of an inappropriate type. |
| `ValueError` | If `fetches` or `feed_dict` keys are invalid or refer to a `Tensor` that doesn't exist. |
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1608-L1618)
```
__enter__()
```
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/client/session.py#L1620-L1658)
```
__exit__(
exec_type, exec_value, exec_tb
)
```
| programming_docs |
tensorflow Module: tf.compat.v1.math Module: tf.compat.v1.math
=========================
Math Operations.
>
> **Note:** Functions taking `Tensor` arguments can also take anything accepted by [`tf.convert_to_tensor`](../../convert_to_tensor).
>
>
> **Note:** Elementwise binary operations in TensorFlow follow [numpy-style broadcasting](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).
>
TensorFlow provides a variety of math functions including:
* Basic arithmetic operators and trigonometric functions.
* Special math functions (like: [`tf.math.igamma`](../../math/igamma) and [`tf.math.zeta`](../../math/zeta))
* Complex number functions (like: [`tf.math.imag`](../../math/imag) and [`tf.math.angle`](../../math/angle))
* Reductions and scans (like: [`tf.math.reduce_mean`](../../math/reduce_mean) and [`tf.math.cumsum`](../../math/cumsum))
* Segment functions (like: [`tf.math.segment_sum`](../../math/segment_sum))
See: [`tf.linalg`](../../linalg) for matrix and tensor functions.
About Segmentation
------------------
TensorFlow provides several operations that you can use to perform common math computations on tensor segments. Here a segmentation is a partitioning of a tensor along the first dimension, i.e. it defines a mapping from the first dimension onto `segment_ids`. The `segment_ids` tensor should be the size of the first dimension, `d0`, with consecutive IDs in the range `0` to `k`, where `k<d0`. In particular, a segmentation of a matrix tensor is a mapping of rows to segments.
#### For example:
```
c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.math.segment_sum(c, tf.constant([0, 0, 1]))
# ==> [[0 0 0 0]
# [5 6 7 8]]
```
The standard `segment_*` functions assert that the segment indices are sorted. If you have unsorted indices use the equivalent `unsorted_segment_` function. These functions take an additional argument `num_segments` so that the output tensor can be efficiently allocated.
```
c = tf.constant([[1,2,3,4], [-1,-2,-3,-4], [5,6,7,8]])
tf.math.unsorted_segment_sum(c, tf.constant([0, 1, 0]), num_segments=2)
# ==> [[ 6, 8, 10, 12],
# [-1, -2, -3, -4]]
```
Modules
-------
[`special`](math/special) module: Public API for tf.math.special namespace.
Functions
---------
[`abs(...)`](../../math/abs): Computes the absolute value of a tensor.
[`accumulate_n(...)`](../../math/accumulate_n): Returns the element-wise sum of a list of tensors.
[`acos(...)`](../../math/acos): Computes acos of x element-wise.
[`acosh(...)`](../../math/acosh): Computes inverse hyperbolic cosine of x element-wise.
[`add(...)`](../../math/add): Returns x + y element-wise.
[`add_n(...)`](../../math/add_n): Adds all input tensors element-wise.
[`angle(...)`](../../math/angle): Returns the element-wise argument of a complex (or real) tensor.
[`argmax(...)`](argmax): Returns the index with the largest value across axes of a tensor. (deprecated arguments)
[`argmin(...)`](argmin): Returns the index with the smallest value across axes of a tensor. (deprecated arguments)
[`asin(...)`](../../math/asin): Computes the trignometric inverse sine of x element-wise.
[`asinh(...)`](../../math/asinh): Computes inverse hyperbolic sine of x element-wise.
[`atan(...)`](../../math/atan): Computes the trignometric inverse tangent of x element-wise.
[`atan2(...)`](../../math/atan2): Computes arctangent of `y/x` element-wise, respecting signs of the arguments.
[`atanh(...)`](../../math/atanh): Computes inverse hyperbolic tangent of x element-wise.
[`bessel_i0(...)`](../../math/bessel_i0): Computes the Bessel i0 function of `x` element-wise.
[`bessel_i0e(...)`](../../math/bessel_i0e): Computes the Bessel i0e function of `x` element-wise.
[`bessel_i1(...)`](../../math/bessel_i1): Computes the Bessel i1 function of `x` element-wise.
[`bessel_i1e(...)`](../../math/bessel_i1e): Computes the Bessel i1e function of `x` element-wise.
[`betainc(...)`](../../math/betainc): Compute the regularized incomplete beta integral \(I\_x(a, b)\).
[`bincount(...)`](bincount): Counts the number of occurrences of each value in an integer array.
[`ceil(...)`](../../math/ceil): Return the ceiling of the input, element-wise.
[`confusion_matrix(...)`](confusion_matrix): Computes the confusion matrix from predictions and labels.
[`conj(...)`](../../math/conj): Returns the complex conjugate of a complex number.
[`cos(...)`](../../math/cos): Computes cos of x element-wise.
[`cosh(...)`](../../math/cosh): Computes hyperbolic cosine of x element-wise.
[`count_nonzero(...)`](count_nonzero): Computes number of nonzero elements across dimensions of a tensor. (deprecated arguments) (deprecated arguments)
[`cumprod(...)`](../../math/cumprod): Compute the cumulative product of the tensor `x` along `axis`.
[`cumsum(...)`](../../math/cumsum): Compute the cumulative sum of the tensor `x` along `axis`.
[`cumulative_logsumexp(...)`](../../math/cumulative_logsumexp): Compute the cumulative log-sum-exp of the tensor `x` along `axis`.
[`digamma(...)`](../../math/digamma): Computes Psi, the derivative of Lgamma (the log of the absolute value of
[`divide(...)`](../../math/divide): Computes Python style division of `x` by `y`.
[`divide_no_nan(...)`](../../math/divide_no_nan): Computes a safe divide which returns 0 if `y` (denominator) is zero.
[`equal(...)`](../../math/equal): Returns the truth value of (x == y) element-wise.
[`erf(...)`](../../math/erf): Computes the [Gauss error function](https://en.wikipedia.org/wiki/Error_function) of `x` element-wise. In statistics, for non-negative values of \(x\), the error function has the following interpretation: for a random variable \(Y\) that is normally distributed with mean 0 and variance \(1/\sqrt{2}\), \(erf(x)\) is the probability that \(Y\) falls in the range \([−x, x]\).
[`erfc(...)`](../../math/erfc): Computes the complementary error function of `x` element-wise.
[`erfcinv(...)`](../../math/erfcinv): Computes the inverse of complementary error function.
[`erfinv(...)`](../../math/erfinv): Compute inverse error function.
[`exp(...)`](../../math/exp): Computes exponential of x element-wise. \(y = e^x\).
[`expm1(...)`](../../math/expm1): Computes `exp(x) - 1` element-wise.
[`floor(...)`](../../math/floor): Returns element-wise largest integer not greater than x.
[`floordiv(...)`](../../math/floordiv): Divides `x / y` elementwise, rounding toward the most negative integer.
[`floormod(...)`](../../math/floormod): Returns element-wise remainder of division. When `x < 0` xor `y < 0` is
[`greater(...)`](../../math/greater): Returns the truth value of (x > y) element-wise.
[`greater_equal(...)`](../../math/greater_equal): Returns the truth value of (x >= y) element-wise.
[`igamma(...)`](../../math/igamma): Compute the lower regularized incomplete Gamma function `P(a, x)`.
[`igammac(...)`](../../math/igammac): Compute the upper regularized incomplete Gamma function `Q(a, x)`.
[`imag(...)`](../../math/imag): Returns the imaginary part of a complex (or real) tensor.
[`in_top_k(...)`](math/in_top_k): Says whether the targets are in the top `K` predictions.
[`invert_permutation(...)`](../../math/invert_permutation): Computes the inverse permutation of a tensor.
[`is_finite(...)`](../../math/is_finite): Returns which elements of x are finite.
[`is_inf(...)`](../../math/is_inf): Returns which elements of x are Inf.
[`is_nan(...)`](../../math/is_nan): Returns which elements of x are NaN.
[`is_non_decreasing(...)`](../../math/is_non_decreasing): Returns `True` if `x` is non-decreasing.
[`is_strictly_increasing(...)`](../../math/is_strictly_increasing): Returns `True` if `x` is strictly increasing.
[`l2_normalize(...)`](../../math/l2_normalize): Normalizes along dimension `axis` using an L2 norm. (deprecated arguments)
[`lbeta(...)`](../../math/lbeta): Computes \(ln(|Beta(x)|)\), reducing along the last dimension.
[`less(...)`](../../math/less): Returns the truth value of (x < y) element-wise.
[`less_equal(...)`](../../math/less_equal): Returns the truth value of (x <= y) element-wise.
[`lgamma(...)`](../../math/lgamma): Computes the log of the absolute value of `Gamma(x)` element-wise.
[`log(...)`](../../math/log): Computes natural logarithm of x element-wise.
[`log1p(...)`](../../math/log1p): Computes natural logarithm of (1 + x) element-wise.
[`log_sigmoid(...)`](../../math/log_sigmoid): Computes log sigmoid of `x` element-wise.
[`log_softmax(...)`](math/log_softmax): Computes log softmax activations. (deprecated arguments)
[`logical_and(...)`](../../math/logical_and): Returns the truth value of x AND y element-wise.
[`logical_not(...)`](../../math/logical_not): Returns the truth value of `NOT x` element-wise.
[`logical_or(...)`](../../math/logical_or): Returns the truth value of x OR y element-wise.
[`logical_xor(...)`](../../math/logical_xor): Logical XOR function.
[`maximum(...)`](../../math/maximum): Returns the max of x and y (i.e. x > y ? x : y) element-wise.
[`minimum(...)`](../../math/minimum): Returns the min of x and y (i.e. x < y ? x : y) element-wise.
[`mod(...)`](../../math/floormod): Returns element-wise remainder of division. When `x < 0` xor `y < 0` is
[`multiply(...)`](../../math/multiply): Returns an element-wise x \* y.
[`multiply_no_nan(...)`](../../math/multiply_no_nan): Computes the product of x and y and returns 0 if the y is zero, even if x is NaN or infinite.
[`ndtri(...)`](../../math/ndtri): Compute quantile of Standard Normal.
[`negative(...)`](../../math/negative): Computes numerical negative value element-wise.
[`nextafter(...)`](../../math/nextafter): Returns the next representable value of `x1` in the direction of `x2`, element-wise.
[`not_equal(...)`](../../math/not_equal): Returns the truth value of (x != y) element-wise.
[`polygamma(...)`](../../math/polygamma): Compute the polygamma function \(\psi^{(n)}(x)\).
[`polyval(...)`](../../math/polyval): Computes the elementwise value of a polynomial.
[`pow(...)`](../../math/pow): Computes the power of one value to another.
[`real(...)`](../../math/real): Returns the real part of a complex (or real) tensor.
[`reciprocal(...)`](../../math/reciprocal): Computes the reciprocal of x element-wise.
[`reciprocal_no_nan(...)`](../../math/reciprocal_no_nan): Performs a safe reciprocal operation, element wise.
[`reduce_all(...)`](reduce_all): Computes [`tf.math.logical_and`](../../math/logical_and) of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_any(...)`](reduce_any): Computes [`tf.math.logical_or`](../../math/logical_or) of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_euclidean_norm(...)`](../../math/reduce_euclidean_norm): Computes the Euclidean norm of elements across dimensions of a tensor.
[`reduce_logsumexp(...)`](reduce_logsumexp): Computes log(sum(exp(elements across dimensions of a tensor))). (deprecated arguments)
[`reduce_max(...)`](reduce_max): Computes [`tf.math.maximum`](../../math/maximum) of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_mean(...)`](reduce_mean): Computes the mean of elements across dimensions of a tensor.
[`reduce_min(...)`](reduce_min): Computes the [`tf.math.minimum`](../../math/minimum) of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_prod(...)`](reduce_prod): Computes [`tf.math.multiply`](../../math/multiply) of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_std(...)`](../../math/reduce_std): Computes the standard deviation of elements across dimensions of a tensor.
[`reduce_sum(...)`](reduce_sum): Computes the sum of elements across dimensions of a tensor. (deprecated arguments)
[`reduce_variance(...)`](../../math/reduce_variance): Computes the variance of elements across dimensions of a tensor.
[`rint(...)`](../../math/rint): Returns element-wise integer closest to x.
[`round(...)`](../../math/round): Rounds the values of a tensor to the nearest integer, element-wise.
[`rsqrt(...)`](../../math/rsqrt): Computes reciprocal of square root of x element-wise.
[`scalar_mul(...)`](scalar_mul): Multiplies a scalar times a `Tensor` or `IndexedSlices` object.
[`segment_max(...)`](../../math/segment_max): Computes the maximum along segments of a tensor.
[`segment_mean(...)`](../../math/segment_mean): Computes the mean along segments of a tensor.
[`segment_min(...)`](../../math/segment_min): Computes the minimum along segments of a tensor.
[`segment_prod(...)`](../../math/segment_prod): Computes the product along segments of a tensor.
[`segment_sum(...)`](../../math/segment_sum): Computes the sum along segments of a tensor.
[`sigmoid(...)`](../../math/sigmoid): Computes sigmoid of `x` element-wise.
[`sign(...)`](../../math/sign): Returns an element-wise indication of the sign of a number.
[`sin(...)`](../../math/sin): Computes sine of x element-wise.
[`sinh(...)`](../../math/sinh): Computes hyperbolic sine of x element-wise.
[`sobol_sample(...)`](../../math/sobol_sample): Generates points from the Sobol sequence.
[`softmax(...)`](math/softmax): Computes softmax activations.
[`softplus(...)`](../../math/softplus): Computes elementwise softplus: `softplus(x) = log(exp(x) + 1)`.
[`softsign(...)`](../../nn/softsign): Computes softsign: `features / (abs(features) + 1)`.
[`sqrt(...)`](../../math/sqrt): Computes element-wise square root of the input tensor.
[`square(...)`](../../math/square): Computes square of x element-wise.
[`squared_difference(...)`](../../math/squared_difference): Returns conj(x - y)(x - y) element-wise.
[`subtract(...)`](../../math/subtract): Returns x - y element-wise.
[`tan(...)`](../../math/tan): Computes tan of x element-wise.
[`tanh(...)`](../../math/tanh): Computes hyperbolic tangent of `x` element-wise.
[`top_k(...)`](../../math/top_k): Finds values and indices of the `k` largest entries for the last dimension.
[`truediv(...)`](../../math/truediv): Divides x / y elementwise (using Python 3 division operator semantics).
[`unsorted_segment_max(...)`](../../math/unsorted_segment_max): Computes the maximum along segments of a tensor.
[`unsorted_segment_mean(...)`](../../math/unsorted_segment_mean): Computes the mean along segments of a tensor.
[`unsorted_segment_min(...)`](../../math/unsorted_segment_min): Computes the minimum along segments of a tensor.
[`unsorted_segment_prod(...)`](../../math/unsorted_segment_prod): Computes the product along segments of a tensor.
[`unsorted_segment_sqrt_n(...)`](../../math/unsorted_segment_sqrt_n): Computes the sum along segments of a tensor divided by the sqrt(N).
[`unsorted_segment_sum(...)`](../../math/unsorted_segment_sum): Computes the sum along segments of a tensor.
[`xdivy(...)`](../../math/xdivy): Returns 0 if x == 0, and x / y otherwise, elementwise.
[`xlog1py(...)`](../../math/xlog1py): Compute x \* log1p(y).
[`xlogy(...)`](../../math/xlogy): Returns 0 if x == 0, and x \* log(y) otherwise, elementwise.
[`zero_fraction(...)`](../../math/zero_fraction): Returns the fraction of zeros in `value`.
[`zeta(...)`](../../math/zeta): Compute the Hurwitz zeta function \(\zeta(x, q)\).
tensorflow tf.compat.v1.add_to_collection tf.compat.v1.add\_to\_collection
================================
Wrapper for [`Graph.add_to_collection()`](https://www.tensorflow.org/api_docs/python/tf/Graph#add_to_collection) using the default graph.
```
tf.compat.v1.add_to_collection(
name, value
)
```
See [`tf.Graph.add_to_collection`](../../graph#add_to_collection) for more details.
| Args |
| `name` | The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. |
| `value` | The value to add to the collection. |
eager compatibility
-------------------
Collections are only supported in eager when variables are created inside an EagerVariableStore (e.g. as part of a layer or template).
tensorflow tf.compat.v1.foldl tf.compat.v1.foldl
==================
foldl on the list of tensors unpacked from `elems` on dimension 0.
```
tf.compat.v1.foldl(
fn,
elems,
initializer=None,
parallel_iterations=10,
back_prop=True,
swap_memory=False,
name=None
)
```
This foldl operator repeatedly applies the callable `fn` to a sequence of elements from first to last. The elements are made of the tensors unpacked from `elems` on dimension 0. The callable fn takes two tensors as arguments. The first argument is the accumulated value computed from the preceding invocation of fn, and the second is the value at the current position of `elems`. If `initializer` is None, `elems` must contain at least one element, and its first element is used as the initializer.
Suppose that `elems` is unpacked into `values`, a list of tensors. The shape of the result tensor is fn(initializer, values[0]).shape`.
This method also allows multi-arity `elems` and output of `fn`. If `elems` is a (possibly nested) list or tuple of tensors, then each of these tensors must have a matching first (unpack) dimension. The signature of `fn` may match the structure of `elems`. That is, if `elems` is `(t1, [t2, t3, [t4, t5]])`, then an appropriate signature for `fn` is: `fn = lambda (t1, [t2, t3, [t4, t5]]):`.
| Args |
| `fn` | The callable to be performed. |
| `elems` | A tensor or (possibly nested) sequence of tensors, each of which will be unpacked along their first dimension. The nested sequence of the resulting slices will be the first argument to `fn`. |
| `initializer` | (optional) A tensor or (possibly nested) sequence of tensors, as the initial value for the accumulator. |
| `parallel_iterations` | (optional) The number of iterations allowed to run in parallel. |
| `back_prop` | (optional) True enables support for back propagation. |
| `swap_memory` | (optional) True enables GPU-CPU memory swapping. |
| `name` | (optional) Name prefix for the returned tensors. |
| Returns |
| A tensor or (possibly nested) sequence of tensors, resulting from applying `fn` consecutively to the list of tensors unpacked from `elems`, from first to last. |
| Raises |
| `TypeError` | if `fn` is not callable. |
#### Example:
```
elems = tf.constant([1, 2, 3, 4, 5, 6])
sum = foldl(lambda a, x: a + x, elems)
# sum == 21
```
tensorflow tf.compat.v1.disable_v2_behavior tf.compat.v1.disable\_v2\_behavior
==================================
Disables TensorFlow 2.x behaviors.
```
tf.compat.v1.disable_v2_behavior()
```
Migrate to TF2
--------------
Using this function indicates that your software is not compatible with eager execution and [`tf.function`](../../function) in TF2.
To migrate to TF2, rewrite your code to be compatible with eager execution. Please refer to the [migration guide](https://www.tensorflow.org/guide/migrate) for additional resource on the topic.
Description
-----------
This function can be called at the beginning of the program (before `Tensors`, `Graphs` or other structures have been created, and before devices have been initialized. It switches all global behaviors that are different between TensorFlow 1.x and 2.x to behave as intended for 1.x.
User can call this function to disable 2.x behavior during complex migrations.
tensorflow tf.compat.v1.gather_nd tf.compat.v1.gather\_nd
=======================
Gather slices from `params` into a Tensor with shape specified by `indices`.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.manip.gather_nd`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/gather_nd)
```
tf.compat.v1.gather_nd(
params, indices, name=None, batch_dims=0
)
```
`indices` is a `Tensor` of indices into `params`. The index vectors are arranged along the last axis of `indices`.
This is similar to [`tf.gather`](../../gather), in which `indices` defines slices into the first dimension of `params`. In [`tf.gather_nd`](../../gather_nd), `indices` defines slices into the first `N` dimensions of `params`, where `N = indices.shape[-1]`.
Gathering scalars
-----------------
In the simplest case the vectors in `indices` index the full rank of `params`:
```
tf.gather_nd(
indices=[[0, 0],
[1, 1]],
params = [['a', 'b'],
['c', 'd']]).numpy()
array([b'a', b'd'], dtype=object)
```
In this case the result has 1-axis fewer than `indices`, and each index vector is replaced by the scalar indexed from `params`.
In this case the shape relationship is:
```
index_depth = indices.shape[-1]
assert index_depth == params.shape.rank
result_shape = indices.shape[:-1]
```
If `indices` has a rank of `K`, it is helpful to think `indices` as a (K-1)-dimensional tensor of indices into `params`.
Gathering slices
----------------
If the index vectors do not index the full rank of `params` then each location in the result contains a slice of params. This example collects rows from a matrix:
```
tf.gather_nd(
indices = [[1],
[0]],
params = [['a', 'b', 'c'],
['d', 'e', 'f']]).numpy()
array([[b'd', b'e', b'f'],
[b'a', b'b', b'c']], dtype=object)
```
Here `indices` contains `[2]` index vectors, each with a length of `1`. The index vectors each refer to rows of the `params` matrix. Each row has a shape of `[3]` so the output shape is `[2, 3]`.
In this case, the relationship between the shapes is:
```
index_depth = indices.shape[-1]
outer_shape = indices.shape[:-1]
assert index_depth <= params.shape.rank
inner_shape = params.shape[index_depth:]
output_shape = outer_shape + inner_shape
```
It is helpful to think of the results in this case as tensors-of-tensors. The shape of the outer tensor is set by the leading dimensions of `indices`. While the shape of the inner tensors is the shape of a single slice.
Batches
-------
Additionally both `params` and `indices` can have `M` leading batch dimensions that exactly match. In this case `batch_dims` must be set to `M`.
For example, to collect one row from each of a batch of matrices you could set the leading elements of the index vectors to be their location in the batch:
```
tf.gather_nd(
indices = [[0, 1],
[1, 0],
[2, 4],
[3, 2],
[4, 1]],
params=tf.zeros([5, 7, 3])).shape.as_list()
[5, 3]
```
The `batch_dims` argument lets you omit those leading location dimensions from the index:
```
tf.gather_nd(
batch_dims=1,
indices = [[1],
[0],
[4],
[2],
[1]],
params=tf.zeros([5, 7, 3])).shape.as_list()
[5, 3]
```
This is equivalent to caling a separate `gather_nd` for each location in the batch dimensions.
```
params=tf.zeros([5, 7, 3])
indices=tf.zeros([5, 1])
batch_dims = 1
index_depth = indices.shape[-1]
batch_shape = indices.shape[:batch_dims]
assert params.shape[:batch_dims] == batch_shape
outer_shape = indices.shape[batch_dims:-1]
assert index_depth <= params.shape.rank
inner_shape = params.shape[batch_dims + index_depth:]
output_shape = batch_shape + outer_shape + inner_shape
output_shape.as_list()
[5, 3]
```
### More examples
Indexing into a 3-tensor:
```
tf.gather_nd(
indices = [[1]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[[b'a1', b'b1'],
[b'c1', b'd1']]], dtype=object)
```
```
tf.gather_nd(
indices = [[0, 1], [1, 0]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[b'c0', b'd0'],
[b'a1', b'b1']], dtype=object)
```
```
tf.gather_nd(
indices = [[0, 0, 1], [1, 0, 1]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([b'b0', b'b1'], dtype=object)
```
The examples below are for the case when only indices have leading extra dimensions. If both 'params' and 'indices' have leading batch dimensions, use the 'batch\_dims' parameter to run gather\_nd in batch mode.
Batched indexing into a matrix:
```
tf.gather_nd(
indices = [[[0, 0]], [[0, 1]]],
params = [['a', 'b'], ['c', 'd']]).numpy()
array([[b'a'],
[b'b']], dtype=object)
```
Batched slice indexing into a matrix:
```
tf.gather_nd(
indices = [[[1]], [[0]]],
params = [['a', 'b'], ['c', 'd']]).numpy()
array([[[b'c', b'd']],
[[b'a', b'b']]], dtype=object)
```
Batched indexing into a 3-tensor:
```
tf.gather_nd(
indices = [[[1]], [[0]]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[[[b'a1', b'b1'],
[b'c1', b'd1']]],
[[[b'a0', b'b0'],
[b'c0', b'd0']]]], dtype=object)
```
```
tf.gather_nd(
indices = [[[0, 1], [1, 0]], [[0, 0], [1, 1]]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[[b'c0', b'd0'],
[b'a1', b'b1']],
[[b'a0', b'b0'],
[b'c1', b'd1']]], dtype=object)
```
```
tf.gather_nd(
indices = [[[0, 0, 1], [1, 0, 1]], [[0, 1, 1], [1, 1, 0]]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[b'b0', b'b1'],
[b'd0', b'c1']], dtype=object)
```
Examples with batched 'params' and 'indices':
```
tf.gather_nd(
batch_dims = 1,
indices = [[1],
[0]],
params = [[['a0', 'b0'],
['c0', 'd0']],
[['a1', 'b1'],
['c1', 'd1']]]).numpy()
array([[b'c0', b'd0'],
[b'a1', b'b1']], dtype=object)
```
```
tf.gather_nd(
batch_dims = 1,
indices = [[[1]], [[0]]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[[b'c0', b'd0']],
[[b'a1', b'b1']]], dtype=object)
```
```
tf.gather_nd(
batch_dims = 1,
indices = [[[1, 0]], [[0, 1]]],
params = [[['a0', 'b0'], ['c0', 'd0']],
[['a1', 'b1'], ['c1', 'd1']]]).numpy()
array([[b'c0'],
[b'b1']], dtype=object)
```
See also [`tf.gather`](../../gather).
| Args |
| `params` | A `Tensor`. The tensor from which to gather values. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. Index tensor. |
| `name` | A name for the operation (optional). |
| `batch_dims` | An integer or a scalar 'Tensor'. The number of batch dimensions. |
| Returns |
| A `Tensor`. Has the same type as `params`. |
| programming_docs |
tensorflow tf.compat.v1.substr tf.compat.v1.substr
===================
Return substrings from `Tensor` of strings.
```
tf.compat.v1.substr(
input, pos, len, name=None, unit='BYTE'
)
```
For each string in the input `Tensor`, creates a substring starting at index `pos` with a total length of `len`.
If `len` defines a substring that would extend beyond the length of the input string, or if `len` is negative, then as many characters as possible are used.
A negative `pos` indicates distance within the string backwards from the end.
If `pos` specifies an index which is out of range for any of the input strings, then an `InvalidArgumentError` is thrown.
`pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on Op creation.
>
> **Note:** `Substr` supports broadcasting up to two dimensions. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
Examples
Using scalar `pos` and `len`:
```
input = [b'Hello', b'World']
position = 1
length = 3
output = [b'ell', b'orl']
```
Using `pos` and `len` with same shape as `input`:
```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen']]
position = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
length = [[2, 3, 4],
[4, 3, 2],
[5, 5, 5]]
output = [[b'en', b'eve', b'lve'],
[b'hirt', b'urt', b'te'],
[b'ixtee', b'vente', b'hteen']]
```
Broadcasting `pos` and `len` onto `input`:
```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen'],
[b'nineteen', b'twenty', b'twentyone']]
position = [1, 2, 3]
length = [1, 2, 3]
output = [[b'e', b'ev', b'lve'],
[b'h', b'ur', b'tee'],
[b'i', b've', b'hte'],
[b'i', b'en', b'nty']]
```
Broadcasting `input` onto `pos` and `len`:
```
input = b'thirteen'
position = [1, 5, 7]
length = [3, 2, 1]
output = [b'hir', b'ee', b'n']
```
| Raises |
| * `ValueError`: If the first argument cannot be converted to a Tensor of `dtype string`.
* `InvalidArgumentError`: If indices are out of range.
* `ValueError`: If `pos` and `len` are not the same shape.
|
| Args |
| `input` | A `Tensor` of type `string`. Tensor of strings |
| `pos` | A `Tensor`. Must be one of the following types: `int32`, `int64`. Scalar defining the position of first character in each substring |
| `len` | A `Tensor`. Must have the same type as `pos`. Scalar defining the number of characters to include in each substring |
| `unit` | An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to `"BYTE"`. The unit that is used to create the substring. One of: `"BYTE"` (for defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 encoded Unicode code points). The default is `"BYTE"`. Results are undefined if `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid UTF-8. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `string`. |
tensorflow tf.compat.v1.initialize_local_variables tf.compat.v1.initialize\_local\_variables
=========================================
See [`tf.compat.v1.local_variables_initializer`](local_variables_initializer). (deprecated)
```
tf.compat.v1.initialize_local_variables()
```
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.assert_scalar tf.compat.v1.assert\_scalar
===========================
Asserts that the given `tensor` is a scalar (i.e. zero-dimensional).
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_scalar`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_scalar)
```
tf.compat.v1.assert_scalar(
tensor, name=None, message=None
)
```
This function raises `ValueError` unless it can be certain that the given `tensor` is a scalar. `ValueError` is also raised if the shape of `tensor` is unknown.
| Args |
| `tensor` | A `Tensor`. |
| `name` | A name for this operation. Defaults to "assert\_scalar" |
| `message` | A string to prefix to the default message. |
| Returns |
| The input tensor (potentially converted to a `Tensor`). |
| Raises |
| `ValueError` | If the tensor is not scalar (rank 0), or if its shape is unknown. |
tensorflow Module: tf.compat.v1.linalg Module: tf.compat.v1.linalg
===========================
Operations for linear algebra.
Modules
-------
[`experimental`](linalg/experimental) module: Public API for tf.linalg.experimental namespace.
Classes
-------
[`class LinearOperator`](../../linalg/linearoperator): Base class defining a [batch of] linear operator[s].
[`class LinearOperatorAdjoint`](../../linalg/linearoperatoradjoint): `LinearOperator` representing the adjoint of another operator.
[`class LinearOperatorBlockDiag`](../../linalg/linearoperatorblockdiag): Combines one or more `LinearOperators` in to a Block Diagonal matrix.
[`class LinearOperatorBlockLowerTriangular`](../../linalg/linearoperatorblocklowertriangular): Combines `LinearOperators` into a blockwise lower-triangular matrix.
[`class LinearOperatorCirculant`](../../linalg/linearoperatorcirculant): `LinearOperator` acting like a circulant matrix.
[`class LinearOperatorCirculant2D`](../../linalg/linearoperatorcirculant2d): `LinearOperator` acting like a block circulant matrix.
[`class LinearOperatorCirculant3D`](../../linalg/linearoperatorcirculant3d): `LinearOperator` acting like a nested block circulant matrix.
[`class LinearOperatorComposition`](../../linalg/linearoperatorcomposition): Composes one or more `LinearOperators`.
[`class LinearOperatorDiag`](../../linalg/linearoperatordiag): `LinearOperator` acting like a [batch] square diagonal matrix.
[`class LinearOperatorFullMatrix`](../../linalg/linearoperatorfullmatrix): `LinearOperator` that wraps a [batch] matrix.
[`class LinearOperatorHouseholder`](../../linalg/linearoperatorhouseholder): `LinearOperator` acting like a [batch] of Householder transformations.
[`class LinearOperatorIdentity`](../../linalg/linearoperatoridentity): `LinearOperator` acting like a [batch] square identity matrix.
[`class LinearOperatorInversion`](../../linalg/linearoperatorinversion): `LinearOperator` representing the inverse of another operator.
[`class LinearOperatorKronecker`](../../linalg/linearoperatorkronecker): Kronecker product between two `LinearOperators`.
[`class LinearOperatorLowRankUpdate`](../../linalg/linearoperatorlowrankupdate): Perturb a `LinearOperator` with a rank `K` update.
[`class LinearOperatorLowerTriangular`](../../linalg/linearoperatorlowertriangular): `LinearOperator` acting like a [batch] square lower triangular matrix.
[`class LinearOperatorPermutation`](../../linalg/linearoperatorpermutation): `LinearOperator` acting like a [batch] of permutation matrices.
[`class LinearOperatorScaledIdentity`](../../linalg/linearoperatorscaledidentity): `LinearOperator` acting like a scaled [batch] identity matrix `A = c I`.
[`class LinearOperatorToeplitz`](../../linalg/linearoperatortoeplitz): `LinearOperator` acting like a [batch] of toeplitz matrices.
[`class LinearOperatorTridiag`](../../linalg/linearoperatortridiag): `LinearOperator` acting like a [batch] square tridiagonal matrix.
[`class LinearOperatorZeros`](../../linalg/linearoperatorzeros): `LinearOperator` acting like a [batch] zero matrix.
Functions
---------
[`adjoint(...)`](../../linalg/adjoint): Transposes the last two dimensions of and conjugates tensor `matrix`.
[`band_part(...)`](../../linalg/band_part): Copy a tensor setting everything outside a central band in each innermost matrix to zero.
[`cholesky(...)`](../../linalg/cholesky): Computes the Cholesky decomposition of one or more square matrices.
[`cholesky_solve(...)`](../../linalg/cholesky_solve): Solves systems of linear eqns `A X = RHS`, given Cholesky factorizations.
[`cross(...)`](../../linalg/cross): Compute the pairwise cross product.
[`det(...)`](../../linalg/det): Computes the determinant of one or more square matrices.
[`diag(...)`](../../linalg/diag): Returns a batched diagonal tensor with given batched diagonal values.
[`diag_part(...)`](../../linalg/diag_part): Returns the batched diagonal part of a batched tensor.
[`eigh(...)`](../../linalg/eigh): Computes the eigen decomposition of a batch of self-adjoint matrices.
[`eigh_tridiagonal(...)`](../../linalg/eigh_tridiagonal): Computes the eigenvalues of a Hermitian tridiagonal matrix.
[`eigvalsh(...)`](../../linalg/eigvalsh): Computes the eigenvalues of one or more self-adjoint matrices.
[`einsum(...)`](../../einsum): Tensor contraction over specified indices and outer product.
[`expm(...)`](../../linalg/expm): Computes the matrix exponential of one or more square matrices.
[`eye(...)`](../../eye): Construct an identity matrix, or a batch of matrices.
[`global_norm(...)`](../../linalg/global_norm): Computes the global norm of multiple tensors.
[`inv(...)`](../../linalg/inv): Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes).
[`l2_normalize(...)`](../../math/l2_normalize): Normalizes along dimension `axis` using an L2 norm. (deprecated arguments)
[`logdet(...)`](../../linalg/logdet): Computes log of the determinant of a hermitian positive definite matrix.
[`logm(...)`](../../linalg/logm): Computes the matrix logarithm of one or more square matrices:
[`lstsq(...)`](../../linalg/lstsq): Solves one or more linear least-squares problems.
[`lu(...)`](../../linalg/lu): Computes the LU decomposition of one or more square matrices.
[`lu_matrix_inverse(...)`](../../linalg/lu_matrix_inverse): Computes the inverse given the LU decomposition(s) of one or more matrices.
[`lu_reconstruct(...)`](../../linalg/lu_reconstruct): The reconstruct one or more matrices from their LU decomposition(s).
[`lu_solve(...)`](../../linalg/lu_solve): Solves systems of linear eqns `A X = RHS`, given LU factorizations.
[`matmul(...)`](../../linalg/matmul): Multiplies matrix `a` by matrix `b`, producing `a` \* `b`.
[`matrix_rank(...)`](../../linalg/matrix_rank): Compute the matrix rank of one or more matrices.
[`matrix_transpose(...)`](../../linalg/matrix_transpose): Transposes last two dimensions of tensor `a`.
[`matvec(...)`](../../linalg/matvec): Multiplies matrix `a` by vector `b`, producing `a` \* `b`.
[`norm(...)`](norm): Computes the norm of vectors, matrices, and tensors. (deprecated arguments)
[`normalize(...)`](../../linalg/normalize): Normalizes `tensor` along dimension `axis` using specified norm.
[`pinv(...)`](../../linalg/pinv): Compute the Moore-Penrose pseudo-inverse of one or more matrices.
[`qr(...)`](../../linalg/qr): Computes the QR decompositions of one or more matrices.
[`set_diag(...)`](../../linalg/set_diag): Returns a batched matrix tensor with new batched diagonal values.
[`slogdet(...)`](../../linalg/slogdet): Computes the sign and the log of the absolute value of the determinant of
[`solve(...)`](../../linalg/solve): Solves systems of linear equations.
[`sqrtm(...)`](../../linalg/sqrtm): Computes the matrix square root of one or more square matrices:
[`svd(...)`](../../linalg/svd): Computes the singular value decompositions of one or more matrices.
[`tensor_diag(...)`](../../linalg/tensor_diag): Returns a diagonal tensor with a given diagonal values.
[`tensor_diag_part(...)`](../../linalg/tensor_diag_part): Returns the diagonal part of the tensor.
[`tensordot(...)`](../../tensordot): Tensor contraction of a and b along specified axes and outer product.
[`trace(...)`](../../linalg/trace): Compute the trace of a tensor `x`.
[`transpose(...)`](../../linalg/matrix_transpose): Transposes last two dimensions of tensor `a`.
[`triangular_solve(...)`](../../linalg/triangular_solve): Solve systems of linear equations with upper or lower triangular matrices.
[`tridiagonal_matmul(...)`](../../linalg/tridiagonal_matmul): Multiplies tridiagonal matrix by matrix.
[`tridiagonal_solve(...)`](../../linalg/tridiagonal_solve): Solves tridiagonal systems of equations.
tensorflow tf.compat.v1.parse_example tf.compat.v1.parse\_example
===========================
Parses `Example` protos into a `dict` of tensors.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.io.parse_example`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/parse_example)
```
tf.compat.v1.parse_example(
serialized, features, name=None, example_names=None
)
```
Parses a number of serialized [`Example`](https://www.tensorflow.org/code/tensorflow/core/example/example.proto) protos given in `serialized`. We refer to `serialized` as a batch with `batch_size` many entries of individual `Example` protos.
`example_names` may contain descriptive names for the corresponding serialized protos. These may be useful for debugging purposes, but they have no effect on the output. If not `None`, `example_names` must be the same length as `serialized`.
This op parses serialized examples into a dictionary mapping keys to `Tensor` `SparseTensor`, and `RaggedTensor` objects. `features` is a dict from keys to `VarLenFeature`, `SparseFeature`, `RaggedFeature`, and `FixedLenFeature` objects. Each `VarLenFeature` and `SparseFeature` is mapped to a `SparseTensor`; each `FixedLenFeature` is mapped to a `Tensor`; and each `RaggedFeature` is mapped to a `RaggedTensor`.
Each `VarLenFeature` maps to a `SparseTensor` of the specified type representing a ragged matrix. Its indices are `[batch, index]` where `batch` identifies the example in `serialized`, and `index` is the value's index in the list of values associated with that feature and example.
Each `SparseFeature` maps to a `SparseTensor` of the specified type representing a Tensor of `dense_shape` `[batch_size] + SparseFeature.size`. Its `values` come from the feature in the examples with key `value_key`. A `values[i]` comes from a position `k` in the feature of an example at batch entry `batch`. This positional information is recorded in `indices[i]` as `[batch, index_0, index_1, ...]` where `index_j` is the `k-th` value of the feature in the example at with key [`SparseFeature.index_key[j]`](https://www.tensorflow.org/api_docs/python/tf/io/SparseFeature#index_key). In other words, we split the indices (except the first index indicating the batch entry) of a `SparseTensor` by dimension into different features of the `Example`. Due to its complexity a `VarLenFeature` should be preferred over a `SparseFeature` whenever possible.
Each `FixedLenFeature` `df` maps to a `Tensor` of the specified type (or [`tf.float32`](../../../tf#float32) if not specified) and shape `(serialized.size(),) + df.shape`.
`FixedLenFeature` entries with a `default_value` are optional. With no default value, we will fail if that `Feature` is missing from any example in `serialized`.
Each `FixedLenSequenceFeature` `df` maps to a `Tensor` of the specified type (or [`tf.float32`](../../../tf#float32) if not specified) and shape `(serialized.size(), None) + df.shape`. All examples in `serialized` will be padded with `default_value` along the second dimension.
Each `RaggedFeature` maps to a `RaggedTensor` of the specified type. It is formed by stacking the `RaggedTensor` for each example, where the `RaggedTensor` for each individual example is constructed using the tensors specified by `RaggedTensor.values_key` and [`RaggedTensor.partition`](https://www.tensorflow.org/tfx/tf_metadata/api_docs/python/tfmd/proto/schema_pb2/TensorRepresentation/RaggedTensor#partition). See the [`tf.io.RaggedFeature`](../../io/raggedfeature) documentation for details and examples.
#### Examples:
For example, if one expects a [`tf.float32`](../../../tf#float32) `VarLenFeature` `ft` and three serialized `Example`s are provided:
```
serialized = [
features
{ feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } },
features
{ feature []},
features
{ feature { key: "ft" value { float_list { value: [3.0] } } }
]
```
then the output will look like:
```
{"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]],
values=[1.0, 2.0, 3.0],
dense_shape=(3, 2)) }
```
If instead a `FixedLenSequenceFeature` with `default_value = -1.0` and `shape=[]` is used then the output will look like:
```
{"ft": [[1.0, 2.0], [3.0, -1.0]]}
```
Given two `Example` input protos in `serialized`:
```
[
features {
feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } }
feature { key: "gps" value { float_list { value: [] } } }
},
features {
feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } }
feature { key: "dank" value { int64_list { value: [ 42 ] } } }
feature { key: "gps" value { } }
}
]
```
And arguments
```
example_names: ["input0", "input1"],
features: {
"kw": VarLenFeature(tf.string),
"dank": VarLenFeature(tf.int64),
"gps": VarLenFeature(tf.float32),
}
```
Then the output is a dictionary:
```
{
"kw": SparseTensor(
indices=[[0, 0], [0, 1], [1, 0]],
values=["knit", "big", "emmy"]
dense_shape=[2, 2]),
"dank": SparseTensor(
indices=[[1, 0]],
values=[42],
dense_shape=[2, 1]),
"gps": SparseTensor(
indices=[],
values=[],
dense_shape=[2, 0]),
}
```
For dense results in two serialized `Example`s:
```
[
features {
feature { key: "age" value { int64_list { value: [ 0 ] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
},
features {
feature { key: "age" value { int64_list { value: [] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
}
]
```
#### We can use arguments:
```
example_names: ["input0", "input1"],
features: {
"age": FixedLenFeature([], dtype=tf.int64, default_value=-1),
"gender": FixedLenFeature([], dtype=tf.string),
}
```
And the expected output is:
```
{
"age": [[0], [-1]],
"gender": [["f"], ["f"]],
}
```
An alternative to `VarLenFeature` to obtain a `SparseTensor` is `SparseFeature`. For example, given two `Example` input protos in `serialized`:
```
[
features {
feature { key: "val" value { float_list { value: [ 0.5, -1.0 ] } } }
feature { key: "ix" value { int64_list { value: [ 3, 20 ] } } }
},
features {
feature { key: "val" value { float_list { value: [ 0.0 ] } } }
feature { key: "ix" value { int64_list { value: [ 42 ] } } }
}
]
```
And arguments
```
example_names: ["input0", "input1"],
features: {
"sparse": SparseFeature(
index_key="ix", value_key="val", dtype=tf.float32, size=100),
}
```
Then the output is a dictionary:
```
{
"sparse": SparseTensor(
indices=[[0, 3], [0, 20], [1, 42]],
values=[0.5, -1.0, 0.0]
dense_shape=[2, 100]),
}
```
See the [`tf.io.RaggedFeature`](../../io/raggedfeature) documentation for examples showing how `RaggedFeature` can be used to obtain `RaggedTensor`s.
| Args |
| `serialized` | A vector (1-D Tensor) of strings, a batch of binary serialized `Example` protos. |
| `features` | A `dict` mapping feature keys to `FixedLenFeature`, `VarLenFeature`, `SparseFeature`, and `RaggedFeature` values. |
| `example_names` | A vector (1-D Tensor) of strings (optional), the names of the serialized protos in the batch. |
| `name` | A name for this operation (optional). |
| Returns |
| A `dict` mapping feature keys to `Tensor`, `SparseTensor`, and `RaggedTensor` values. |
| Raises |
| `ValueError` | if any feature is invalid. |
| programming_docs |
tensorflow tf.compat.v1.to_int32 tf.compat.v1.to\_int32
======================
Casts a tensor to type `int32`. (deprecated)
```
tf.compat.v1.to_int32(
x, name='ToInt32'
)
```
Migrate to TF2
--------------
This name was deprecated and removed in TF2, but has an exact replacement [`tf.cast(..., tf.int32)`](../../cast). There are no further issues with eager execution or tf.function.
Before:
```
tf.compat.v1.to_int32(tf.constant(1, dtype=tf.int64))
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
After:
```
tf.cast(tf.constant(1, dtype=tf.int64), tf.int32)
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
Description
-----------
| Args |
| `x` | A `Tensor` or `SparseTensor` or `IndexedSlices`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` or `SparseTensor` or `IndexedSlices` with same shape as `x` with type `int32`. |
| Raises |
| `TypeError` | If `x` cannot be cast to the `int32`. |
tensorflow tf.compat.v1.disable_eager_execution tf.compat.v1.disable\_eager\_execution
======================================
Disables eager execution.
```
tf.compat.v1.disable_eager_execution()
```
Migrate to TF2
--------------
This function is not necessary if you are using TF2. Eager execution is enabled by default. If you want to use Graph mode please consider [tf.function](https://www.tensorflow.org/api_docs/python/tf/function).
Description
-----------
This function can only be called before any Graphs, Ops, or Tensors have been created.
tensorflow tf.compat.v1.enable_v2_behavior tf.compat.v1.enable\_v2\_behavior
=================================
Enables TensorFlow 2.x behaviors.
```
tf.compat.v1.enable_v2_behavior()
```
Migrate to TF2
--------------
This function is not necessary if you are using TF2. V2 behavior is enabled by default.
Description
-----------
This function can be called at the beginning of the program (before `Tensors`, `Graphs` or other structures have been created, and before devices have been initialized. It switches all global behaviors that are different between TensorFlow 1.x and 2.x to behave as intended for 2.x.
This function is called in the main TensorFlow `__init__.py` file, user should not need to call it, except during complex migrations.
tensorflow Module: tf.compat.v1.graph_util Module: tf.compat.v1.graph\_util
================================
Helpers to manipulate a tensor graph in python.
Functions
---------
[`convert_variables_to_constants(...)`](graph_util/convert_variables_to_constants): Replaces all the variables in a graph with constants of the same values. (deprecated)
[`extract_sub_graph(...)`](graph_util/extract_sub_graph): Extract the subgraph that can reach any of the nodes in 'dest\_nodes'. (deprecated)
[`import_graph_def(...)`](../../graph_util/import_graph_def): Imports the graph from `graph_def` into the current default `Graph`. (deprecated arguments)
[`must_run_on_cpu(...)`](graph_util/must_run_on_cpu): Returns True if the given node\_def must run on CPU, otherwise False. (deprecated)
[`remove_training_nodes(...)`](graph_util/remove_training_nodes): Prunes out nodes that aren't needed for inference. (deprecated)
[`tensor_shape_from_node_def_name(...)`](graph_util/tensor_shape_from_node_def_name): Convenience function to get a shape from a NodeDef's input string. (deprecated)
tensorflow Module: tf.compat.v1.version Module: tf.compat.v1.version
============================
Public API for tf.version namespace.
| Other Members |
| COMPILER\_VERSION | `'9.3.1 20200408'` |
| GIT\_VERSION | `'v2.9.0-rc2-42-g8a20d54a3c1'` |
| GRAPH\_DEF\_VERSION | `1087` |
| GRAPH\_DEF\_VERSION\_MIN\_CONSUMER | `0` |
| GRAPH\_DEF\_VERSION\_MIN\_PRODUCER | `0` |
| VERSION | `'2.9.0'` |
tensorflow Module: tf.compat.v1.resource_loader Module: tf.compat.v1.resource\_loader
=====================================
Resource management library.
Functions
---------
[`get_data_files_path(...)`](resource_loader/get_data_files_path): Get a direct path to the data files colocated with the script.
[`get_path_to_datafile(...)`](resource_loader/get_path_to_datafile): Get the path to the specified file in the data dependencies.
[`get_root_dir_with_all_resources(...)`](resource_loader/get_root_dir_with_all_resources): Get a root directory containing all the data attributes in the build rule.
[`load_resource(...)`](resource_loader/load_resource): Load the resource at given path, where path is relative to tensorflow/.
[`readahead_file_path(...)`](resource_loader/readahead_file_path): Readahead files not implemented; simply returns given path.
tensorflow tf.compat.v1.RunMetadata tf.compat.v1.RunMetadata
========================
A ProtocolMessage
| Attributes |
| `cost_graph` | `CostGraphDef cost_graph` |
| `function_graphs` | `repeated FunctionGraphs function_graphs` |
| `partition_graphs` | `repeated GraphDef partition_graphs` |
| `step_stats` | `StepStats step_stats` |
Child Classes
-------------
[`class FunctionGraphs`](runmetadata/functiongraphs)
tensorflow tf.compat.v1.argmax tf.compat.v1.argmax
===================
Returns the index with the largest value across axes of a tensor. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.argmax`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/argmax)
```
tf.compat.v1.argmax(
input,
axis=None,
name=None,
dimension=None,
output_type=tf.dtypes.int64
)
```
Note that in case of ties the identity of the return value is not guaranteed.
#### Usage:
```
import tensorflow as tf
a = [1, 10, 26.9, 2.8, 166.32, 62.3]
b = tf.math.argmax(input = a)
c = tf.keras.backend.eval(b)
# c = 4
# here a[4] = 166.32 which is the largest element of a across axis 0
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`, `bool`. |
| `axis` | A `Tensor`. Must be one of the following types: `int16`, `int32`, `int64`. int16, int32 or int64, must be in the range `[-rank(input), rank(input))`. Describes which axis of the input Tensor to reduce across. For vectors, use axis = 0. |
| `output_type` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.int16, tf.uint16, tf.int32, tf.int64`. Defaults to [`tf.int64`](../../../tf#int64). |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `output_type`. |
tensorflow tf.compat.v1.set_random_seed tf.compat.v1.set\_random\_seed
==============================
Sets the graph-level random seed for the default graph.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.random.set_random_seed`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/set_random_seed)
```
tf.compat.v1.set_random_seed(
seed
)
```
Migrate to TF2
--------------
'tf.compat.v1.set\_random\_seed' is compatible with eager mode. However, in eager mode this API will set the global seed instead of the graph-level seed of the default graph. In TF2 this API is changed to [tf.random.set\_seed](https://www.tensorflow.org/api_docs/python/tf/random/set_seed).
Description
-----------
Operations that rely on a random seed actually derive it from two seeds: the graph-level and operation-level seeds. This sets the graph-level seed.
Its interactions with operation-level seeds is as follows:
1. If neither the graph-level nor the operation seed is set: A random seed is used for this op.
2. If the graph-level seed is set, but the operation seed is not: The system deterministically picks an operation seed in conjunction with the graph-level seed so that it gets a unique random sequence. Within the same version of tensorflow and user code, this sequence is deterministic. However across different versions, this sequence might change. If the code depends on particular seeds to work, specify both graph-level and operation-level seeds explicitly.
3. If the graph-level seed is not set, but the operation seed is set: A default graph-level seed and the specified operation seed are used to determine the random sequence.
4. If both the graph-level and the operation seed are set: Both seeds are used in conjunction to determine the random sequence.
To illustrate the user-visible effects, consider these examples:
To generate different sequences across sessions, set neither graph-level nor op-level seeds:
```
a = tf.random.uniform([1])
b = tf.random.normal([1])
print("Session 1")
with tf.compat.v1.Session() as sess1:
print(sess1.run(a)) # generates 'A1'
print(sess1.run(a)) # generates 'A2'
print(sess1.run(b)) # generates 'B1'
print(sess1.run(b)) # generates 'B2'
print("Session 2")
with tf.compat.v1.Session() as sess2:
print(sess2.run(a)) # generates 'A3'
print(sess2.run(a)) # generates 'A4'
print(sess2.run(b)) # generates 'B3'
print(sess2.run(b)) # generates 'B4'
```
To generate the same repeatable sequence for an op across sessions, set the seed for the op:
```
a = tf.random.uniform([1], seed=1)
b = tf.random.normal([1])
# Repeatedly running this block with the same graph will generate the same
# sequence of values for 'a', but different sequences of values for 'b'.
print("Session 1")
with tf.compat.v1.Session() as sess1:
print(sess1.run(a)) # generates 'A1'
print(sess1.run(a)) # generates 'A2'
print(sess1.run(b)) # generates 'B1'
print(sess1.run(b)) # generates 'B2'
print("Session 2")
with tf.compat.v1.Session() as sess2:
print(sess2.run(a)) # generates 'A1'
print(sess2.run(a)) # generates 'A2'
print(sess2.run(b)) # generates 'B3'
print(sess2.run(b)) # generates 'B4'
```
To make the random sequences generated by all ops be repeatable across sessions, set a graph-level seed:
```
tf.compat.v1.random.set_random_seed(1234)
a = tf.random.uniform([1])
b = tf.random.normal([1])
# Repeatedly running this block with the same graph will generate the same
# sequences of 'a' and 'b'.
print("Session 1")
with tf.compat.v1.Session() as sess1:
print(sess1.run(a)) # generates 'A1'
print(sess1.run(a)) # generates 'A2'
print(sess1.run(b)) # generates 'B1'
print(sess1.run(b)) # generates 'B2'
print("Session 2")
with tf.compat.v1.Session() as sess2:
print(sess2.run(a)) # generates 'A1'
print(sess2.run(a)) # generates 'A2'
print(sess2.run(b)) # generates 'B1'
print(sess2.run(b)) # generates 'B2'
```
| Args |
| `seed` | integer. |
tensorflow tf.compat.v1.reduce_join tf.compat.v1.reduce\_join
=========================
Joins all strings into a single string, or joins along an axis.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.strings.reduce_join`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_join)
```
tf.compat.v1.reduce_join(
inputs,
axis=None,
keep_dims=None,
separator='',
name=None,
reduction_indices=None,
keepdims=None
)
```
This is the reduction operation for the elementwise [`tf.strings.join`](../../strings/join) op.
```
tf.strings.reduce_join([['abc','123'],
['def','456']]).numpy()
b'abc123def456'
tf.strings.reduce_join([['abc','123'],
['def','456']], axis=-1).numpy()
array([b'abc123', b'def456'], dtype=object)
tf.strings.reduce_join([['abc','123'],
['def','456']],
axis=-1,
separator=" ").numpy()
array([b'abc 123', b'def 456'], dtype=object)
```
| Args |
| `inputs` | A [`tf.string`](../../../tf#string) tensor. |
| `axis` | Which axis to join along. The default behavior is to join all elements, producing a scalar. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `separator` | a string added between each string being joined. |
| `name` | A name for the operation (optional). |
| Returns |
| A [`tf.string`](../../../tf#string) tensor. |
tensorflow tf.compat.v1.assert_variables_initialized tf.compat.v1.assert\_variables\_initialized
===========================================
Returns an Op to check if variables are initialized.
```
tf.compat.v1.assert_variables_initialized(
var_list=None
)
```
>
> **Note:** This function is obsolete and will be removed in 6 months. Please change your implementation to use `report_uninitialized_variables()`.
>
When run, the returned Op will raise the exception `FailedPreconditionError` if any of the variables has not yet been initialized.
>
> **Note:** This function is implemented by trying to fetch the values of the variables. If one of the variables is not initialized a message may be logged by the C++ runtime. This is expected.
>
| Args |
| `var_list` | List of `Variable` objects to check. Defaults to the value of `global_variables().` |
| Returns |
| An Op, or None if there are no variables. |
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.add_to_collections tf.compat.v1.add\_to\_collections
=================================
Wrapper for [`Graph.add_to_collections()`](https://www.tensorflow.org/api_docs/python/tf/Graph#add_to_collections) using the default graph.
```
tf.compat.v1.add_to_collections(
names, value
)
```
See [`tf.Graph.add_to_collections`](../../graph#add_to_collections) for more details.
| Args |
| `names` | The key for the collections. The `GraphKeys` class contains many standard names for collections. |
| `value` | The value to add to the collections. |
eager compatibility
-------------------
Collections are only supported in eager when variables are created inside an EagerVariableStore (e.g. as part of a layer or template).
tensorflow tf.compat.v1.reduce_mean tf.compat.v1.reduce\_mean
=========================
Computes the mean of elements across dimensions of a tensor.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.math.reduce_mean`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/reduce_mean)
```
tf.compat.v1.reduce_mean(
input_tensor,
axis=None,
keepdims=None,
name=None,
reduction_indices=None,
keep_dims=None
)
```
Reduces `input_tensor` along the dimensions given in `axis` by computing the mean of elements across the dimensions in `axis`. Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each the entries in `axis`, which must be unique. If `keepdims` is true, the reduced dimensions are retained with length 1.
If `axis` is None, all dimensions are reduced, and a tensor with a single element is returned.
#### For example:
```
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x)
<tf.Tensor: shape=(), dtype=float32, numpy=1.5>
tf.reduce_mean(x, 0)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1.5, 1.5], dtype=float32)>
tf.reduce_mean(x, 1)
<tf.Tensor: shape=(2,), dtype=float32, numpy=array([1., 2.], dtype=float32)>
```
| Args |
| `input_tensor` | The tensor to reduce. Should have numeric type. |
| `axis` | The dimensions to reduce. If `None` (the default), reduces all dimensions. Must be in the range `[-rank(input_tensor), rank(input_tensor))`. |
| `keepdims` | If true, retains reduced dimensions with length 1. |
| `name` | A name for the operation (optional). |
| `reduction_indices` | The old (deprecated) name for axis. |
| `keep_dims` | Deprecated alias for `keepdims`. |
| Returns |
| The reduced tensor. |
numpy compatibility
-------------------
Equivalent to np.mean
Please note that `np.mean` has a `dtype` parameter that could be used to specify the output type. By default this is `dtype=float64`. On the other hand, [`tf.reduce_mean`](../../math/reduce_mean) has an aggressive type inference from `input_tensor`, for example:
```
x = tf.constant([1, 0, 1, 0])
tf.reduce_mean(x)
<tf.Tensor: shape=(), dtype=int32, numpy=0>
y = tf.constant([1., 0., 1., 0.])
tf.reduce_mean(y)
<tf.Tensor: shape=(), dtype=float32, numpy=0.5>
```
tensorflow tf.compat.v1.sparse_concat tf.compat.v1.sparse\_concat
===========================
Concatenates a list of `SparseTensor` along the specified dimension. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.sparse.concat`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/sparse_concat)
```
tf.compat.v1.sparse_concat(
axis,
sp_inputs,
name=None,
expand_nonconcat_dim=False,
concat_dim=None,
expand_nonconcat_dims=None
)
```
Concatenation is with respect to the dense versions of each sparse input. It is assumed that each inputs is a `SparseTensor` whose elements are ordered along increasing dimension number.
If expand\_nonconcat\_dim is False, all inputs' shapes must match, except for the concat dimension. If expand\_nonconcat\_dim is True, then inputs' shapes are allowed to vary among all inputs.
The `indices`, `values`, and `shapes` lists must have the same length.
If expand\_nonconcat\_dim is False, then the output shape is identical to the inputs', except along the concat dimension, where it is the sum of the inputs' sizes along that dimension.
If expand\_nonconcat\_dim is True, then the output shape along the non-concat dimensions will be expand to be the largest among all inputs, and it is the sum of the inputs sizes along the concat dimension.
The output elements will be resorted to preserve the sort order along increasing dimension number.
This op runs in `O(M log M)` time, where `M` is the total number of non-empty values across all inputs. This is due to the need for an internal sort in order to concatenate efficiently across an arbitrary dimension.
For example, if `axis = 1` and the inputs are
```
sp_inputs[0]: shape = [2, 3]
[0, 2]: "a"
[1, 0]: "b"
[1, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
```
then the output will be
```
shape = [2, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[1, 1]: "c"
```
Graphically this is equivalent to doing
```
[ a] concat [ d e ] = [ a d e ]
[b c ] [ ] [b c ]
```
Another example, if 'axis = 1' and the inputs are
```
sp_inputs[0]: shape = [3, 3]
[0, 2]: "a"
[1, 0]: "b"
[2, 1]: "c"
sp_inputs[1]: shape = [2, 4]
[0, 1]: "d"
[0, 2]: "e"
```
if expand\_nonconcat\_dim = False, this will result in an error. But if expand\_nonconcat\_dim = True, this will result in:
```
shape = [3, 7]
[0, 2]: "a"
[0, 4]: "d"
[0, 5]: "e"
[1, 0]: "b"
[2, 1]: "c"
```
Graphically this is equivalent to doing
```
[ a] concat [ d e ] = [ a d e ]
[b ] [ ] [b ]
[ c ] [ c ]
```
| Args |
| `axis` | Dimension to concatenate along. Must be in range [-rank, rank), where rank is the number of dimensions in each input `SparseTensor`. |
| `sp_inputs` | List of `SparseTensor` to concatenate. |
| `name` | A name prefix for the returned tensors (optional). |
| `expand_nonconcat_dim` | Whether to allow the expansion in the non-concat dimensions. Defaulted to False. |
| `concat_dim` | The old (deprecated) name for axis. |
| `expand_nonconcat_dims` | alias for expand\_nonconcat\_dim |
| Returns |
| A `SparseTensor` with the concatenated output. |
| Raises |
| `TypeError` | If `sp_inputs` is not a list of `SparseTensor`. |
| programming_docs |
tensorflow tf.compat.v1.setdiff1d tf.compat.v1.setdiff1d
======================
Computes the difference between two lists of numbers or strings.
```
tf.compat.v1.setdiff1d(
x,
y,
index_dtype=tf.dtypes.int32,
name=None
)
```
Given a list `x` and a list `y`, this operation returns a list `out` that represents all values that are in `x` but not in `y`. The returned list `out` is sorted in the same order that the numbers appear in `x` (duplicates are preserved). This operation also returns a list `idx` that represents the position of each `out` element in `x`. In other words:
`out[i] = x[idx[i]] for i in [0, 1, ..., len(out) - 1]`
For example, given this input:
```
x = [1, 2, 3, 4, 5, 6]
y = [1, 3, 5]
```
This operation would return:
```
out ==> [2, 4, 6]
idx ==> [1, 3, 5]
```
| Args |
| `x` | A `Tensor`. 1-D. Values to keep. |
| `y` | A `Tensor`. Must have the same type as `x`. 1-D. Values to remove. |
| `out_idx` | An optional [`tf.DType`](../../dtypes/dtype) from: `tf.int32, tf.int64`. Defaults to [`tf.int32`](../../../tf#int32). |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (out, idx). |
| `out` | A `Tensor`. Has the same type as `x`. |
| `idx` | A `Tensor` of type `out_idx`. |
tensorflow tf.compat.v1.assert_near tf.compat.v1.assert\_near
=========================
Assert the condition `x` and `y` are close element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_near`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_near)
```
tf.compat.v1.assert_near(
x,
y,
rtol=None,
atol=None,
data=None,
summarize=None,
message=None,
name=None
)
```
Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_near(x, y)]):
output = tf.reduce_sum(x)
```
This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have
`tf.abs(x[i] - y[i]) <= atol + rtol * tf.abs(y[i])`.
If both `x` and `y` are empty, this is trivially satisfied.
The default `atol` and `rtol` is `10 * eps`, where `eps` is the smallest representable positive number such that `1 + eps != 1`. This is about `1.2e-6` in `32bit`, `2.22e-15` in `64bit`, and `0.00977` in `16bit`. See `numpy.finfo`.
| Args |
| `x` | Float or complex `Tensor`. |
| `y` | Float or complex `Tensor`, same `dtype` as, and broadcastable to, `x`. |
| `rtol` | `Tensor`. Same `dtype` as, and broadcastable to, `x`. The relative tolerance. Default is `10 * eps`. |
| `atol` | `Tensor`. Same `dtype` as, and broadcastable to, `x`. The absolute tolerance. Default is `10 * eps`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_near". |
| Returns |
| Op that raises `InvalidArgumentError` if `x` and `y` are not close enough. |
numpy compatibility
-------------------
Similar to `numpy.testing.assert_allclose`, except tolerance depends on data type. This is due to the fact that `TensorFlow` is often used with `32bit`, `64bit`, and even `16bit` data.
tensorflow tf.compat.v1.parse_single_example tf.compat.v1.parse\_single\_example
===================================
Parses a single `Example` proto.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.io.parse_single_example`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/parse_single_example)
```
tf.compat.v1.parse_single_example(
serialized, features, name=None, example_names=None
)
```
Similar to `parse_example`, except:
For dense tensors, the returned `Tensor` is identical to the output of `parse_example`, except there is no batch dimension, the output shape is the same as the shape given in `dense_shape`.
For `SparseTensor`s, the first (batch) column of the indices matrix is removed (the indices matrix is a column vector), the values vector is unchanged, and the first (`batch_size`) entry of the shape vector is removed (it is now a single element vector).
One might see performance advantages by batching `Example` protos with `parse_example` instead of using this function directly.
| Args |
| `serialized` | A scalar string Tensor, a single serialized Example. |
| `features` | A `dict` mapping feature keys to `FixedLenFeature` or `VarLenFeature` values. |
| `name` | A name for this operation (optional). |
| `example_names` | (Optional) A scalar string Tensor, the associated name. |
| Returns |
| A `dict` mapping feature keys to `Tensor` and `SparseTensor` values. |
| Raises |
| `ValueError` | if any feature is invalid. |
tensorflow tf.compat.v1.sparse_matmul tf.compat.v1.sparse\_matmul
===========================
Multiply matrix "a" by matrix "b".
```
tf.compat.v1.sparse_matmul(
a,
b,
transpose_a=False,
transpose_b=False,
a_is_sparse=False,
b_is_sparse=False,
name=None
)
```
The inputs must be two-dimensional matrices and the inner dimension of "a" must match the outer dimension of "b". Both "a" and "b" must be `Tensor`s not `SparseTensor`s. This op is optimized for the case where at least one of "a" or "b" is sparse, in the sense that they have a large proportion of zero values. The breakeven for using this versus a dense matrix multiply on one platform was 30% zero values in the sparse matrix.
The gradient computation of this operation will only take advantage of sparsity in the input gradient when that gradient comes from a Relu.
| Args |
| `a` | A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. |
| `b` | A `Tensor`. Must be one of the following types: `float32`, `bfloat16`. |
| `transpose_a` | An optional `bool`. Defaults to `False`. |
| `transpose_b` | An optional `bool`. Defaults to `False`. |
| `a_is_sparse` | An optional `bool`. Defaults to `False`. |
| `b_is_sparse` | An optional `bool`. Defaults to `False`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.random_poisson tf.compat.v1.random\_poisson
============================
Draws `shape` samples from each of the given Poisson distribution(s).
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.random.poisson`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/random_poisson)
```
tf.compat.v1.random_poisson(
lam,
shape,
dtype=tf.dtypes.float32,
seed=None,
name=None
)
```
`lam` is the rate parameter describing the distribution(s).
#### Example:
```
samples = tf.random.poisson([0.5, 1.5], [10])
# samples has shape [10, 2], where each slice [:, 0] and [:, 1] represents
# the samples drawn from each distribution
samples = tf.random.poisson([12.2, 3.3], [7, 5])
# samples has shape [7, 5, 2], where each slice [:, :, 0] and [:, :, 1]
# represents the 7x5 samples drawn from each of the two distributions
```
| Args |
| `lam` | A Tensor or Python value or N-D array of type `dtype`. `lam` provides the rate parameter(s) describing the poisson distribution(s) to sample. |
| `shape` | A 1-D integer Tensor or Python array. The shape of the output samples to be drawn per "rate"-parameterized distribution. |
| `dtype` | The type of the output: `float16`, `float32`, `float64`, `int32` or `int64`. |
| `seed` | A Python integer. Used to create a random seed for the distributions. See [`tf.random.set_seed`](../../random/set_seed) for behavior. |
| `name` | Optional name for the operation. |
| Returns |
| `samples` | a `Tensor` of shape `tf.concat([shape, tf.shape(lam)], axis=0)` with values of type `dtype`. |
tensorflow tf.compat.v1.IdentityReader tf.compat.v1.IdentityReader
===========================
A Reader that outputs the queued work as both the key and value.
Inherits From: [`ReaderBase`](readerbase)
```
tf.compat.v1.IdentityReader(
name=None
)
```
To use, enqueue strings in a Queue. Read will take the front work string and output (work, work).
See ReaderBase for supported methods.
| Args |
| `name` | A name for the operation (optional). |
| Attributes |
| `reader_ref` | Op that implements the reader. |
| `supports_serialize` | Whether the Reader implementation can serialize its state. |
Methods
-------
### `num_records_produced`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L328-L346)
```
num_records_produced(
name=None
)
```
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `num_work_units_completed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L348-L362)
```
num_work_units_completed(
name=None
)
```
Returns the number of work units this reader has finished processing.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L261-L288)
```
read(
queue, name=None
)
```
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (key, value). |
| `key` | A string scalar Tensor. |
| `value` | A string scalar Tensor. |
### `read_up_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L290-L326)
```
read_up_to(
queue, num_records, name=None
)
```
Returns up to num\_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num\_records even before the last batch.
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `num_records` | Number of records to read. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (keys, values). |
| `keys` | A 1-D string Tensor. |
| `values` | A 1-D string Tensor. |
### `reset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L406-L418)
```
reset(
name=None
)
```
Restore a reader to its initial clean state.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `restore_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L381-L399)
```
restore_state(
state, name=None
)
```
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
| Args |
| `state` | A string Tensor. Result of a SerializeState of a Reader with matching type. |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `serialize_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L364-L379)
```
serialize_state(
name=None
)
```
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A string Tensor. |
eager compatibility
-------------------
Readers are not compatible with eager execution. Instead, please use [`tf.data`](../../data) to get data into your model.
tensorflow Module: tf.compat.v1.summary Module: tf.compat.v1.summary
============================
Operations for writing summary data, for use in analysis and visualization.
See the [Summaries and TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard) guide.
Classes
-------
[`class Event`](event): A ProtocolMessage
[`class FileWriter`](summary/filewriter): Writes `Summary` protocol buffers to event files.
[`class FileWriterCache`](summary/filewritercache): Cache for file writers.
[`class SessionLog`](sessionlog): A ProtocolMessage
[`class Summary`](summary): A ProtocolMessage
[`class SummaryDescription`](summary/summarydescription): A ProtocolMessage
[`class TaggedRunMetadata`](summary/taggedrunmetadata): A ProtocolMessage
Functions
---------
[`all_v2_summary_ops(...)`](summary/all_v2_summary_ops): Returns all V2-style summary ops defined in the current default graph.
[`audio(...)`](summary/audio): Outputs a `Summary` protocol buffer with audio.
[`get_summary_description(...)`](summary/get_summary_description): Given a TensorSummary node\_def, retrieve its SummaryDescription.
[`histogram(...)`](summary/histogram): Outputs a `Summary` protocol buffer with a histogram.
[`image(...)`](summary/image): Outputs a `Summary` protocol buffer with images.
[`initialize(...)`](summary/initialize): Initializes summary writing for graph execution mode.
[`merge(...)`](summary/merge): Merges summaries.
[`merge_all(...)`](summary/merge_all): Merges all summaries collected in the default graph.
[`scalar(...)`](summary/scalar): Outputs a `Summary` protocol buffer containing a single scalar value.
[`tensor_summary(...)`](summary/tensor_summary): Outputs a `Summary` protocol buffer with a serialized tensor.proto.
[`text(...)`](summary/text): Summarizes textual data.
tensorflow tf.compat.v1.get_seed tf.compat.v1.get\_seed
======================
Returns the local seeds an operation should use given an op-specific seed.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.random.get_seed`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/get_seed)
```
tf.compat.v1.get_seed(
op_seed
)
```
Given operation-specific seed, `op_seed`, this helper function returns two seeds derived from graph-level and op-level seeds. Many random operations internally use the two seeds to allow user to change the seed globally for a graph, or for only specific operations.
For details on how the graph-level seed interacts with op seeds, see [`tf.compat.v1.random.set_random_seed`](set_random_seed).
| Args |
| `op_seed` | integer. |
| Returns |
| A tuple of two integers that should be used for the local seed of this operation. |
tensorflow tf.compat.v1.wrap_function tf.compat.v1.wrap\_function
===========================
Wraps the TF 1.x function fn into a graph function.
```
tf.compat.v1.wrap_function(
fn, signature, name=None
)
```
The python function `fn` will be called once with symbolic arguments specified in the `signature`, traced, and turned into a graph function. Any variables created by `fn` will be owned by the object returned by `wrap_function`. The resulting graph function can be called with tensors which match the signature.
```
def f(x, do_add):
v = tf.Variable(5.0)
if do_add:
op = v.assign_add(x)
else:
op = v.assign_sub(x)
with tf.control_dependencies([op]):
return v.read_value()
f_add = tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), True])
assert float(f_add(1.0)) == 6.0
assert float(f_add(1.0)) == 7.0
# Can call tf.compat.v1.wrap_function again to get a new trace, a new set
# of variables, and possibly different non-template arguments.
f_sub= tf.compat.v1.wrap_function(f, [tf.TensorSpec((), tf.float32), False])
assert float(f_sub(1.0)) == 4.0
assert float(f_sub(1.0)) == 3.0
```
Both [`tf.compat.v1.wrap_function`](wrap_function) and [`tf.function`](../../function) create a callable TensorFlow graph. But while [`tf.function`](../../function) runs all stateful operations (e.g. [`tf.print`](../../print)) and sequences operations to provide the same semantics as eager execution, `wrap_function` is closer to the behavior of `session.run` in TensorFlow 1.x. It will not run any operations unless they are required to compute the function's outputs, either through a data dependency or a control dependency. Nor will it sequence operations.
Unlike [`tf.function`](../../function), `wrap_function` will only trace the Python function once. As with placeholders in TF 1.x, shapes and dtypes must be provided to `wrap_function`'s `signature` argument.
Since it is only traced once, variables and state may be created inside the function and owned by the function wrapper object.
| Args |
| `fn` | python function to be wrapped |
| `signature` | the placeholder and python arguments to be passed to the wrapped function |
| `name` | Optional. The name of the function. |
| Returns |
| the wrapped graph function. |
tensorflow tf.compat.v1.initialize_variables tf.compat.v1.initialize\_variables
==================================
See [`tf.compat.v1.variables_initializer`](variables_initializer). (deprecated)
```
tf.compat.v1.initialize_variables(
var_list, name='init'
)
```
>
> **Note:** The output of this function should be used. If it is not, a warning will be logged or an error may be raised. To mark the output as used, call its .mark\_used() method.
>
tensorflow tf.compat.v1.global_variables_initializer tf.compat.v1.global\_variables\_initializer
===========================================
Returns an Op that initializes global variables.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.global_variables`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/global_variables_initializer)
```
tf.compat.v1.global_variables_initializer()
```
Migrate to TF2
--------------
In TF2, variables are initialized immediately when they are created. There is no longer a need to run variable initializers before using them.
Description
-----------
This is just a shortcut for `variables_initializer(global_variables())`
| Returns |
| An Op that initializes global variables in the graph. |
tensorflow tf.compat.v1.scatter_div tf.compat.v1.scatter\_div
=========================
Divides a variable reference by sparse updates.
```
tf.compat.v1.scatter_div(
ref, indices, updates, use_locking=False, name=None
)
```
This operation computes
```
# Scalar indices
ref[indices, ...] /= updates[...]
# Vector indices (for each i)
ref[indices[i], ...] /= updates[i, ...]
# High rank indices (for each i, ..., j)
ref[indices[i, ..., j], ...] /= updates[i, ..., j, ...]
```
This operation outputs `ref` after the update is done. This makes it easier to chain operations that need to use the reset value.
Duplicate entries are handled correctly: if multiple `indices` reference the same location, their contributions divide.
Requires `updates.shape = indices.shape + ref.shape[1:]` or `updates.shape = []`.
| Args |
| `ref` | A mutable `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, `int64`, `qint8`, `quint8`, `qint32`, `bfloat16`, `uint16`, `complex128`, `half`, `uint32`, `uint64`. Should be from a `Variable` node. |
| `indices` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A tensor of indices into the first dimension of `ref`. |
| `updates` | A `Tensor`. Must have the same type as `ref`. A tensor of values that `ref` is divided by. |
| `use_locking` | An optional `bool`. Defaults to `False`. If True, the operation will be protected by a lock; otherwise the behavior is undefined, but may exhibit less contention. |
| `name` | A name for the operation (optional). |
| Returns |
| A mutable `Tensor`. Has the same type as `ref`. |
| programming_docs |
tensorflow Module: tf.compat.v1.logging Module: tf.compat.v1.logging
============================
Logging and Summary Operations.
Functions
---------
[`TaskLevelStatusMessage(...)`](logging/tasklevelstatusmessage)
[`debug(...)`](logging/debug)
[`error(...)`](logging/error)
[`fatal(...)`](logging/fatal)
[`flush(...)`](logging/flush)
[`get_verbosity(...)`](logging/get_verbosity): Return how much logging output will be produced.
[`info(...)`](logging/info)
[`log(...)`](logging/log)
[`log_every_n(...)`](logging/log_every_n): Log 'msg % args' at level 'level' once per 'n' times.
[`log_first_n(...)`](logging/log_first_n): Log 'msg % args' at level 'level' only first 'n' times.
[`log_if(...)`](logging/log_if): Log 'msg % args' at level 'level' only if condition is fulfilled.
[`set_verbosity(...)`](logging/set_verbosity): Sets the threshold for what messages will be logged.
[`vlog(...)`](logging/vlog)
[`warn(...)`](logging/warn)
[`warning(...)`](logging/warning)
| Other Members |
| DEBUG | `10` |
| ERROR | `40` |
| FATAL | `50` |
| INFO | `20` |
| WARN | `30` |
tensorflow tf.compat.v1.sparse_to_dense tf.compat.v1.sparse\_to\_dense
==============================
Converts a sparse representation into a dense tensor. (deprecated)
```
tf.compat.v1.sparse_to_dense(
sparse_indices,
output_shape,
sparse_values,
default_value=0,
validate_indices=True,
name=None
)
```
Builds an array `dense` with shape `output_shape` such that
```
# If sparse_indices is scalar
dense[i] = (i == sparse_indices ? sparse_values : default_value)
# If sparse_indices is a vector, then for each i
dense[sparse_indices[i]] = sparse_values[i]
# If sparse_indices is an n by d matrix, then for each i in [0, n)
dense[sparse_indices[i][0], ..., sparse_indices[i][d-1]] = sparse_values[i]
```
All other values in `dense` are set to `default_value`. If `sparse_values` is a scalar, all sparse indices are set to this single value.
Indices should be sorted in lexicographic order, and indices must not contain any repeats. If `validate_indices` is True, these properties are checked during execution.
| Args |
| `sparse_indices` | A 0-D, 1-D, or 2-D `Tensor` of type `int32` or `int64`. `sparse_indices[i]` contains the complete index where `sparse_values[i]` will be placed. |
| `output_shape` | A 1-D `Tensor` of the same type as `sparse_indices`. Shape of the dense output tensor. |
| `sparse_values` | A 0-D or 1-D `Tensor`. Values corresponding to each row of `sparse_indices`, or a scalar value to be used for all sparse indices. |
| `default_value` | A 0-D `Tensor` of the same type as `sparse_values`. Value to set for indices not specified in `sparse_indices`. Defaults to zero. |
| `validate_indices` | A boolean value. If True, indices are checked to make sure they are sorted in lexicographic order and that there are no repeats. |
| `name` | A name for the operation (optional). |
| Returns |
| Dense `Tensor` of shape `output_shape`. Has the same type as `sparse_values`. |
tensorflow tf.compat.v1.OptimizerOptions tf.compat.v1.OptimizerOptions
=============================
A ProtocolMessage
| Attributes |
| `cpu_global_jit` | `bool cpu_global_jit` |
| `do_common_subexpression_elimination` | `bool do_common_subexpression_elimination` |
| `do_constant_folding` | `bool do_constant_folding` |
| `do_function_inlining` | `bool do_function_inlining` |
| `global_jit_level` | `GlobalJitLevel global_jit_level` |
| `max_folded_constant_in_bytes` | `int64 max_folded_constant_in_bytes` |
| `opt_level` | `Level opt_level` |
| Class Variables |
| DEFAULT | `0` |
| GlobalJitLevel | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
| L0 | `-1` |
| L1 | `0` |
| Level | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
| OFF | `-1` |
| ON\_1 | `1` |
| ON\_2 | `2` |
tensorflow tf.compat.v1.get_collection_ref tf.compat.v1.get\_collection\_ref
=================================
Wrapper for [`Graph.get_collection_ref()`](https://www.tensorflow.org/api_docs/python/tf/Graph#get_collection_ref) using the default graph.
```
tf.compat.v1.get_collection_ref(
key
)
```
See [`tf.Graph.get_collection_ref`](../../graph#get_collection_ref) for more details.
| Args |
| `key` | The key for the collection. For example, the `GraphKeys` class contains many standard names for collections. |
| Returns |
| The list of values in the collection with the given `name`, or an empty list if no value has been added to that collection. Note that this returns the collection list itself, which can be modified in place to change the collection. |
eager compatibility
-------------------
Collections are not supported when eager execution is enabled.
tensorflow tf.compat.v1.FixedLengthRecordReader tf.compat.v1.FixedLengthRecordReader
====================================
A Reader that outputs fixed-length records from a file.
Inherits From: [`ReaderBase`](readerbase)
```
tf.compat.v1.FixedLengthRecordReader(
record_bytes,
header_bytes=None,
footer_bytes=None,
hop_bytes=None,
name=None,
encoding=None
)
```
See ReaderBase for supported methods.
| Args |
| `record_bytes` | An int. |
| `header_bytes` | An optional int. Defaults to 0. |
| `footer_bytes` | An optional int. Defaults to 0. |
| `hop_bytes` | An optional int. Defaults to 0. |
| `name` | A name for the operation (optional). |
| `encoding` | The type of encoding for the file. Defaults to none. |
| Attributes |
| `reader_ref` | Op that implements the reader. |
| `supports_serialize` | Whether the Reader implementation can serialize its state. |
Methods
-------
### `num_records_produced`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L328-L346)
```
num_records_produced(
name=None
)
```
Returns the number of records this reader has produced.
This is the same as the number of Read executions that have succeeded.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `num_work_units_completed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L348-L362)
```
num_work_units_completed(
name=None
)
```
Returns the number of work units this reader has finished processing.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| An int64 Tensor. |
### `read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L261-L288)
```
read(
queue, name=None
)
```
Returns the next record (key, value) pair produced by a reader.
Will dequeue a work unit from queue if necessary (e.g. when the Reader needs to start reading from a new file since it has finished with the previous file).
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (key, value). |
| `key` | A string scalar Tensor. |
| `value` | A string scalar Tensor. |
### `read_up_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L290-L326)
```
read_up_to(
queue, num_records, name=None
)
```
Returns up to num\_records (key, value) pairs produced by a reader.
Will dequeue a work unit from queue if necessary (e.g., when the Reader needs to start reading from a new file since it has finished with the previous file). It may return less than num\_records even before the last batch.
| Args |
| `queue` | A Queue or a mutable string Tensor representing a handle to a Queue, with string work items. |
| `num_records` | Number of records to read. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of Tensors (keys, values). |
| `keys` | A 1-D string Tensor. |
| `values` | A 1-D string Tensor. |
### `reset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L406-L418)
```
reset(
name=None
)
```
Restore a reader to its initial clean state.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `restore_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L381-L399)
```
restore_state(
state, name=None
)
```
Restore a reader to a previously saved state.
Not all Readers support being restored, so this can produce an Unimplemented error.
| Args |
| `state` | A string Tensor. Result of a SerializeState of a Reader with matching type. |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
### `serialize_state`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/io_ops.py#L364-L379)
```
serialize_state(
name=None
)
```
Produce a string tensor that encodes the state of a reader.
Not all Readers support being serialized, so this can produce an Unimplemented error.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A string Tensor. |
eager compatibility
-------------------
Readers are not compatible with eager execution. Instead, please use [`tf.data`](../../data) to get data into your model.
tensorflow tf.compat.v1.shape tf.compat.v1.shape
==================
Returns the shape of a tensor.
```
tf.compat.v1.shape(
input,
name=None,
out_type=tf.dtypes.int32
)
```
This operation returns a 1-D integer tensor representing the shape of `input`.
#### For example:
```
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
tf.shape(t) # [2, 2, 3]
```
| Args |
| `input` | A `Tensor` or `SparseTensor`. |
| `name` | A name for the operation (optional). |
| `out_type` | (Optional) The specified output type of the operation (`int32` or `int64`). Defaults to [`tf.int32`](../../../tf#int32). |
| Returns |
| A `Tensor` of type `out_type`. |
tensorflow Module: tf.compat.v1.estimator Module: tf.compat.v1.estimator
==============================
Estimator: High level tools for working with models.
Modules
-------
[`experimental`](estimator/experimental) module: Public API for tf.estimator.experimental namespace.
[`export`](estimator/export) module: All public utility methods for exporting Estimator to SavedModel.
[`inputs`](estimator/inputs) module: Utility methods to create simple input\_fns.
[`tpu`](estimator/tpu) module: Public API for tf.estimator.tpu namespace.
Classes
-------
[`class BaselineClassifier`](estimator/baselineclassifier): A classifier that can establish a simple baseline.
[`class BaselineEstimator`](estimator/baselineestimator): An estimator that can establish a simple baseline.
[`class BaselineRegressor`](estimator/baselineregressor): A regressor that can establish a simple baseline.
[`class BestExporter`](../../estimator/bestexporter): This class exports the serving graph and checkpoints of the best models.
[`class BinaryClassHead`](../../estimator/binaryclasshead): Creates a `Head` for single label binary classification.
[`class CheckpointSaverHook`](../../estimator/checkpointsaverhook): Saves checkpoints every N steps or seconds.
[`class CheckpointSaverListener`](../../estimator/checkpointsaverlistener): Interface for listeners that take action before or after checkpoint save.
[`class DNNClassifier`](estimator/dnnclassifier): A classifier for TensorFlow DNN models.
[`class DNNEstimator`](estimator/dnnestimator): An estimator for TensorFlow DNN models with user-specified head.
[`class DNNLinearCombinedClassifier`](estimator/dnnlinearcombinedclassifier): An estimator for TensorFlow Linear and DNN joined classification models.
[`class DNNLinearCombinedEstimator`](estimator/dnnlinearcombinedestimator): An estimator for TensorFlow Linear and DNN joined models with custom head.
[`class DNNLinearCombinedRegressor`](estimator/dnnlinearcombinedregressor): An estimator for TensorFlow Linear and DNN joined models for regression.
[`class DNNRegressor`](estimator/dnnregressor): A regressor for TensorFlow DNN models.
[`class Estimator`](estimator/estimator): Estimator class to train and evaluate TensorFlow models.
[`class EstimatorSpec`](../../estimator/estimatorspec): Ops and objects returned from a `model_fn` and passed to an `Estimator`.
[`class EvalSpec`](../../estimator/evalspec): Configuration for the "eval" part for the `train_and_evaluate` call.
[`class Exporter`](../../estimator/exporter): A class representing a type of model export.
[`class FeedFnHook`](../../estimator/feedfnhook): Runs `feed_fn` and sets the `feed_dict` accordingly.
[`class FinalExporter`](../../estimator/finalexporter): This class exports the serving graph and checkpoints at the end.
[`class FinalOpsHook`](../../estimator/finalopshook): A hook which evaluates `Tensors` at the end of a session.
[`class GlobalStepWaiterHook`](../../estimator/globalstepwaiterhook): Delays execution until global step reaches `wait_until_step`.
[`class Head`](../../estimator/head): Interface for the head/top of a model.
[`class LatestExporter`](../../estimator/latestexporter): This class regularly exports the serving graph and checkpoints.
[`class LinearClassifier`](estimator/linearclassifier): Linear classifier model.
[`class LinearEstimator`](estimator/linearestimator): An estimator for TensorFlow linear models with user-specified head.
[`class LinearRegressor`](estimator/linearregressor): An estimator for TensorFlow Linear regression problems.
[`class LoggingTensorHook`](../../estimator/loggingtensorhook): Prints the given tensors every N local steps, every N seconds, or at end.
[`class LogisticRegressionHead`](../../estimator/logisticregressionhead): Creates a `Head` for logistic regression.
[`class ModeKeys`](../../estimator/modekeys): Standard names for Estimator model modes.
[`class MultiClassHead`](../../estimator/multiclasshead): Creates a `Head` for multi class classification.
[`class MultiHead`](../../estimator/multihead): Creates a `Head` for multi-objective learning.
[`class MultiLabelHead`](../../estimator/multilabelhead): Creates a `Head` for multi-label classification.
[`class NanLossDuringTrainingError`](../../estimator/nanlossduringtrainingerror): Unspecified run-time error.
[`class NanTensorHook`](../../estimator/nantensorhook): Monitors the loss tensor and stops training if loss is NaN.
[`class PoissonRegressionHead`](../../estimator/poissonregressionhead): Creates a `Head` for poisson regression using [`tf.nn.log_poisson_loss`](../../nn/log_poisson_loss).
[`class ProfilerHook`](../../estimator/profilerhook): Captures CPU/GPU profiling information every N steps or seconds.
[`class RegressionHead`](../../estimator/regressionhead): Creates a `Head` for regression using the `mean_squared_error` loss.
[`class RunConfig`](../../estimator/runconfig): This class specifies the configurations for an `Estimator` run.
[`class SecondOrStepTimer`](../../estimator/secondorsteptimer): Timer that triggers at most once every N seconds or once every N steps.
[`class SessionRunArgs`](../../estimator/sessionrunargs): Represents arguments to be added to a `Session.run()` call.
[`class SessionRunContext`](../../estimator/sessionruncontext): Provides information about the `session.run()` call being made.
[`class SessionRunHook`](../../estimator/sessionrunhook): Hook to extend calls to MonitoredSession.run().
[`class SessionRunValues`](../../estimator/sessionrunvalues): Contains the results of `Session.run()`.
[`class StepCounterHook`](../../estimator/stepcounterhook): Hook that counts steps per second.
[`class StopAtStepHook`](../../estimator/stopatstephook): Hook that requests stop at a specified step.
[`class SummarySaverHook`](../../estimator/summarysaverhook): Saves summaries every N steps.
[`class TrainSpec`](../../estimator/trainspec): Configuration for the "train" part for the `train_and_evaluate` call.
[`class VocabInfo`](../../estimator/vocabinfo): Vocabulary information for warm-starting.
[`class WarmStartSettings`](../../estimator/warmstartsettings): Settings for warm-starting in `tf.estimator.Estimators`.
Functions
---------
[`add_metrics(...)`](../../estimator/add_metrics): Creates a new [`tf.estimator.Estimator`](../../estimator/estimator) which has given metrics.
[`classifier_parse_example_spec(...)`](estimator/classifier_parse_example_spec): Generates parsing spec for tf.parse\_example to be used with classifiers.
[`regressor_parse_example_spec(...)`](estimator/regressor_parse_example_spec): Generates parsing spec for tf.parse\_example to be used with regressors.
[`train_and_evaluate(...)`](../../estimator/train_and_evaluate): Train and evaluate the `estimator`.
tensorflow tf.compat.v1.get_variable tf.compat.v1.get\_variable
==========================
Gets an existing variable with these parameters or create a new one.
```
tf.compat.v1.get_variable(
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=None,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None,
constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../v1) api, [`tf.compat.v1.get_variable`](get_variable) is mostly compatible with eager execution and [`tf.function`](../../function) but only if you combine it with the [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables) decorator. (Though it will behave as if reuse is always set to `AUTO_REUSE`.)
See the [model migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) for more info.
If you do not combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables), `get_variable` will create a brand new variable every single time it is called and will never reuse variables, regardless of variable names or `reuse` arguments.
The TF2 equivalent of this symbol would be [`tf.Variable`](../../variable), but note that when using [`tf.Variable`](../../variable) you must make sure you track your variables (and regularizer arguments) either manually or via [`tf.Module`](../../module) or [`tf.keras.layers.Layer`](../../keras/layers/layer) mechanisms.
A section of the [migration guide](https://www.tensorflow.org/guide/migrate/model_mapping#incremental_migration_to_native_tf2) provides more details on incrementally migrating these usages to [`tf.Variable`](../../variable) as well.
>
> **Note:** The `partitioner` arg is not compatible with TF2 behaviors even when using [`tf.compat.v1.keras.utils.track_tf1_style_variables`](keras/utils/track_tf1_style_variables). It can be replaced by using `ParameterServerStrategy` and its partitioners. See the [multi-gpu migration guide](https://www.tensorflow.org/guide/migrate/multi_worker_cpu_gpu_training) and the ParameterServerStrategy guides it references for more info.
>
Description
-----------
This function prefixes the name with the current variable scope and performs reuse checks. See the [Variable Scope How To](https://tensorflow.org/guide/variables) for an extensive description of how reusing works. Here is a basic example:
```
def foo():
with tf.variable_scope("foo", reuse=tf.AUTO_REUSE):
v = tf.get_variable("v", [1])
return v
v1 = foo() # Creates v.
v2 = foo() # Gets the same, existing v.
assert v1 == v2
```
If initializer is `None` (the default), the default initializer passed in the variable scope will be used. If that one is `None` too, a `glorot_uniform_initializer` will be used. The initializer can also be a Tensor, in which case the variable is initialized to this value and shape.
Similarly, if the regularizer is `None` (the default), the default regularizer passed in the variable scope will be used (if that is `None` too, then by default no regularization is performed).
If a partitioner is provided, a `PartitionedVariable` is returned. Accessing this object as a `Tensor` returns the shards concatenated along the partition axis.
Some useful partitioners are available. See, e.g., `variable_axis_size_partitioner` and `min_max_variable_partitioner`.
| Args |
| `name` | The name of the new or existing variable. |
| `shape` | Shape of the new or existing variable. |
| `dtype` | Type of the new or existing variable (defaults to `DT_FLOAT`). |
| `initializer` | Initializer for the variable if one is created. Can either be an initializer object or a Tensor. If it's a Tensor, its shape must be known unless validate\_shape is False. |
| `regularizer` | A (Tensor -> Tensor or None) function; the result of applying it on a newly created variable will be added to the collection `tf.GraphKeys.REGULARIZATION_LOSSES` and can be used for regularization. |
| `trainable` | If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../variable)). |
| `collections` | List of graph collections keys to add the Variable to. Defaults to `[GraphKeys.GLOBAL_VARIABLES]` (see [`tf.Variable`](../../variable)). |
| `caching_device` | Optional device string or function describing where the Variable should be cached for reading. Defaults to the Variable's device. If not `None`, caches on another device. Typical use is to cache on the device where the Ops using the Variable reside, to deduplicate copying through `Switch` and other conditional statements. |
| `partitioner` | Optional callable that accepts a fully defined `TensorShape` and `dtype` of the Variable to be created, and returns a list of partitions for each axis (currently only one axis can be partitioned). |
| `validate_shape` | If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial\_value must be known. For this to be used the initializer must be a Tensor and not an initializer object. |
| `use_resource` | If False, creates a regular Variable. If true, creates an experimental ResourceVariable instead with well-defined semantics. Defaults to False (will later change to True). When eager execution is enabled this argument is always forced to be True. |
| `custom_getter` | Callable that takes as a first argument the true getter, and allows overwriting the internal get\_variable method. The signature of `custom_getter` should match that of this method, but the most future-proof version will allow for changes: `def custom_getter(getter, *args, **kwargs)`. Direct access to all `get_variable` parameters is also allowed: `def custom_getter(getter, name, *args, **kwargs)`. A simple identity custom getter that simply creates variables with modified names is:
```
def custom_getter(getter, name, *args, **kwargs):
return getter(name + '_suffix', *args, **kwargs)
```
|
| `constraint` | An optional projection function to be applied to the variable after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected Tensor representing the value of the variable and return the Tensor for the projected value (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `synchronization` | Indicates when a distributed a variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableSynchronization`](../../variablesynchronization). By default the synchronization is set to `AUTO` and the current `DistributionStrategy` chooses when to synchronize. |
| `aggregation` | Indicates how a distributed variable will be aggregated. Accepted values are constants defined in the class [`tf.VariableAggregation`](../../variableaggregation). |
| Returns |
| The created or existing `Variable` (or `PartitionedVariable`, if a partitioner was used). |
| Raises |
| `ValueError` | when creating a new variable and shape is not declared, when violating reuse during variable creation, or when `initializer` dtype and `dtype` don't match. Reuse is set inside `variable_scope`. |
| programming_docs |
tensorflow tf.compat.v1.disable_tensor_equality tf.compat.v1.disable\_tensor\_equality
======================================
Compare Tensors by their id and be hashable.
```
tf.compat.v1.disable_tensor_equality()
```
This is a legacy behaviour of TensorFlow and is highly discouraged.
tensorflow Module: tf.compat.v1.signal Module: tf.compat.v1.signal
===========================
Signal processing operations.
See the [tf.signal](https://tensorflow.org/api_guides/python/contrib.signal) guide.
Functions
---------
[`dct(...)`](../../signal/dct): Computes the 1D [Discrete Cosine Transform (DCT)][dct] of `input`.
[`fft(...)`](../../signal/fft): Fast Fourier transform.
[`fft2d(...)`](../../signal/fft2d): 2D fast Fourier transform.
[`fft3d(...)`](../../signal/fft3d): 3D fast Fourier transform.
[`fftshift(...)`](../../signal/fftshift): Shift the zero-frequency component to the center of the spectrum.
[`frame(...)`](../../signal/frame): Expands `signal`'s `axis` dimension into frames of `frame_length`.
[`hamming_window(...)`](../../signal/hamming_window): Generate a [Hamming](https://en.wikipedia.org/wiki/Window_function#Hamming_window) window.
[`hann_window(...)`](../../signal/hann_window): Generate a [Hann window](https://en.wikipedia.org/wiki/Window_function#Hann_window).
[`idct(...)`](../../signal/idct): Computes the 1D [Inverse Discrete Cosine Transform (DCT)][idct] of `input`.
[`ifft(...)`](../../signal/ifft): Inverse fast Fourier transform.
[`ifft2d(...)`](../../signal/ifft2d): Inverse 2D fast Fourier transform.
[`ifft3d(...)`](../../signal/ifft3d): Inverse 3D fast Fourier transform.
[`ifftshift(...)`](../../signal/ifftshift): The inverse of fftshift.
[`inverse_mdct(...)`](../../signal/inverse_mdct): Computes the inverse modified DCT of `mdcts`.
[`inverse_stft(...)`](../../signal/inverse_stft): Computes the inverse [Short-time Fourier Transform](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) of `stfts`.
[`inverse_stft_window_fn(...)`](../../signal/inverse_stft_window_fn): Generates a window function that can be used in `inverse_stft`.
[`irfft(...)`](../../signal/irfft): Inverse real-valued fast Fourier transform.
[`irfft2d(...)`](../../signal/irfft2d): Inverse 2D real-valued fast Fourier transform.
[`irfft3d(...)`](../../signal/irfft3d): Inverse 3D real-valued fast Fourier transform.
[`kaiser_bessel_derived_window(...)`](../../signal/kaiser_bessel_derived_window): Generate a [Kaiser Bessel derived window][kbd].
[`kaiser_window(...)`](../../signal/kaiser_window): Generate a [Kaiser window][kaiser].
[`linear_to_mel_weight_matrix(...)`](../../signal/linear_to_mel_weight_matrix): Returns a matrix to warp linear scale spectrograms to the [mel scale](https://en.wikipedia.org/wiki/Mel_scale).
[`mdct(...)`](../../signal/mdct): Computes the [Modified Discrete Cosine Transform][mdct] of `signals`.
[`mfccs_from_log_mel_spectrograms(...)`](../../signal/mfccs_from_log_mel_spectrograms): Computes [MFCCs](https://en.wikipedia.org/wiki/Mel-frequency_cepstrum) of `log_mel_spectrograms`.
[`overlap_and_add(...)`](../../signal/overlap_and_add): Reconstructs a signal from a framed representation.
[`rfft(...)`](../../signal/rfft): Real-valued fast Fourier transform.
[`rfft2d(...)`](../../signal/rfft2d): 2D real-valued fast Fourier transform.
[`rfft3d(...)`](../../signal/rfft3d): 3D real-valued fast Fourier transform.
[`stft(...)`](../../signal/stft): Computes the [Short-time Fourier Transform](https://en.wikipedia.org/wiki/Short-time_Fourier_transform) of `signals`.
[`vorbis_window(...)`](../../signal/vorbis_window): Generate a [Vorbis power complementary window][vorbis].
tensorflow Module: tf.compat.v1.raw_ops Module: tf.compat.v1.raw\_ops
=============================
Public API for tf.raw\_ops namespace.
Functions
---------
[`Abort(...)`](../../raw_ops/abort): Raise a exception to abort the process when called.
[`Abs(...)`](../../raw_ops/abs): Computes the absolute value of a tensor.
[`AccumulateNV2(...)`](../../raw_ops/accumulatenv2): Returns the element-wise sum of a list of tensors.
[`AccumulatorApplyGradient(...)`](../../raw_ops/accumulatorapplygradient): Applies a gradient to a given accumulator.
[`AccumulatorNumAccumulated(...)`](../../raw_ops/accumulatornumaccumulated): Returns the number of gradients aggregated in the given accumulators.
[`AccumulatorSetGlobalStep(...)`](../../raw_ops/accumulatorsetglobalstep): Updates the accumulator with a new value for global\_step.
[`AccumulatorTakeGradient(...)`](../../raw_ops/accumulatortakegradient): Extracts the average gradient in the given ConditionalAccumulator.
[`Acos(...)`](../../raw_ops/acos): Computes acos of x element-wise.
[`Acosh(...)`](../../raw_ops/acosh): Computes inverse hyperbolic cosine of x element-wise.
[`Add(...)`](../../raw_ops/add): Returns x + y element-wise.
[`AddManySparseToTensorsMap(...)`](../../raw_ops/addmanysparsetotensorsmap): Add an `N`-minibatch `SparseTensor` to a `SparseTensorsMap`, return `N` handles.
[`AddN(...)`](../../raw_ops/addn): Add all input tensors element wise.
[`AddSparseToTensorsMap(...)`](../../raw_ops/addsparsetotensorsmap): Add a `SparseTensor` to a `SparseTensorsMap` return its handle.
[`AddV2(...)`](../../raw_ops/addv2): Returns x + y element-wise.
[`AdjustContrast(...)`](../../raw_ops/adjustcontrast): Deprecated. Disallowed in GraphDef version >= 2.
[`AdjustContrastv2(...)`](../../raw_ops/adjustcontrastv2): Adjust the contrast of one or more images.
[`AdjustHue(...)`](../../raw_ops/adjusthue): Adjust the hue of one or more images.
[`AdjustSaturation(...)`](../../raw_ops/adjustsaturation): Adjust the saturation of one or more images.
[`All(...)`](../../raw_ops/all): Computes the "logical and" of elements across dimensions of a tensor.
[`AllCandidateSampler(...)`](../../raw_ops/allcandidatesampler): Generates labels for candidate sampling with a learned unigram distribution.
[`AllToAll(...)`](../../raw_ops/alltoall): An Op to exchange data across TPU replicas.
[`Angle(...)`](../../raw_ops/angle): Returns the argument of a complex number.
[`AnonymousHashTable(...)`](../../raw_ops/anonymoushashtable): Creates a uninitialized anonymous hash table.
[`AnonymousIterator(...)`](../../raw_ops/anonymousiterator): A container for an iterator resource.
[`AnonymousIteratorV2(...)`](../../raw_ops/anonymousiteratorv2): A container for an iterator resource.
[`AnonymousIteratorV3(...)`](../../raw_ops/anonymousiteratorv3): A container for an iterator resource.
[`AnonymousMemoryCache(...)`](../../raw_ops/anonymousmemorycache)
[`AnonymousMultiDeviceIterator(...)`](../../raw_ops/anonymousmultideviceiterator): A container for a multi device iterator resource.
[`AnonymousMultiDeviceIteratorV3(...)`](../../raw_ops/anonymousmultideviceiteratorv3): A container for a multi device iterator resource.
[`AnonymousMutableDenseHashTable(...)`](../../raw_ops/anonymousmutabledensehashtable): Creates an empty anonymous mutable hash table that uses tensors as the backing store.
[`AnonymousMutableHashTable(...)`](../../raw_ops/anonymousmutablehashtable): Creates an empty anonymous mutable hash table.
[`AnonymousMutableHashTableOfTensors(...)`](../../raw_ops/anonymousmutablehashtableoftensors): Creates an empty anonymous mutable hash table of vector values.
[`AnonymousRandomSeedGenerator(...)`](../../raw_ops/anonymousrandomseedgenerator)
[`AnonymousSeedGenerator(...)`](../../raw_ops/anonymousseedgenerator)
[`Any(...)`](../../raw_ops/any): Computes the "logical or" of elements across dimensions of a tensor.
[`ApplyAdaMax(...)`](../../raw_ops/applyadamax): Update '\*var' according to the AdaMax algorithm.
[`ApplyAdadelta(...)`](../../raw_ops/applyadadelta): Update '\*var' according to the adadelta scheme.
[`ApplyAdagrad(...)`](../../raw_ops/applyadagrad): Update '\*var' according to the adagrad scheme.
[`ApplyAdagradDA(...)`](../../raw_ops/applyadagradda): Update '\*var' according to the proximal adagrad scheme.
[`ApplyAdagradV2(...)`](../../raw_ops/applyadagradv2): Update '\*var' according to the adagrad scheme.
[`ApplyAdam(...)`](../../raw_ops/applyadam): Update '\*var' according to the Adam algorithm.
[`ApplyAddSign(...)`](../../raw_ops/applyaddsign): Update '\*var' according to the AddSign update.
[`ApplyCenteredRMSProp(...)`](../../raw_ops/applycenteredrmsprop): Update '\*var' according to the centered RMSProp algorithm.
[`ApplyFtrl(...)`](../../raw_ops/applyftrl): Update '\*var' according to the Ftrl-proximal scheme.
[`ApplyFtrlV2(...)`](../../raw_ops/applyftrlv2): Update '\*var' according to the Ftrl-proximal scheme.
[`ApplyGradientDescent(...)`](../../raw_ops/applygradientdescent): Update '\*var' by subtracting 'alpha' \* 'delta' from it.
[`ApplyMomentum(...)`](../../raw_ops/applymomentum): Update '\*var' according to the momentum scheme.
[`ApplyPowerSign(...)`](../../raw_ops/applypowersign): Update '\*var' according to the AddSign update.
[`ApplyProximalAdagrad(...)`](../../raw_ops/applyproximaladagrad): Update '*var' and '*accum' according to FOBOS with Adagrad learning rate.
[`ApplyProximalGradientDescent(...)`](../../raw_ops/applyproximalgradientdescent): Update '\*var' as FOBOS algorithm with fixed learning rate.
[`ApplyRMSProp(...)`](../../raw_ops/applyrmsprop): Update '\*var' according to the RMSProp algorithm.
[`ApproximateEqual(...)`](../../raw_ops/approximateequal): Returns the truth value of abs(x-y) < tolerance element-wise.
[`ArgMax(...)`](../../raw_ops/argmax): Returns the index with the largest value across dimensions of a tensor.
[`ArgMin(...)`](../../raw_ops/argmin): Returns the index with the smallest value across dimensions of a tensor.
[`AsString(...)`](../../raw_ops/asstring): Converts each entry in the given tensor to strings.
[`Asin(...)`](../../raw_ops/asin): Computes the trignometric inverse sine of x element-wise.
[`Asinh(...)`](../../raw_ops/asinh): Computes inverse hyperbolic sine of x element-wise.
[`Assert(...)`](../../raw_ops/assert): Asserts that the given condition is true.
[`AssertCardinalityDataset(...)`](../../raw_ops/assertcardinalitydataset)
[`AssertNextDataset(...)`](../../raw_ops/assertnextdataset): A transformation that asserts which transformations happen next.
[`AssertPrevDataset(...)`](../../raw_ops/assertprevdataset): A transformation that asserts which transformations happened previously.
[`Assign(...)`](../../raw_ops/assign): Update 'ref' by assigning 'value' to it.
[`AssignAdd(...)`](../../raw_ops/assignadd): Update 'ref' by adding 'value' to it.
[`AssignAddVariableOp(...)`](../../raw_ops/assignaddvariableop): Adds a value to the current value of a variable.
[`AssignSub(...)`](../../raw_ops/assignsub): Update 'ref' by subtracting 'value' from it.
[`AssignSubVariableOp(...)`](../../raw_ops/assignsubvariableop): Subtracts a value from the current value of a variable.
[`AssignVariableOp(...)`](../../raw_ops/assignvariableop): Assigns a new value to a variable.
[`AssignVariableXlaConcatND(...)`](../../raw_ops/assignvariablexlaconcatnd): Concats input tensor across all dimensions.
[`Atan(...)`](../../raw_ops/atan): Computes the trignometric inverse tangent of x element-wise.
[`Atan2(...)`](../../raw_ops/atan2): Computes arctangent of `y/x` element-wise, respecting signs of the arguments.
[`Atanh(...)`](../../raw_ops/atanh): Computes inverse hyperbolic tangent of x element-wise.
[`AudioSpectrogram(...)`](../../raw_ops/audiospectrogram): Produces a visualization of audio data over time.
[`AudioSummary(...)`](../../raw_ops/audiosummary): Outputs a `Summary` protocol buffer with audio.
[`AudioSummaryV2(...)`](../../raw_ops/audiosummaryv2): Outputs a `Summary` protocol buffer with audio.
[`AutoShardDataset(...)`](../../raw_ops/autosharddataset): Creates a dataset that shards the input dataset.
[`AvgPool(...)`](../../raw_ops/avgpool): Performs average pooling on the input.
[`AvgPool3D(...)`](../../raw_ops/avgpool3d): Performs 3D average pooling on the input.
[`AvgPool3DGrad(...)`](../../raw_ops/avgpool3dgrad): Computes gradients of average pooling function.
[`AvgPoolGrad(...)`](../../raw_ops/avgpoolgrad): Computes gradients of the average pooling function.
[`BandedTriangularSolve(...)`](../../raw_ops/bandedtriangularsolve)
[`Barrier(...)`](../../raw_ops/barrier): Defines a barrier that persists across different graph executions.
[`BarrierClose(...)`](../../raw_ops/barrierclose): Closes the given barrier.
[`BarrierIncompleteSize(...)`](../../raw_ops/barrierincompletesize): Computes the number of incomplete elements in the given barrier.
[`BarrierInsertMany(...)`](../../raw_ops/barrierinsertmany): For each key, assigns the respective value to the specified component.
[`BarrierReadySize(...)`](../../raw_ops/barrierreadysize): Computes the number of complete elements in the given barrier.
[`BarrierTakeMany(...)`](../../raw_ops/barriertakemany): Takes the given number of completed elements from a barrier.
[`Batch(...)`](../../raw_ops/batch): Batches all input tensors nondeterministically.
[`BatchCholesky(...)`](../../raw_ops/batchcholesky)
[`BatchCholeskyGrad(...)`](../../raw_ops/batchcholeskygrad)
[`BatchDataset(...)`](../../raw_ops/batchdataset): Creates a dataset that batches `batch_size` elements from `input_dataset`.
[`BatchDatasetV2(...)`](../../raw_ops/batchdatasetv2): Creates a dataset that batches `batch_size` elements from `input_dataset`.
[`BatchFFT(...)`](../../raw_ops/batchfft)
[`BatchFFT2D(...)`](../../raw_ops/batchfft2d)
[`BatchFFT3D(...)`](../../raw_ops/batchfft3d)
[`BatchFunction(...)`](../../raw_ops/batchfunction): Batches all the inputs tensors to the computation done by the function.
[`BatchIFFT(...)`](../../raw_ops/batchifft)
[`BatchIFFT2D(...)`](../../raw_ops/batchifft2d)
[`BatchIFFT3D(...)`](../../raw_ops/batchifft3d)
[`BatchMatMul(...)`](../../raw_ops/batchmatmul): Multiplies slices of two tensors in batches.
[`BatchMatMulV2(...)`](../../raw_ops/batchmatmulv2): Multiplies slices of two tensors in batches.
[`BatchMatMulV3(...)`](../../raw_ops/batchmatmulv3): Multiplies slices of two tensors in batches.
[`BatchMatrixBandPart(...)`](../../raw_ops/batchmatrixbandpart)
[`BatchMatrixDeterminant(...)`](../../raw_ops/batchmatrixdeterminant)
[`BatchMatrixDiag(...)`](../../raw_ops/batchmatrixdiag)
[`BatchMatrixDiagPart(...)`](../../raw_ops/batchmatrixdiagpart)
[`BatchMatrixInverse(...)`](../../raw_ops/batchmatrixinverse)
[`BatchMatrixSetDiag(...)`](../../raw_ops/batchmatrixsetdiag)
[`BatchMatrixSolve(...)`](../../raw_ops/batchmatrixsolve)
[`BatchMatrixSolveLs(...)`](../../raw_ops/batchmatrixsolvels)
[`BatchMatrixTriangularSolve(...)`](../../raw_ops/batchmatrixtriangularsolve)
[`BatchNormWithGlobalNormalization(...)`](../../raw_ops/batchnormwithglobalnormalization): Batch normalization.
[`BatchNormWithGlobalNormalizationGrad(...)`](../../raw_ops/batchnormwithglobalnormalizationgrad): Gradients for batch normalization.
[`BatchSelfAdjointEig(...)`](../../raw_ops/batchselfadjointeig)
[`BatchSelfAdjointEigV2(...)`](../../raw_ops/batchselfadjointeigv2)
[`BatchSvd(...)`](../../raw_ops/batchsvd)
[`BatchToSpace(...)`](../../raw_ops/batchtospace): BatchToSpace for 4-D tensors of type T.
[`BatchToSpaceND(...)`](../../raw_ops/batchtospacend): BatchToSpace for N-D tensors of type T.
[`BesselI0(...)`](../../raw_ops/besseli0)
[`BesselI0e(...)`](../../raw_ops/besseli0e)
[`BesselI1(...)`](../../raw_ops/besseli1)
[`BesselI1e(...)`](../../raw_ops/besseli1e)
[`BesselJ0(...)`](../../raw_ops/besselj0)
[`BesselJ1(...)`](../../raw_ops/besselj1)
[`BesselK0(...)`](../../raw_ops/besselk0)
[`BesselK0e(...)`](../../raw_ops/besselk0e)
[`BesselK1(...)`](../../raw_ops/besselk1)
[`BesselK1e(...)`](../../raw_ops/besselk1e)
[`BesselY0(...)`](../../raw_ops/bessely0)
[`BesselY1(...)`](../../raw_ops/bessely1)
[`Betainc(...)`](../../raw_ops/betainc): Compute the regularized incomplete beta integral \(I\_x(a, b)\).
[`BiasAdd(...)`](../../raw_ops/biasadd): Adds `bias` to `value`.
[`BiasAddGrad(...)`](../../raw_ops/biasaddgrad): The backward operation for "BiasAdd" on the "bias" tensor.
[`BiasAddV1(...)`](../../raw_ops/biasaddv1): Adds `bias` to `value`.
[`Bincount(...)`](../../raw_ops/bincount): Counts the number of occurrences of each value in an integer array.
[`Bitcast(...)`](../../raw_ops/bitcast): Bitcasts a tensor from one type to another without copying data.
[`BitwiseAnd(...)`](../../raw_ops/bitwiseand): Elementwise computes the bitwise AND of `x` and `y`.
[`BitwiseOr(...)`](../../raw_ops/bitwiseor): Elementwise computes the bitwise OR of `x` and `y`.
[`BitwiseXor(...)`](../../raw_ops/bitwisexor): Elementwise computes the bitwise XOR of `x` and `y`.
[`BlockLSTM(...)`](../../raw_ops/blocklstm): Computes the LSTM cell forward propagation for all the time steps.
[`BlockLSTMGrad(...)`](../../raw_ops/blocklstmgrad): Computes the LSTM cell backward propagation for the entire time sequence.
[`BlockLSTMGradV2(...)`](../../raw_ops/blocklstmgradv2): Computes the LSTM cell backward propagation for the entire time sequence.
[`BlockLSTMV2(...)`](../../raw_ops/blocklstmv2): Computes the LSTM cell forward propagation for all the time steps.
[`BoostedTreesAggregateStats(...)`](../../raw_ops/boostedtreesaggregatestats): Aggregates the summary of accumulated stats for the batch.
[`BoostedTreesBucketize(...)`](../../raw_ops/boostedtreesbucketize): Bucketize each feature based on bucket boundaries.
[`BoostedTreesCalculateBestFeatureSplit(...)`](../../raw_ops/boostedtreescalculatebestfeaturesplit): Calculates gains for each feature and returns the best possible split information for the feature.
[`BoostedTreesCalculateBestFeatureSplitV2(...)`](../../raw_ops/boostedtreescalculatebestfeaturesplitv2): Calculates gains for each feature and returns the best possible split information for each node. However, if no split is found, then no split information is returned for that node.
[`BoostedTreesCalculateBestGainsPerFeature(...)`](../../raw_ops/boostedtreescalculatebestgainsperfeature): Calculates gains for each feature and returns the best possible split information for the feature.
[`BoostedTreesCenterBias(...)`](../../raw_ops/boostedtreescenterbias): Calculates the prior from the training data (the bias) and fills in the first node with the logits' prior. Returns a boolean indicating whether to continue centering.
[`BoostedTreesCreateEnsemble(...)`](../../raw_ops/boostedtreescreateensemble): Creates a tree ensemble model and returns a handle to it.
[`BoostedTreesCreateQuantileStreamResource(...)`](../../raw_ops/boostedtreescreatequantilestreamresource): Create the Resource for Quantile Streams.
[`BoostedTreesDeserializeEnsemble(...)`](../../raw_ops/boostedtreesdeserializeensemble): Deserializes a serialized tree ensemble config and replaces current tree
[`BoostedTreesEnsembleResourceHandleOp(...)`](../../raw_ops/boostedtreesensembleresourcehandleop): Creates a handle to a BoostedTreesEnsembleResource
[`BoostedTreesExampleDebugOutputs(...)`](../../raw_ops/boostedtreesexampledebugoutputs): Debugging/model interpretability outputs for each example.
[`BoostedTreesFlushQuantileSummaries(...)`](../../raw_ops/boostedtreesflushquantilesummaries): Flush the quantile summaries from each quantile stream resource.
[`BoostedTreesGetEnsembleStates(...)`](../../raw_ops/boostedtreesgetensemblestates): Retrieves the tree ensemble resource stamp token, number of trees and growing statistics.
[`BoostedTreesMakeQuantileSummaries(...)`](../../raw_ops/boostedtreesmakequantilesummaries): Makes the summary of quantiles for the batch.
[`BoostedTreesMakeStatsSummary(...)`](../../raw_ops/boostedtreesmakestatssummary): Makes the summary of accumulated stats for the batch.
[`BoostedTreesPredict(...)`](../../raw_ops/boostedtreespredict): Runs multiple additive regression ensemble predictors on input instances and
[`BoostedTreesQuantileStreamResourceAddSummaries(...)`](../../raw_ops/boostedtreesquantilestreamresourceaddsummaries): Add the quantile summaries to each quantile stream resource.
[`BoostedTreesQuantileStreamResourceDeserialize(...)`](../../raw_ops/boostedtreesquantilestreamresourcedeserialize): Deserialize bucket boundaries and ready flag into current QuantileAccumulator.
[`BoostedTreesQuantileStreamResourceFlush(...)`](../../raw_ops/boostedtreesquantilestreamresourceflush): Flush the summaries for a quantile stream resource.
[`BoostedTreesQuantileStreamResourceGetBucketBoundaries(...)`](../../raw_ops/boostedtreesquantilestreamresourcegetbucketboundaries): Generate the bucket boundaries for each feature based on accumulated summaries.
[`BoostedTreesQuantileStreamResourceHandleOp(...)`](../../raw_ops/boostedtreesquantilestreamresourcehandleop): Creates a handle to a BoostedTreesQuantileStreamResource.
[`BoostedTreesSerializeEnsemble(...)`](../../raw_ops/boostedtreesserializeensemble): Serializes the tree ensemble to a proto.
[`BoostedTreesSparseAggregateStats(...)`](../../raw_ops/boostedtreessparseaggregatestats): Aggregates the summary of accumulated stats for the batch.
[`BoostedTreesSparseCalculateBestFeatureSplit(...)`](../../raw_ops/boostedtreessparsecalculatebestfeaturesplit): Calculates gains for each feature and returns the best possible split information for the feature.
[`BoostedTreesTrainingPredict(...)`](../../raw_ops/boostedtreestrainingpredict): Runs multiple additive regression ensemble predictors on input instances and
[`BoostedTreesUpdateEnsemble(...)`](../../raw_ops/boostedtreesupdateensemble): Updates the tree ensemble by either adding a layer to the last tree being grown
[`BoostedTreesUpdateEnsembleV2(...)`](../../raw_ops/boostedtreesupdateensemblev2): Updates the tree ensemble by adding a layer to the last tree being grown
[`BroadcastArgs(...)`](../../raw_ops/broadcastargs): Return the shape of s0 op s1 with broadcast.
[`BroadcastGradientArgs(...)`](../../raw_ops/broadcastgradientargs): Return the reduction indices for computing gradients of s0 op s1 with broadcast.
[`BroadcastTo(...)`](../../raw_ops/broadcastto): Broadcast an array for a compatible shape.
[`Bucketize(...)`](../../raw_ops/bucketize): Bucketizes 'input' based on 'boundaries'.
[`BytesProducedStatsDataset(...)`](../../raw_ops/bytesproducedstatsdataset): Records the bytes size of each element of `input_dataset` in a StatsAggregator.
[`CSRSparseMatrixComponents(...)`](../../raw_ops/csrsparsematrixcomponents): Reads out the CSR components at batch `index`.
[`CSRSparseMatrixToDense(...)`](../../raw_ops/csrsparsematrixtodense): Convert a (possibly batched) CSRSparseMatrix to dense.
[`CSRSparseMatrixToSparseTensor(...)`](../../raw_ops/csrsparsematrixtosparsetensor): Converts a (possibly batched) CSRSparesMatrix to a SparseTensor.
[`CSVDataset(...)`](../../raw_ops/csvdataset)
[`CSVDatasetV2(...)`](../../raw_ops/csvdatasetv2)
[`CTCBeamSearchDecoder(...)`](../../raw_ops/ctcbeamsearchdecoder): Performs beam search decoding on the logits given in input.
[`CTCGreedyDecoder(...)`](../../raw_ops/ctcgreedydecoder): Performs greedy decoding on the logits given in inputs.
[`CTCLoss(...)`](../../raw_ops/ctcloss): Calculates the CTC Loss (log probability) for each batch entry. Also calculates
[`CTCLossV2(...)`](../../raw_ops/ctclossv2): Calculates the CTC Loss (log probability) for each batch entry. Also calculates
[`CacheDataset(...)`](../../raw_ops/cachedataset): Creates a dataset that caches elements from `input_dataset`.
[`CacheDatasetV2(...)`](../../raw_ops/cachedatasetv2)
[`Case(...)`](../../raw_ops/case): An n-way switch statement which calls a single branch function.
[`Cast(...)`](../../raw_ops/cast): Cast x of type SrcT to y of DstT.
[`Ceil(...)`](../../raw_ops/ceil): Returns element-wise smallest integer not less than x.
[`CheckNumerics(...)`](../../raw_ops/checknumerics): Checks a tensor for NaN and Inf values.
[`CheckNumericsV2(...)`](../../raw_ops/checknumericsv2): Checks a tensor for NaN, -Inf and +Inf values.
[`Cholesky(...)`](../../raw_ops/cholesky): Computes the Cholesky decomposition of one or more square matrices.
[`CholeskyGrad(...)`](../../raw_ops/choleskygrad): Computes the reverse mode backpropagated gradient of the Cholesky algorithm.
[`ChooseFastestBranchDataset(...)`](../../raw_ops/choosefastestbranchdataset)
[`ChooseFastestDataset(...)`](../../raw_ops/choosefastestdataset)
[`ClipByValue(...)`](../../raw_ops/clipbyvalue): Clips tensor values to a specified min and max.
[`CloseSummaryWriter(...)`](../../raw_ops/closesummarywriter)
[`CollectiveAllToAllV3(...)`](../../raw_ops/collectivealltoallv3): Mutually exchanges multiple tensors of identical type and shape.
[`CollectiveAssignGroupV2(...)`](../../raw_ops/collectiveassigngroupv2): Assign group keys based on group assignment.
[`CollectiveBcastRecv(...)`](../../raw_ops/collectivebcastrecv): Receives a tensor value broadcast from another device.
[`CollectiveBcastRecvV2(...)`](../../raw_ops/collectivebcastrecvv2): Receives a tensor value broadcast from another device.
[`CollectiveBcastSend(...)`](../../raw_ops/collectivebcastsend): Broadcasts a tensor value to one or more other devices.
[`CollectiveBcastSendV2(...)`](../../raw_ops/collectivebcastsendv2): Broadcasts a tensor value to one or more other devices.
[`CollectiveGather(...)`](../../raw_ops/collectivegather): Mutually accumulates multiple tensors of identical type and shape.
[`CollectiveGatherV2(...)`](../../raw_ops/collectivegatherv2): Mutually accumulates multiple tensors of identical type and shape.
[`CollectiveInitializeCommunicator(...)`](../../raw_ops/collectiveinitializecommunicator): Initializes a group for collective operations.
[`CollectivePermute(...)`](../../raw_ops/collectivepermute): An Op to permute tensors across replicated TPU instances.
[`CollectiveReduce(...)`](../../raw_ops/collectivereduce): Mutually reduces multiple tensors of identical type and shape.
[`CollectiveReduceV2(...)`](../../raw_ops/collectivereducev2): Mutually reduces multiple tensors of identical type and shape.
[`CollectiveReduceV3(...)`](../../raw_ops/collectivereducev3): Mutually reduces multiple tensors of identical type and shape.
[`CombinedNonMaxSuppression(...)`](../../raw_ops/combinednonmaxsuppression): Greedily selects a subset of bounding boxes in descending order of score,
[`Complex(...)`](../../raw_ops/complex): Converts two real numbers to a complex number.
[`ComplexAbs(...)`](../../raw_ops/complexabs): Computes the complex absolute value of a tensor.
[`CompositeTensorVariantFromComponents(...)`](../../raw_ops/compositetensorvariantfromcomponents): Encodes an `ExtensionType` value into a `variant` scalar Tensor.
[`CompositeTensorVariantToComponents(...)`](../../raw_ops/compositetensorvarianttocomponents): Decodes a `variant` scalar Tensor into an `ExtensionType` value.
[`CompressElement(...)`](../../raw_ops/compresselement): Compresses a dataset element.
[`ComputeAccidentalHits(...)`](../../raw_ops/computeaccidentalhits): Computes the ids of the positions in sampled\_candidates that match true\_labels.
[`ComputeBatchSize(...)`](../../raw_ops/computebatchsize): Computes the static batch size of a dataset sans partial batches.
[`Concat(...)`](../../raw_ops/concat): Concatenates tensors along one dimension.
[`ConcatOffset(...)`](../../raw_ops/concatoffset): Computes offsets of concat inputs within its output.
[`ConcatV2(...)`](../../raw_ops/concatv2): Concatenates tensors along one dimension.
[`ConcatenateDataset(...)`](../../raw_ops/concatenatedataset): Creates a dataset that concatenates `input_dataset` with `another_dataset`.
[`ConditionalAccumulator(...)`](../../raw_ops/conditionalaccumulator): A conditional accumulator for aggregating gradients.
[`ConfigureDistributedTPU(...)`](../../raw_ops/configuredistributedtpu): Sets up the centralized structures for a distributed TPU system.
[`ConfigureTPUEmbedding(...)`](../../raw_ops/configuretpuembedding): Sets up TPUEmbedding in a distributed TPU system.
[`Conj(...)`](../../raw_ops/conj): Returns the complex conjugate of a complex number.
[`ConjugateTranspose(...)`](../../raw_ops/conjugatetranspose): Shuffle dimensions of x according to a permutation and conjugate the result.
[`Const(...)`](../../raw_ops/const): Returns a constant tensor.
[`ConsumeMutexLock(...)`](../../raw_ops/consumemutexlock): This op consumes a lock created by `MutexLock`.
[`ControlTrigger(...)`](../../raw_ops/controltrigger): Does nothing. Serves as a control trigger for scheduling.
[`Conv2D(...)`](../../raw_ops/conv2d): Computes a 2-D convolution given 4-D `input` and `filter` tensors.
[`Conv2DBackpropFilter(...)`](../../raw_ops/conv2dbackpropfilter): Computes the gradients of convolution with respect to the filter.
[`Conv2DBackpropInput(...)`](../../raw_ops/conv2dbackpropinput): Computes the gradients of convolution with respect to the input.
[`Conv3D(...)`](../../raw_ops/conv3d): Computes a 3-D convolution given 5-D `input` and `filter` tensors.
[`Conv3DBackpropFilter(...)`](../../raw_ops/conv3dbackpropfilter): Computes the gradients of 3-D convolution with respect to the filter.
[`Conv3DBackpropFilterV2(...)`](../../raw_ops/conv3dbackpropfilterv2): Computes the gradients of 3-D convolution with respect to the filter.
[`Conv3DBackpropInput(...)`](../../raw_ops/conv3dbackpropinput): Computes the gradients of 3-D convolution with respect to the input.
[`Conv3DBackpropInputV2(...)`](../../raw_ops/conv3dbackpropinputv2): Computes the gradients of 3-D convolution with respect to the input.
[`Copy(...)`](../../raw_ops/copy): Copy a tensor from CPU-to-CPU or GPU-to-GPU.
[`CopyHost(...)`](../../raw_ops/copyhost): Copy a tensor to host.
[`Cos(...)`](../../raw_ops/cos): Computes cos of x element-wise.
[`Cosh(...)`](../../raw_ops/cosh): Computes hyperbolic cosine of x element-wise.
[`CountUpTo(...)`](../../raw_ops/countupto): Increments 'ref' until it reaches 'limit'.
[`CreateSummaryDbWriter(...)`](../../raw_ops/createsummarydbwriter)
[`CreateSummaryFileWriter(...)`](../../raw_ops/createsummaryfilewriter)
[`CropAndResize(...)`](../../raw_ops/cropandresize): Extracts crops from the input image tensor and resizes them.
[`CropAndResizeGradBoxes(...)`](../../raw_ops/cropandresizegradboxes): Computes the gradient of the crop\_and\_resize op wrt the input boxes tensor.
[`CropAndResizeGradImage(...)`](../../raw_ops/cropandresizegradimage): Computes the gradient of the crop\_and\_resize op wrt the input image tensor.
[`Cross(...)`](../../raw_ops/cross): Compute the pairwise cross product.
[`CrossReplicaSum(...)`](../../raw_ops/crossreplicasum): An Op to sum inputs across replicated TPU instances.
[`CudnnRNN(...)`](../../raw_ops/cudnnrnn): A RNN backed by cuDNN.
[`CudnnRNNBackprop(...)`](../../raw_ops/cudnnrnnbackprop): Backprop step of CudnnRNN.
[`CudnnRNNBackpropV2(...)`](../../raw_ops/cudnnrnnbackpropv2): Backprop step of CudnnRNN.
[`CudnnRNNBackpropV3(...)`](../../raw_ops/cudnnrnnbackpropv3): Backprop step of CudnnRNNV3.
[`CudnnRNNCanonicalToParams(...)`](../../raw_ops/cudnnrnncanonicaltoparams): Converts CudnnRNN params from canonical form to usable form.
[`CudnnRNNCanonicalToParamsV2(...)`](../../raw_ops/cudnnrnncanonicaltoparamsv2): Converts CudnnRNN params from canonical form to usable form. It supports the projection in LSTM.
[`CudnnRNNParamsSize(...)`](../../raw_ops/cudnnrnnparamssize): Computes size of weights that can be used by a Cudnn RNN model.
[`CudnnRNNParamsToCanonical(...)`](../../raw_ops/cudnnrnnparamstocanonical): Retrieves CudnnRNN params in canonical form.
[`CudnnRNNParamsToCanonicalV2(...)`](../../raw_ops/cudnnrnnparamstocanonicalv2): Retrieves CudnnRNN params in canonical form. It supports the projection in LSTM.
[`CudnnRNNV2(...)`](../../raw_ops/cudnnrnnv2): A RNN backed by cuDNN.
[`CudnnRNNV3(...)`](../../raw_ops/cudnnrnnv3): A RNN backed by cuDNN.
[`Cumprod(...)`](../../raw_ops/cumprod): Compute the cumulative product of the tensor `x` along `axis`.
[`Cumsum(...)`](../../raw_ops/cumsum): Compute the cumulative sum of the tensor `x` along `axis`.
[`CumulativeLogsumexp(...)`](../../raw_ops/cumulativelogsumexp): Compute the cumulative product of the tensor `x` along `axis`.
[`DataFormatDimMap(...)`](../../raw_ops/dataformatdimmap): Returns the dimension index in the destination data format given the one in
[`DataFormatVecPermute(...)`](../../raw_ops/dataformatvecpermute): Permute input tensor from `src_format` to `dst_format`.
[`DataServiceDataset(...)`](../../raw_ops/dataservicedataset): Creates a dataset that reads data from the tf.data service.
[`DataServiceDatasetV2(...)`](../../raw_ops/dataservicedatasetv2): Creates a dataset that reads data from the tf.data service.
[`DataServiceDatasetV3(...)`](../../raw_ops/dataservicedatasetv3): Creates a dataset that reads data from the tf.data service.
[`DatasetCardinality(...)`](../../raw_ops/datasetcardinality): Returns the cardinality of `input_dataset`.
[`DatasetFromGraph(...)`](../../raw_ops/datasetfromgraph): Creates a dataset from the given `graph_def`.
[`DatasetToGraph(...)`](../../raw_ops/datasettograph): Returns a serialized GraphDef representing `input_dataset`.
[`DatasetToGraphV2(...)`](../../raw_ops/datasettographv2): Returns a serialized GraphDef representing `input_dataset`.
[`DatasetToSingleElement(...)`](../../raw_ops/datasettosingleelement): Outputs the single element from the given dataset.
[`DatasetToTFRecord(...)`](../../raw_ops/datasettotfrecord): Writes the given dataset to the given file using the TFRecord format.
[`Dawsn(...)`](../../raw_ops/dawsn)
[`DebugGradientIdentity(...)`](../../raw_ops/debuggradientidentity): Identity op for gradient debugging.
[`DebugGradientRefIdentity(...)`](../../raw_ops/debuggradientrefidentity): Identity op for gradient debugging.
[`DebugIdentity(...)`](../../raw_ops/debugidentity): Provides an identity mapping of the non-Ref type input tensor for debugging.
[`DebugIdentityV2(...)`](../../raw_ops/debugidentityv2): Debug Identity V2 Op.
[`DebugNanCount(...)`](../../raw_ops/debugnancount): Debug NaN Value Counter Op.
[`DebugNumericSummary(...)`](../../raw_ops/debugnumericsummary): Debug Numeric Summary Op.
[`DebugNumericSummaryV2(...)`](../../raw_ops/debugnumericsummaryv2): Debug Numeric Summary V2 Op.
[`DecodeAndCropJpeg(...)`](../../raw_ops/decodeandcropjpeg): Decode and Crop a JPEG-encoded image to a uint8 tensor.
[`DecodeBase64(...)`](../../raw_ops/decodebase64): Decode web-safe base64-encoded strings.
[`DecodeBmp(...)`](../../raw_ops/decodebmp): Decode the first frame of a BMP-encoded image to a uint8 tensor.
[`DecodeCSV(...)`](../../raw_ops/decodecsv): Convert CSV records to tensors. Each column maps to one tensor.
[`DecodeCompressed(...)`](../../raw_ops/decodecompressed): Decompress strings.
[`DecodeGif(...)`](../../raw_ops/decodegif): Decode the frame(s) of a GIF-encoded image to a uint8 tensor.
[`DecodeImage(...)`](../../raw_ops/decodeimage): Function for decode\_bmp, decode\_gif, decode\_jpeg, and decode\_png.
[`DecodeJSONExample(...)`](../../raw_ops/decodejsonexample): Convert JSON-encoded Example records to binary protocol buffer strings.
[`DecodeJpeg(...)`](../../raw_ops/decodejpeg): Decode a JPEG-encoded image to a uint8 tensor.
[`DecodePaddedRaw(...)`](../../raw_ops/decodepaddedraw): Reinterpret the bytes of a string as a vector of numbers.
[`DecodePng(...)`](../../raw_ops/decodepng): Decode a PNG-encoded image to a uint8 or uint16 tensor.
[`DecodeProtoV2(...)`](../../raw_ops/decodeprotov2): The op extracts fields from a serialized protocol buffers message into tensors.
[`DecodeRaw(...)`](../../raw_ops/decoderaw): Reinterpret the bytes of a string as a vector of numbers.
[`DecodeWav(...)`](../../raw_ops/decodewav): Decode a 16-bit PCM WAV file to a float tensor.
[`DeepCopy(...)`](../../raw_ops/deepcopy): Makes a copy of `x`.
[`DeleteIterator(...)`](../../raw_ops/deleteiterator): A container for an iterator resource.
[`DeleteMemoryCache(...)`](../../raw_ops/deletememorycache)
[`DeleteMultiDeviceIterator(...)`](../../raw_ops/deletemultideviceiterator): A container for an iterator resource.
[`DeleteRandomSeedGenerator(...)`](../../raw_ops/deleterandomseedgenerator)
[`DeleteSeedGenerator(...)`](../../raw_ops/deleteseedgenerator)
[`DeleteSessionTensor(...)`](../../raw_ops/deletesessiontensor): Delete the tensor specified by its handle in the session.
[`DenseBincount(...)`](../../raw_ops/densebincount): Counts the number of occurrences of each value in an integer array.
[`DenseCountSparseOutput(...)`](../../raw_ops/densecountsparseoutput): Performs sparse-output bin counting for a tf.tensor input.
[`DenseToCSRSparseMatrix(...)`](../../raw_ops/densetocsrsparsematrix): Converts a dense tensor to a (possibly batched) CSRSparseMatrix.
[`DenseToDenseSetOperation(...)`](../../raw_ops/densetodensesetoperation): Applies set operation along last dimension of 2 `Tensor` inputs.
[`DenseToSparseBatchDataset(...)`](../../raw_ops/densetosparsebatchdataset): Creates a dataset that batches input elements into a SparseTensor.
[`DenseToSparseSetOperation(...)`](../../raw_ops/densetosparsesetoperation): Applies set operation along last dimension of `Tensor` and `SparseTensor`.
[`DepthToSpace(...)`](../../raw_ops/depthtospace): DepthToSpace for tensors of type T.
[`DepthwiseConv2dNative(...)`](../../raw_ops/depthwiseconv2dnative): Computes a 2-D depthwise convolution given 4-D `input` and `filter` tensors.
[`DepthwiseConv2dNativeBackpropFilter(...)`](../../raw_ops/depthwiseconv2dnativebackpropfilter): Computes the gradients of depthwise convolution with respect to the filter.
[`DepthwiseConv2dNativeBackpropInput(...)`](../../raw_ops/depthwiseconv2dnativebackpropinput): Computes the gradients of depthwise convolution with respect to the input.
[`Dequantize(...)`](../../raw_ops/dequantize): Dequantize the 'input' tensor into a float or bfloat16 Tensor.
[`DeserializeIterator(...)`](../../raw_ops/deserializeiterator): Converts the given variant tensor to an iterator and stores it in the given resource.
[`DeserializeManySparse(...)`](../../raw_ops/deserializemanysparse): Deserialize and concatenate `SparseTensors` from a serialized minibatch.
[`DeserializeSparse(...)`](../../raw_ops/deserializesparse): Deserialize `SparseTensor` objects.
[`DestroyResourceOp(...)`](../../raw_ops/destroyresourceop): Deletes the resource specified by the handle.
[`DestroyTemporaryVariable(...)`](../../raw_ops/destroytemporaryvariable): Destroys the temporary variable and returns its final value.
[`DeviceIndex(...)`](../../raw_ops/deviceindex): Return the index of device the op runs.
[`Diag(...)`](../../raw_ops/diag): Returns a diagonal tensor with a given diagonal values.
[`DiagPart(...)`](../../raw_ops/diagpart): Returns the diagonal part of the tensor.
[`Digamma(...)`](../../raw_ops/digamma): Computes Psi, the derivative of Lgamma (the log of the absolute value of
[`Dilation2D(...)`](../../raw_ops/dilation2d): Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors.
[`Dilation2DBackpropFilter(...)`](../../raw_ops/dilation2dbackpropfilter): Computes the gradient of morphological 2-D dilation with respect to the filter.
[`Dilation2DBackpropInput(...)`](../../raw_ops/dilation2dbackpropinput): Computes the gradient of morphological 2-D dilation with respect to the input.
[`DirectedInterleaveDataset(...)`](../../raw_ops/directedinterleavedataset): A substitute for `InterleaveDataset` on a fixed list of `N` datasets.
[`Div(...)`](../../raw_ops/div): Returns x / y element-wise.
[`DivNoNan(...)`](../../raw_ops/divnonan): Returns 0 if the denominator is zero.
[`DrawBoundingBoxes(...)`](../../raw_ops/drawboundingboxes): Draw bounding boxes on a batch of images.
[`DrawBoundingBoxesV2(...)`](../../raw_ops/drawboundingboxesv2): Draw bounding boxes on a batch of images.
[`DummyIterationCounter(...)`](../../raw_ops/dummyiterationcounter)
[`DummyMemoryCache(...)`](../../raw_ops/dummymemorycache)
[`DummySeedGenerator(...)`](../../raw_ops/dummyseedgenerator)
[`DynamicEnqueueTPUEmbeddingArbitraryTensorBatch(...)`](../../raw_ops/dynamicenqueuetpuembeddingarbitrarytensorbatch): Eases the porting of code that uses tf.nn.embedding\_lookup\_sparse().
[`DynamicPartition(...)`](../../raw_ops/dynamicpartition): Partitions `data` into `num_partitions` tensors using indices from `partitions`.
[`DynamicStitch(...)`](../../raw_ops/dynamicstitch): Interleave the values from the `data` tensors into a single tensor.
[`EagerPyFunc(...)`](../../raw_ops/eagerpyfunc): Eagerly executes a python function to compute func(input)->output. The
[`EditDistance(...)`](../../raw_ops/editdistance): Computes the (possibly normalized) Levenshtein Edit Distance.
[`Eig(...)`](../../raw_ops/eig): Computes the eigen decomposition of one or more square matrices.
[`Einsum(...)`](../../raw_ops/einsum): Tensor contraction according to Einstein summation convention.
[`Elu(...)`](../../raw_ops/elu): Computes the exponential linear function.
[`EluGrad(...)`](../../raw_ops/elugrad): Computes gradients for the exponential linear (Elu) operation.
[`Empty(...)`](../../raw_ops/empty): Creates a tensor with the given shape.
[`EmptyTensorList(...)`](../../raw_ops/emptytensorlist): Creates and returns an empty tensor list.
[`EncodeBase64(...)`](../../raw_ops/encodebase64): Encode strings into web-safe base64 format.
[`EncodeJpeg(...)`](../../raw_ops/encodejpeg): JPEG-encode an image.
[`EncodeJpegVariableQuality(...)`](../../raw_ops/encodejpegvariablequality): JPEG encode input image with provided compression quality.
[`EncodePng(...)`](../../raw_ops/encodepng): PNG-encode an image.
[`EncodeProto(...)`](../../raw_ops/encodeproto): The op serializes protobuf messages provided in the input tensors.
[`EncodeWav(...)`](../../raw_ops/encodewav): Encode audio data using the WAV file format.
[`EnqueueTPUEmbeddingArbitraryTensorBatch(...)`](../../raw_ops/enqueuetpuembeddingarbitrarytensorbatch): Eases the porting of code that uses tf.nn.embedding\_lookup\_sparse().
[`EnqueueTPUEmbeddingIntegerBatch(...)`](../../raw_ops/enqueuetpuembeddingintegerbatch): An op that enqueues a list of input batch tensors to TPUEmbedding.
[`EnqueueTPUEmbeddingRaggedTensorBatch(...)`](../../raw_ops/enqueuetpuembeddingraggedtensorbatch): Eases the porting of code that uses tf.nn.embedding\_lookup().
[`EnqueueTPUEmbeddingSparseBatch(...)`](../../raw_ops/enqueuetpuembeddingsparsebatch): An op that enqueues TPUEmbedding input indices from a SparseTensor.
[`EnqueueTPUEmbeddingSparseTensorBatch(...)`](../../raw_ops/enqueuetpuembeddingsparsetensorbatch): Eases the porting of code that uses tf.nn.embedding\_lookup\_sparse().
[`EnsureShape(...)`](../../raw_ops/ensureshape): Ensures that the tensor's shape matches the expected shape.
[`Enter(...)`](../../raw_ops/enter): Creates or finds a child frame, and makes `data` available to the child frame.
[`Equal(...)`](../../raw_ops/equal): Returns the truth value of (x == y) element-wise.
[`Erf(...)`](../../raw_ops/erf): Computes the [Gauss error function](https://en.wikipedia.org/wiki/Error_function) of `x` element-wise. In statistics, for non-negative values of \(x\), the error function has the following interpretation: for a random variable \(Y\) that is normally distributed with mean 0 and variance \(1/\sqrt{2}\), \(erf(x)\) is the probability that \(Y\) falls in the range \([−x, x]\).
[`Erfc(...)`](../../raw_ops/erfc): Computes the complementary error function of `x` element-wise.
[`Erfinv(...)`](../../raw_ops/erfinv)
[`EuclideanNorm(...)`](../../raw_ops/euclideannorm): Computes the euclidean norm of elements across dimensions of a tensor.
[`Exit(...)`](../../raw_ops/exit): Exits the current frame to its parent frame.
[`Exp(...)`](../../raw_ops/exp): Computes exponential of x element-wise. \(y = e^x\).
[`ExpandDims(...)`](../../raw_ops/expanddims): Inserts a dimension of 1 into a tensor's shape.
[`ExperimentalAssertNextDataset(...)`](../../raw_ops/experimentalassertnextdataset)
[`ExperimentalAutoShardDataset(...)`](../../raw_ops/experimentalautosharddataset): Creates a dataset that shards the input dataset.
[`ExperimentalBytesProducedStatsDataset(...)`](../../raw_ops/experimentalbytesproducedstatsdataset): Records the bytes size of each element of `input_dataset` in a StatsAggregator.
[`ExperimentalCSVDataset(...)`](../../raw_ops/experimentalcsvdataset)
[`ExperimentalChooseFastestDataset(...)`](../../raw_ops/experimentalchoosefastestdataset)
[`ExperimentalDatasetCardinality(...)`](../../raw_ops/experimentaldatasetcardinality): Returns the cardinality of `input_dataset`.
[`ExperimentalDatasetToTFRecord(...)`](../../raw_ops/experimentaldatasettotfrecord): Writes the given dataset to the given file using the TFRecord format.
[`ExperimentalDenseToSparseBatchDataset(...)`](../../raw_ops/experimentaldensetosparsebatchdataset): Creates a dataset that batches input elements into a SparseTensor.
[`ExperimentalDirectedInterleaveDataset(...)`](../../raw_ops/experimentaldirectedinterleavedataset): A substitute for `InterleaveDataset` on a fixed list of `N` datasets.
[`ExperimentalGroupByReducerDataset(...)`](../../raw_ops/experimentalgroupbyreducerdataset): Creates a dataset that computes a group-by on `input_dataset`.
[`ExperimentalGroupByWindowDataset(...)`](../../raw_ops/experimentalgroupbywindowdataset): Creates a dataset that computes a windowed group-by on `input_dataset`.
[`ExperimentalIgnoreErrorsDataset(...)`](../../raw_ops/experimentalignoreerrorsdataset): Creates a dataset that contains the elements of `input_dataset` ignoring errors.
[`ExperimentalIteratorGetDevice(...)`](../../raw_ops/experimentaliteratorgetdevice): Returns the name of the device on which `resource` has been placed.
[`ExperimentalLMDBDataset(...)`](../../raw_ops/experimentallmdbdataset)
[`ExperimentalLatencyStatsDataset(...)`](../../raw_ops/experimentallatencystatsdataset): Records the latency of producing `input_dataset` elements in a StatsAggregator.
[`ExperimentalMapAndBatchDataset(...)`](../../raw_ops/experimentalmapandbatchdataset): Creates a dataset that fuses mapping with batching.
[`ExperimentalMapDataset(...)`](../../raw_ops/experimentalmapdataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ExperimentalMatchingFilesDataset(...)`](../../raw_ops/experimentalmatchingfilesdataset)
[`ExperimentalMaxIntraOpParallelismDataset(...)`](../../raw_ops/experimentalmaxintraopparallelismdataset): Creates a dataset that overrides the maximum intra-op parallelism.
[`ExperimentalNonSerializableDataset(...)`](../../raw_ops/experimentalnonserializabledataset)
[`ExperimentalParallelInterleaveDataset(...)`](../../raw_ops/experimentalparallelinterleavedataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ExperimentalParseExampleDataset(...)`](../../raw_ops/experimentalparseexampledataset): Transforms `input_dataset` containing `Example` protos as vectors of DT\_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features.
[`ExperimentalPrivateThreadPoolDataset(...)`](../../raw_ops/experimentalprivatethreadpooldataset): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`ExperimentalRandomDataset(...)`](../../raw_ops/experimentalrandomdataset): Creates a Dataset that returns pseudorandom numbers.
[`ExperimentalRebatchDataset(...)`](../../raw_ops/experimentalrebatchdataset): Creates a dataset that changes the batch size.
[`ExperimentalScanDataset(...)`](../../raw_ops/experimentalscandataset): Creates a dataset successively reduces `f` over the elements of `input_dataset`.
[`ExperimentalSetStatsAggregatorDataset(...)`](../../raw_ops/experimentalsetstatsaggregatordataset)
[`ExperimentalSleepDataset(...)`](../../raw_ops/experimentalsleepdataset)
[`ExperimentalSlidingWindowDataset(...)`](../../raw_ops/experimentalslidingwindowdataset): Creates a dataset that passes a sliding window over `input_dataset`.
[`ExperimentalSqlDataset(...)`](../../raw_ops/experimentalsqldataset): Creates a dataset that executes a SQL query and emits rows of the result set.
[`ExperimentalStatsAggregatorHandle(...)`](../../raw_ops/experimentalstatsaggregatorhandle): Creates a statistics manager resource.
[`ExperimentalStatsAggregatorSummary(...)`](../../raw_ops/experimentalstatsaggregatorsummary): Produces a summary of any statistics recorded by the given statistics manager.
[`ExperimentalTakeWhileDataset(...)`](../../raw_ops/experimentaltakewhiledataset): Creates a dataset that stops iteration when predicate` is false.
[`ExperimentalThreadPoolDataset(...)`](../../raw_ops/experimentalthreadpooldataset): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`ExperimentalThreadPoolHandle(...)`](../../raw_ops/experimentalthreadpoolhandle): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`ExperimentalUnbatchDataset(...)`](../../raw_ops/experimentalunbatchdataset): A dataset that splits the elements of its input into multiple elements.
[`ExperimentalUniqueDataset(...)`](../../raw_ops/experimentaluniquedataset): Creates a dataset that contains the unique elements of `input_dataset`.
[`Expint(...)`](../../raw_ops/expint)
[`Expm1(...)`](../../raw_ops/expm1): Computes `exp(x) - 1` element-wise.
[`ExtractGlimpse(...)`](../../raw_ops/extractglimpse): Extracts a glimpse from the input tensor.
[`ExtractGlimpseV2(...)`](../../raw_ops/extractglimpsev2): Extracts a glimpse from the input tensor.
[`ExtractImagePatches(...)`](../../raw_ops/extractimagepatches): Extract `patches` from `images` and put them in the "depth" output dimension.
[`ExtractJpegShape(...)`](../../raw_ops/extractjpegshape): Extract the shape information of a JPEG-encoded image.
[`ExtractVolumePatches(...)`](../../raw_ops/extractvolumepatches): Extract `patches` from `input` and put them in the `"depth"` output dimension. 3D extension of `extract_image_patches`.
[`FFT(...)`](../../raw_ops/fft): Fast Fourier transform.
[`FFT2D(...)`](../../raw_ops/fft2d): 2D fast Fourier transform.
[`FFT3D(...)`](../../raw_ops/fft3d): 3D fast Fourier transform.
[`FIFOQueue(...)`](../../raw_ops/fifoqueue): A queue that produces elements in first-in first-out order.
[`FIFOQueueV2(...)`](../../raw_ops/fifoqueuev2): A queue that produces elements in first-in first-out order.
[`Fact(...)`](../../raw_ops/fact): Output a fact about factorials.
[`FakeParam(...)`](../../raw_ops/fakeparam): This op is used as a placeholder in If branch functions. It doesn't provide a
[`FakeQuantWithMinMaxArgs(...)`](../../raw_ops/fakequantwithminmaxargs): Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type.
[`FakeQuantWithMinMaxArgsGradient(...)`](../../raw_ops/fakequantwithminmaxargsgradient): Compute gradients for a FakeQuantWithMinMaxArgs operation.
[`FakeQuantWithMinMaxVars(...)`](../../raw_ops/fakequantwithminmaxvars): Fake-quantize the 'inputs' tensor of type float via global float scalars
[`FakeQuantWithMinMaxVarsGradient(...)`](../../raw_ops/fakequantwithminmaxvarsgradient): Compute gradients for a FakeQuantWithMinMaxVars operation.
[`FakeQuantWithMinMaxVarsPerChannel(...)`](../../raw_ops/fakequantwithminmaxvarsperchannel): Fake-quantize the 'inputs' tensor of type float via per-channel floats
[`FakeQuantWithMinMaxVarsPerChannelGradient(...)`](../../raw_ops/fakequantwithminmaxvarsperchannelgradient): Compute gradients for a FakeQuantWithMinMaxVarsPerChannel operation.
[`FakeQueue(...)`](../../raw_ops/fakequeue): Deprecated. Do not use.
[`Fill(...)`](../../raw_ops/fill): Creates a tensor filled with a scalar value.
[`FilterByLastComponentDataset(...)`](../../raw_ops/filterbylastcomponentdataset): Creates a dataset containing elements of first component of `input_dataset` having true in the last component.
[`FilterDataset(...)`](../../raw_ops/filterdataset): Creates a dataset containing elements of `input_dataset` matching `predicate`.
[`FinalizeDataset(...)`](../../raw_ops/finalizedataset): Creates a dataset by applying [`tf.data.Options`](../../data/options) to `input_dataset`.
[`Fingerprint(...)`](../../raw_ops/fingerprint): Generates fingerprint values.
[`FixedLengthRecordDataset(...)`](../../raw_ops/fixedlengthrecorddataset): Creates a dataset that emits the records from one or more binary files.
[`FixedLengthRecordDatasetV2(...)`](../../raw_ops/fixedlengthrecorddatasetv2)
[`FixedLengthRecordReader(...)`](../../raw_ops/fixedlengthrecordreader): A Reader that outputs fixed-length records from a file.
[`FixedLengthRecordReaderV2(...)`](../../raw_ops/fixedlengthrecordreaderv2): A Reader that outputs fixed-length records from a file.
[`FixedUnigramCandidateSampler(...)`](../../raw_ops/fixedunigramcandidatesampler): Generates labels for candidate sampling with a learned unigram distribution.
[`FlatMapDataset(...)`](../../raw_ops/flatmapdataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`Floor(...)`](../../raw_ops/floor): Returns element-wise largest integer not greater than x.
[`FloorDiv(...)`](../../raw_ops/floordiv): Returns x // y element-wise.
[`FloorMod(...)`](../../raw_ops/floormod): Returns element-wise remainder of division. When `x < 0` xor `y < 0` is
[`FlushSummaryWriter(...)`](../../raw_ops/flushsummarywriter)
[`For(...)`](../../raw_ops/for): Applies a for loop.
[`FractionalAvgPool(...)`](../../raw_ops/fractionalavgpool): Performs fractional average pooling on the input.
[`FractionalAvgPoolGrad(...)`](../../raw_ops/fractionalavgpoolgrad): Computes gradient of the FractionalAvgPool function.
[`FractionalMaxPool(...)`](../../raw_ops/fractionalmaxpool): Performs fractional max pooling on the input.
[`FractionalMaxPoolGrad(...)`](../../raw_ops/fractionalmaxpoolgrad): Computes gradient of the FractionalMaxPool function.
[`FresnelCos(...)`](../../raw_ops/fresnelcos)
[`FresnelSin(...)`](../../raw_ops/fresnelsin)
[`FusedBatchNorm(...)`](../../raw_ops/fusedbatchnorm): Batch normalization.
[`FusedBatchNormGrad(...)`](../../raw_ops/fusedbatchnormgrad): Gradient for batch normalization.
[`FusedBatchNormGradV2(...)`](../../raw_ops/fusedbatchnormgradv2): Gradient for batch normalization.
[`FusedBatchNormGradV3(...)`](../../raw_ops/fusedbatchnormgradv3): Gradient for batch normalization.
[`FusedBatchNormV2(...)`](../../raw_ops/fusedbatchnormv2): Batch normalization.
[`FusedBatchNormV3(...)`](../../raw_ops/fusedbatchnormv3): Batch normalization.
[`FusedPadConv2D(...)`](../../raw_ops/fusedpadconv2d): Performs a padding as a preprocess during a convolution.
[`FusedResizeAndPadConv2D(...)`](../../raw_ops/fusedresizeandpadconv2d): Performs a resize and padding as a preprocess during a convolution.
[`GRUBlockCell(...)`](../../raw_ops/grublockcell): Computes the GRU cell forward propagation for 1 time step.
[`GRUBlockCellGrad(...)`](../../raw_ops/grublockcellgrad): Computes the GRU cell back-propagation for 1 time step.
[`Gather(...)`](../../raw_ops/gather): Gather slices from `params` according to `indices`.
[`GatherNd(...)`](../../raw_ops/gathernd): Gather slices from `params` into a Tensor with shape specified by `indices`.
[`GatherV2(...)`](../../raw_ops/gatherv2): Gather slices from `params` axis `axis` according to `indices`.
[`GenerateBoundingBoxProposals(...)`](../../raw_ops/generateboundingboxproposals): This op produces Region of Interests from given bounding boxes(bbox\_deltas) encoded wrt anchors according to eq.2 in arXiv:1506.01497
[`GenerateVocabRemapping(...)`](../../raw_ops/generatevocabremapping): Given a path to new and old vocabulary files, returns a remapping Tensor of
[`GeneratorDataset(...)`](../../raw_ops/generatordataset): Creates a dataset that invokes a function to generate elements.
[`GetElementAtIndex(...)`](../../raw_ops/getelementatindex): Gets the element at the specified index in a dataset.
[`GetOptions(...)`](../../raw_ops/getoptions): Returns the [`tf.data.Options`](../../data/options) attached to `input_dataset`.
[`GetSessionHandle(...)`](../../raw_ops/getsessionhandle): Store the input tensor in the state of the current session.
[`GetSessionHandleV2(...)`](../../raw_ops/getsessionhandlev2): Store the input tensor in the state of the current session.
[`GetSessionTensor(...)`](../../raw_ops/getsessiontensor): Get the value of the tensor specified by its handle.
[`Greater(...)`](../../raw_ops/greater): Returns the truth value of (x > y) element-wise.
[`GreaterEqual(...)`](../../raw_ops/greaterequal): Returns the truth value of (x >= y) element-wise.
[`GroupByReducerDataset(...)`](../../raw_ops/groupbyreducerdataset): Creates a dataset that computes a group-by on `input_dataset`.
[`GroupByWindowDataset(...)`](../../raw_ops/groupbywindowdataset): Creates a dataset that computes a windowed group-by on `input_dataset`.
[`GuaranteeConst(...)`](../../raw_ops/guaranteeconst): Gives a guarantee to the TF runtime that the input tensor is a constant.
[`HSVToRGB(...)`](../../raw_ops/hsvtorgb): Convert one or more images from HSV to RGB.
[`HashTable(...)`](../../raw_ops/hashtable): Creates a non-initialized hash table.
[`HashTableV2(...)`](../../raw_ops/hashtablev2): Creates a non-initialized hash table.
[`HistogramFixedWidth(...)`](../../raw_ops/histogramfixedwidth): Return histogram of values.
[`HistogramSummary(...)`](../../raw_ops/histogramsummary): Outputs a `Summary` protocol buffer with a histogram.
[`IFFT(...)`](../../raw_ops/ifft): Inverse fast Fourier transform.
[`IFFT2D(...)`](../../raw_ops/ifft2d): Inverse 2D fast Fourier transform.
[`IFFT3D(...)`](../../raw_ops/ifft3d): Inverse 3D fast Fourier transform.
[`IRFFT(...)`](../../raw_ops/irfft): Inverse real-valued fast Fourier transform.
[`IRFFT2D(...)`](../../raw_ops/irfft2d): Inverse 2D real-valued fast Fourier transform.
[`IRFFT3D(...)`](../../raw_ops/irfft3d): Inverse 3D real-valued fast Fourier transform.
[`Identity(...)`](../../raw_ops/identity): Return a tensor with the same shape and contents as the input tensor or value.
[`IdentityN(...)`](../../raw_ops/identityn): Returns a list of tensors with the same shapes and contents as the input
[`IdentityReader(...)`](../../raw_ops/identityreader): A Reader that outputs the queued work as both the key and value.
[`IdentityReaderV2(...)`](../../raw_ops/identityreaderv2): A Reader that outputs the queued work as both the key and value.
[`If(...)`](../../raw_ops/if): output = cond ? then\_branch(input) : else\_branch(input)
[`Igamma(...)`](../../raw_ops/igamma): Compute the lower regularized incomplete Gamma function `P(a, x)`.
[`IgammaGradA(...)`](../../raw_ops/igammagrada): Computes the gradient of `igamma(a, x)` wrt `a`.
[`Igammac(...)`](../../raw_ops/igammac): Compute the upper regularized incomplete Gamma function `Q(a, x)`.
[`IgnoreErrorsDataset(...)`](../../raw_ops/ignoreerrorsdataset): Creates a dataset that contains the elements of `input_dataset` ignoring errors.
[`Imag(...)`](../../raw_ops/imag): Returns the imaginary part of a complex number.
[`ImageProjectiveTransformV2(...)`](../../raw_ops/imageprojectivetransformv2): Applies the given transform to each of the images.
[`ImageProjectiveTransformV3(...)`](../../raw_ops/imageprojectivetransformv3): Applies the given transform to each of the images.
[`ImageSummary(...)`](../../raw_ops/imagesummary): Outputs a `Summary` protocol buffer with images.
[`ImmutableConst(...)`](../../raw_ops/immutableconst): Returns immutable tensor from memory region.
[`ImportEvent(...)`](../../raw_ops/importevent)
[`InTopK(...)`](../../raw_ops/intopk): Says whether the targets are in the top `K` predictions.
[`InTopKV2(...)`](../../raw_ops/intopkv2): Says whether the targets are in the top `K` predictions.
[`InfeedDequeue(...)`](../../raw_ops/infeeddequeue): A placeholder op for a value that will be fed into the computation.
[`InfeedDequeueTuple(...)`](../../raw_ops/infeeddequeuetuple): Fetches multiple values from infeed as an XLA tuple.
[`InfeedEnqueue(...)`](../../raw_ops/infeedenqueue): An op which feeds a single Tensor value into the computation.
[`InfeedEnqueuePrelinearizedBuffer(...)`](../../raw_ops/infeedenqueueprelinearizedbuffer): An op which enqueues prelinearized buffer into TPU infeed.
[`InfeedEnqueueTuple(...)`](../../raw_ops/infeedenqueuetuple): Feeds multiple Tensor values into the computation as an XLA tuple.
[`InitializeTable(...)`](../../raw_ops/initializetable): Table initializer that takes two tensors for keys and values respectively.
[`InitializeTableFromDataset(...)`](../../raw_ops/initializetablefromdataset)
[`InitializeTableFromTextFile(...)`](../../raw_ops/initializetablefromtextfile): Initializes a table from a text file.
[`InitializeTableFromTextFileV2(...)`](../../raw_ops/initializetablefromtextfilev2): Initializes a table from a text file.
[`InitializeTableV2(...)`](../../raw_ops/initializetablev2): Table initializer that takes two tensors for keys and values respectively.
[`InplaceAdd(...)`](../../raw_ops/inplaceadd): Adds v into specified rows of x.
[`InplaceSub(...)`](../../raw_ops/inplacesub): Subtracts `v` into specified rows of `x`.
[`InplaceUpdate(...)`](../../raw_ops/inplaceupdate): Updates specified rows 'i' with values 'v'.
[`InterleaveDataset(...)`](../../raw_ops/interleavedataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`Inv(...)`](../../raw_ops/inv): Computes the reciprocal of x element-wise.
[`InvGrad(...)`](../../raw_ops/invgrad): Computes the gradient for the inverse of `x` wrt its input.
[`Invert(...)`](../../raw_ops/invert): Invert (flip) each bit of supported types; for example, type `uint8` value 01010101 becomes 10101010.
[`InvertPermutation(...)`](../../raw_ops/invertpermutation): Computes the inverse permutation of a tensor.
[`IsBoostedTreesEnsembleInitialized(...)`](../../raw_ops/isboostedtreesensembleinitialized): Checks whether a tree ensemble has been initialized.
[`IsBoostedTreesQuantileStreamResourceInitialized(...)`](../../raw_ops/isboostedtreesquantilestreamresourceinitialized): Checks whether a quantile stream has been initialized.
[`IsFinite(...)`](../../raw_ops/isfinite): Returns which elements of x are finite.
[`IsInf(...)`](../../raw_ops/isinf): Returns which elements of x are Inf.
[`IsNan(...)`](../../raw_ops/isnan): Returns which elements of x are NaN.
[`IsTPUEmbeddingInitialized(...)`](../../raw_ops/istpuembeddinginitialized): Whether TPU Embedding is initialized in a distributed TPU system.
[`IsVariableInitialized(...)`](../../raw_ops/isvariableinitialized): Checks whether a tensor has been initialized.
[`IsotonicRegression(...)`](../../raw_ops/isotonicregression): Solves a batch of isotonic regression problems.
[`Iterator(...)`](../../raw_ops/iterator): A container for an iterator resource.
[`IteratorFromStringHandle(...)`](../../raw_ops/iteratorfromstringhandle): Converts the given string representing a handle to an iterator to a resource.
[`IteratorFromStringHandleV2(...)`](../../raw_ops/iteratorfromstringhandlev2)
[`IteratorGetDevice(...)`](../../raw_ops/iteratorgetdevice): Returns the name of the device on which `resource` has been placed.
[`IteratorGetNext(...)`](../../raw_ops/iteratorgetnext): Gets the next output from the given iterator .
[`IteratorGetNextAsOptional(...)`](../../raw_ops/iteratorgetnextasoptional): Gets the next output from the given iterator as an Optional variant.
[`IteratorGetNextSync(...)`](../../raw_ops/iteratorgetnextsync): Gets the next output from the given iterator.
[`IteratorToStringHandle(...)`](../../raw_ops/iteratortostringhandle): Converts the given `resource_handle` representing an iterator to a string.
[`IteratorV2(...)`](../../raw_ops/iteratorv2)
[`L2Loss(...)`](../../raw_ops/l2loss): L2 Loss.
[`LMDBDataset(...)`](../../raw_ops/lmdbdataset): Creates a dataset that emits the key-value pairs in one or more LMDB files.
[`LMDBReader(...)`](../../raw_ops/lmdbreader): A Reader that outputs the records from a LMDB file.
[`LRN(...)`](../../raw_ops/lrn): Local Response Normalization.
[`LRNGrad(...)`](../../raw_ops/lrngrad): Gradients for Local Response Normalization.
[`LSTMBlockCell(...)`](../../raw_ops/lstmblockcell): Computes the LSTM cell forward propagation for 1 time step.
[`LSTMBlockCellGrad(...)`](../../raw_ops/lstmblockcellgrad): Computes the LSTM cell backward propagation for 1 timestep.
[`LatencyStatsDataset(...)`](../../raw_ops/latencystatsdataset): Records the latency of producing `input_dataset` elements in a StatsAggregator.
[`LeakyRelu(...)`](../../raw_ops/leakyrelu): Computes rectified linear: `max(features, features * alpha)`.
[`LeakyReluGrad(...)`](../../raw_ops/leakyrelugrad): Computes rectified linear gradients for a LeakyRelu operation.
[`LearnedUnigramCandidateSampler(...)`](../../raw_ops/learnedunigramcandidatesampler): Generates labels for candidate sampling with a learned unigram distribution.
[`LeftShift(...)`](../../raw_ops/leftshift): Elementwise computes the bitwise left-shift of `x` and `y`.
[`LegacyParallelInterleaveDatasetV2(...)`](../../raw_ops/legacyparallelinterleavedatasetv2): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`Less(...)`](../../raw_ops/less): Returns the truth value of (x < y) element-wise.
[`LessEqual(...)`](../../raw_ops/lessequal): Returns the truth value of (x <= y) element-wise.
[`Lgamma(...)`](../../raw_ops/lgamma): Computes the log of the absolute value of `Gamma(x)` element-wise.
[`LinSpace(...)`](../../raw_ops/linspace): Generates values in an interval.
[`ListDiff(...)`](../../raw_ops/listdiff): Computes the difference between two lists of numbers or strings.
[`LoadAndRemapMatrix(...)`](../../raw_ops/loadandremapmatrix): Loads a 2-D (matrix) `Tensor` with name `old_tensor_name` from the checkpoint
[`LoadDataset(...)`](../../raw_ops/loaddataset)
[`LoadTPUEmbeddingADAMParameters(...)`](../../raw_ops/loadtpuembeddingadamparameters): Load ADAM embedding parameters.
[`LoadTPUEmbeddingAdadeltaParameters(...)`](../../raw_ops/loadtpuembeddingadadeltaparameters): Load Adadelta embedding parameters.
[`LoadTPUEmbeddingAdagradMomentumParameters(...)`](../../raw_ops/loadtpuembeddingadagradmomentumparameters): Load Adagrad Momentum embedding parameters.
[`LoadTPUEmbeddingAdagradParameters(...)`](../../raw_ops/loadtpuembeddingadagradparameters): Load Adagrad embedding parameters.
[`LoadTPUEmbeddingCenteredRMSPropParameters(...)`](../../raw_ops/loadtpuembeddingcenteredrmspropparameters): Load centered RMSProp embedding parameters.
[`LoadTPUEmbeddingFTRLParameters(...)`](../../raw_ops/loadtpuembeddingftrlparameters): Load FTRL embedding parameters.
[`LoadTPUEmbeddingFrequencyEstimatorParameters(...)`](../../raw_ops/loadtpuembeddingfrequencyestimatorparameters): Load frequency estimator embedding parameters.
[`LoadTPUEmbeddingMDLAdagradLightParameters(...)`](../../raw_ops/loadtpuembeddingmdladagradlightparameters): Load MDL Adagrad Light embedding parameters.
[`LoadTPUEmbeddingMomentumParameters(...)`](../../raw_ops/loadtpuembeddingmomentumparameters): Load Momentum embedding parameters.
[`LoadTPUEmbeddingProximalAdagradParameters(...)`](../../raw_ops/loadtpuembeddingproximaladagradparameters): Load proximal Adagrad embedding parameters.
[`LoadTPUEmbeddingProximalYogiParameters(...)`](../../raw_ops/loadtpuembeddingproximalyogiparameters)
[`LoadTPUEmbeddingRMSPropParameters(...)`](../../raw_ops/loadtpuembeddingrmspropparameters): Load RMSProp embedding parameters.
[`LoadTPUEmbeddingStochasticGradientDescentParameters(...)`](../../raw_ops/loadtpuembeddingstochasticgradientdescentparameters): Load SGD embedding parameters.
[`Log(...)`](../../raw_ops/log): Computes natural logarithm of x element-wise.
[`Log1p(...)`](../../raw_ops/log1p): Computes natural logarithm of (1 + x) element-wise.
[`LogMatrixDeterminant(...)`](../../raw_ops/logmatrixdeterminant): Computes the sign and the log of the absolute value of the determinant of
[`LogSoftmax(...)`](../../raw_ops/logsoftmax): Computes log softmax activations.
[`LogUniformCandidateSampler(...)`](../../raw_ops/loguniformcandidatesampler): Generates labels for candidate sampling with a log-uniform distribution.
[`LogicalAnd(...)`](../../raw_ops/logicaland): Returns the truth value of x AND y element-wise.
[`LogicalNot(...)`](../../raw_ops/logicalnot): Returns the truth value of `NOT x` element-wise.
[`LogicalOr(...)`](../../raw_ops/logicalor): Returns the truth value of x OR y element-wise.
[`LookupTableExport(...)`](../../raw_ops/lookuptableexport): Outputs all keys and values in the table.
[`LookupTableExportV2(...)`](../../raw_ops/lookuptableexportv2): Outputs all keys and values in the table.
[`LookupTableFind(...)`](../../raw_ops/lookuptablefind): Looks up keys in a table, outputs the corresponding values.
[`LookupTableFindV2(...)`](../../raw_ops/lookuptablefindv2): Looks up keys in a table, outputs the corresponding values.
[`LookupTableImport(...)`](../../raw_ops/lookuptableimport): Replaces the contents of the table with the specified keys and values.
[`LookupTableImportV2(...)`](../../raw_ops/lookuptableimportv2): Replaces the contents of the table with the specified keys and values.
[`LookupTableInsert(...)`](../../raw_ops/lookuptableinsert): Updates the table to associates keys with values.
[`LookupTableInsertV2(...)`](../../raw_ops/lookuptableinsertv2): Updates the table to associates keys with values.
[`LookupTableRemoveV2(...)`](../../raw_ops/lookuptableremovev2): Removes keys and its associated values from a table.
[`LookupTableSize(...)`](../../raw_ops/lookuptablesize): Computes the number of elements in the given table.
[`LookupTableSizeV2(...)`](../../raw_ops/lookuptablesizev2): Computes the number of elements in the given table.
[`LoopCond(...)`](../../raw_ops/loopcond): Forwards the input to the output.
[`LowerBound(...)`](../../raw_ops/lowerbound): Applies lower\_bound(sorted\_search\_values, values) along each row.
[`Lu(...)`](../../raw_ops/lu): Computes the LU decomposition of one or more square matrices.
[`MakeIterator(...)`](../../raw_ops/makeiterator): Makes a new iterator from the given `dataset` and stores it in `iterator`.
[`MapAndBatchDataset(...)`](../../raw_ops/mapandbatchdataset): Creates a dataset that fuses mapping with batching.
[`MapClear(...)`](../../raw_ops/mapclear): Op removes all elements in the underlying container.
[`MapDataset(...)`](../../raw_ops/mapdataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`MapDefun(...)`](../../raw_ops/mapdefun): Maps a function on the list of tensors unpacked from arguments on dimension 0.
[`MapIncompleteSize(...)`](../../raw_ops/mapincompletesize): Op returns the number of incomplete elements in the underlying container.
[`MapPeek(...)`](../../raw_ops/mappeek): Op peeks at the values at the specified key. If the
[`MapSize(...)`](../../raw_ops/mapsize): Op returns the number of elements in the underlying container.
[`MapStage(...)`](../../raw_ops/mapstage): Stage (key, values) in the underlying container which behaves like a hashtable.
[`MapUnstage(...)`](../../raw_ops/mapunstage): Op removes and returns the values associated with the key
[`MapUnstageNoKey(...)`](../../raw_ops/mapunstagenokey): Op removes and returns a random (key, value)
[`MatMul(...)`](../../raw_ops/matmul): Multiply the matrix "a" by the matrix "b".
[`MatchingFiles(...)`](../../raw_ops/matchingfiles): Returns the set of files matching one or more glob patterns.
[`MatchingFilesDataset(...)`](../../raw_ops/matchingfilesdataset)
[`MatrixBandPart(...)`](../../raw_ops/matrixbandpart): Copy a tensor setting everything outside a central band in each innermost matrix to zero.
[`MatrixDeterminant(...)`](../../raw_ops/matrixdeterminant): Computes the determinant of one or more square matrices.
[`MatrixDiag(...)`](../../raw_ops/matrixdiag): Returns a batched diagonal tensor with a given batched diagonal values.
[`MatrixDiagPart(...)`](../../raw_ops/matrixdiagpart): Returns the batched diagonal part of a batched tensor.
[`MatrixDiagPartV2(...)`](../../raw_ops/matrixdiagpartv2): Returns the batched diagonal part of a batched tensor.
[`MatrixDiagPartV3(...)`](../../raw_ops/matrixdiagpartv3): Returns the batched diagonal part of a batched tensor.
[`MatrixDiagV2(...)`](../../raw_ops/matrixdiagv2): Returns a batched diagonal tensor with given batched diagonal values.
[`MatrixDiagV3(...)`](../../raw_ops/matrixdiagv3): Returns a batched diagonal tensor with given batched diagonal values.
[`MatrixExponential(...)`](../../raw_ops/matrixexponential): Deprecated, use python implementation tf.linalg.matrix\_exponential.
[`MatrixInverse(...)`](../../raw_ops/matrixinverse): Computes the inverse of one or more square invertible matrices or their adjoints (conjugate transposes).
[`MatrixLogarithm(...)`](../../raw_ops/matrixlogarithm): Computes the matrix logarithm of one or more square matrices:
[`MatrixSetDiag(...)`](../../raw_ops/matrixsetdiag): Returns a batched matrix tensor with new batched diagonal values.
[`MatrixSetDiagV2(...)`](../../raw_ops/matrixsetdiagv2): Returns a batched matrix tensor with new batched diagonal values.
[`MatrixSetDiagV3(...)`](../../raw_ops/matrixsetdiagv3): Returns a batched matrix tensor with new batched diagonal values.
[`MatrixSolve(...)`](../../raw_ops/matrixsolve): Solves systems of linear equations.
[`MatrixSolveLs(...)`](../../raw_ops/matrixsolvels): Solves one or more linear least-squares problems.
[`MatrixSquareRoot(...)`](../../raw_ops/matrixsquareroot): Computes the matrix square root of one or more square matrices:
[`MatrixTriangularSolve(...)`](../../raw_ops/matrixtriangularsolve): Solves systems of linear equations with upper or lower triangular matrices by backsubstitution.
[`Max(...)`](../../raw_ops/max): Computes the maximum of elements across dimensions of a tensor.
[`MaxIntraOpParallelismDataset(...)`](../../raw_ops/maxintraopparallelismdataset): Creates a dataset that overrides the maximum intra-op parallelism.
[`MaxPool(...)`](../../raw_ops/maxpool): Performs max pooling on the input.
[`MaxPool3D(...)`](../../raw_ops/maxpool3d): Performs 3D max pooling on the input.
[`MaxPool3DGrad(...)`](../../raw_ops/maxpool3dgrad): Computes gradients of 3D max pooling function.
[`MaxPool3DGradGrad(...)`](../../raw_ops/maxpool3dgradgrad): Computes second-order gradients of the maxpooling function.
[`MaxPoolGrad(...)`](../../raw_ops/maxpoolgrad): Computes gradients of the maxpooling function.
[`MaxPoolGradGrad(...)`](../../raw_ops/maxpoolgradgrad): Computes second-order gradients of the maxpooling function.
[`MaxPoolGradGradV2(...)`](../../raw_ops/maxpoolgradgradv2): Computes second-order gradients of the maxpooling function.
[`MaxPoolGradGradWithArgmax(...)`](../../raw_ops/maxpoolgradgradwithargmax): Computes second-order gradients of the maxpooling function.
[`MaxPoolGradV2(...)`](../../raw_ops/maxpoolgradv2): Computes gradients of the maxpooling function.
[`MaxPoolGradWithArgmax(...)`](../../raw_ops/maxpoolgradwithargmax): Computes gradients of the maxpooling function.
[`MaxPoolV2(...)`](../../raw_ops/maxpoolv2): Performs max pooling on the input.
[`MaxPoolWithArgmax(...)`](../../raw_ops/maxpoolwithargmax): Performs max pooling on the input and outputs both max values and indices.
[`Maximum(...)`](../../raw_ops/maximum): Returns the max of x and y (i.e. x > y ? x : y) element-wise.
[`Mean(...)`](../../raw_ops/mean): Computes the mean of elements across dimensions of a tensor.
[`Merge(...)`](../../raw_ops/merge): Forwards the value of an available tensor from `inputs` to `output`.
[`MergeSummary(...)`](../../raw_ops/mergesummary): Merges summaries.
[`MergeV2Checkpoints(...)`](../../raw_ops/mergev2checkpoints): V2 format specific: merges the metadata files of sharded checkpoints. The
[`Mfcc(...)`](../../raw_ops/mfcc): Transforms a spectrogram into a form that's useful for speech recognition.
[`Min(...)`](../../raw_ops/min): Computes the minimum of elements across dimensions of a tensor.
[`Minimum(...)`](../../raw_ops/minimum): Returns the min of x and y (i.e. x < y ? x : y) element-wise.
[`MirrorPad(...)`](../../raw_ops/mirrorpad): Pads a tensor with mirrored values.
[`MirrorPadGrad(...)`](../../raw_ops/mirrorpadgrad): Gradient op for `MirrorPad` op. This op folds a mirror-padded tensor.
[`Mod(...)`](../../raw_ops/mod): Returns element-wise remainder of division. This emulates C semantics in that
[`ModelDataset(...)`](../../raw_ops/modeldataset): Identity transformation that models performance.
[`Mul(...)`](../../raw_ops/mul): Returns x \* y element-wise.
[`MulNoNan(...)`](../../raw_ops/mulnonan): Returns x \* y element-wise. Returns zero if y is zero, even if x if infinite or NaN.
[`MultiDeviceIterator(...)`](../../raw_ops/multideviceiterator): Creates a MultiDeviceIterator resource.
[`MultiDeviceIteratorFromStringHandle(...)`](../../raw_ops/multideviceiteratorfromstringhandle): Generates a MultiDeviceIterator resource from its provided string handle.
[`MultiDeviceIteratorGetNextFromShard(...)`](../../raw_ops/multideviceiteratorgetnextfromshard): Gets next element for the provided shard number.
[`MultiDeviceIteratorInit(...)`](../../raw_ops/multideviceiteratorinit): Initializes the multi device iterator with the given dataset.
[`MultiDeviceIteratorToStringHandle(...)`](../../raw_ops/multideviceiteratortostringhandle): Produces a string handle for the given MultiDeviceIterator.
[`Multinomial(...)`](../../raw_ops/multinomial): Draws samples from a multinomial distribution.
[`MutableDenseHashTable(...)`](../../raw_ops/mutabledensehashtable): Creates an empty hash table that uses tensors as the backing store.
[`MutableDenseHashTableV2(...)`](../../raw_ops/mutabledensehashtablev2): Creates an empty hash table that uses tensors as the backing store.
[`MutableHashTable(...)`](../../raw_ops/mutablehashtable): Creates an empty hash table.
[`MutableHashTableOfTensors(...)`](../../raw_ops/mutablehashtableoftensors): Creates an empty hash table.
[`MutableHashTableOfTensorsV2(...)`](../../raw_ops/mutablehashtableoftensorsv2): Creates an empty hash table.
[`MutableHashTableV2(...)`](../../raw_ops/mutablehashtablev2): Creates an empty hash table.
[`MutexLock(...)`](../../raw_ops/mutexlock): Locks a mutex resource. The output is the lock. So long as the lock tensor
[`MutexV2(...)`](../../raw_ops/mutexv2): Creates a Mutex resource that can be locked by `MutexLock`.
[`NcclAllReduce(...)`](../../raw_ops/ncclallreduce): Outputs a tensor containing the reduction across all input tensors.
[`NcclBroadcast(...)`](../../raw_ops/ncclbroadcast): Sends `input` to all devices that are connected to the output.
[`NcclReduce(...)`](../../raw_ops/ncclreduce): Reduces `input` from `num_devices` using `reduction` to a single device.
[`Ndtri(...)`](../../raw_ops/ndtri)
[`Neg(...)`](../../raw_ops/neg): Computes numerical negative value element-wise.
[`NextAfter(...)`](../../raw_ops/nextafter): Returns the next representable value of `x1` in the direction of `x2`, element-wise.
[`NextIteration(...)`](../../raw_ops/nextiteration): Makes its input available to the next iteration.
[`NoOp(...)`](../../raw_ops/noop): Does nothing. Only useful as a placeholder for control edges.
[`NonDeterministicInts(...)`](../../raw_ops/nondeterministicints): Non-deterministically generates some integers.
[`NonMaxSuppression(...)`](../../raw_ops/nonmaxsuppression): Greedily selects a subset of bounding boxes in descending order of score,
[`NonMaxSuppressionV2(...)`](../../raw_ops/nonmaxsuppressionv2): Greedily selects a subset of bounding boxes in descending order of score,
[`NonMaxSuppressionV3(...)`](../../raw_ops/nonmaxsuppressionv3): Greedily selects a subset of bounding boxes in descending order of score,
[`NonMaxSuppressionV4(...)`](../../raw_ops/nonmaxsuppressionv4): Greedily selects a subset of bounding boxes in descending order of score,
[`NonMaxSuppressionV5(...)`](../../raw_ops/nonmaxsuppressionv5): Greedily selects a subset of bounding boxes in descending order of score,
[`NonMaxSuppressionWithOverlaps(...)`](../../raw_ops/nonmaxsuppressionwithoverlaps): Greedily selects a subset of bounding boxes in descending order of score,
[`NonSerializableDataset(...)`](../../raw_ops/nonserializabledataset)
[`NotEqual(...)`](../../raw_ops/notequal): Returns the truth value of (x != y) element-wise.
[`NthElement(...)`](../../raw_ops/nthelement): Finds values of the `n`-th order statistic for the last dimension.
[`OneHot(...)`](../../raw_ops/onehot): Returns a one-hot tensor.
[`OneShotIterator(...)`](../../raw_ops/oneshotiterator): Makes a "one-shot" iterator that can be iterated only once.
[`OnesLike(...)`](../../raw_ops/oneslike): Returns a tensor of ones with the same shape and type as x.
[`OptimizeDataset(...)`](../../raw_ops/optimizedataset): Creates a dataset by applying optimizations to `input_dataset`.
[`OptimizeDatasetV2(...)`](../../raw_ops/optimizedatasetv2): Creates a dataset by applying related optimizations to `input_dataset`.
[`OptionalFromValue(...)`](../../raw_ops/optionalfromvalue): Constructs an Optional variant from a tuple of tensors.
[`OptionalGetValue(...)`](../../raw_ops/optionalgetvalue): Returns the value stored in an Optional variant or raises an error if none exists.
[`OptionalHasValue(...)`](../../raw_ops/optionalhasvalue): Returns true if and only if the given Optional variant has a value.
[`OptionalNone(...)`](../../raw_ops/optionalnone): Creates an Optional variant with no value.
[`OptionsDataset(...)`](../../raw_ops/optionsdataset): Creates a dataset by attaching tf.data.Options to `input_dataset`.
[`OrderedMapClear(...)`](../../raw_ops/orderedmapclear): Op removes all elements in the underlying container.
[`OrderedMapIncompleteSize(...)`](../../raw_ops/orderedmapincompletesize): Op returns the number of incomplete elements in the underlying container.
[`OrderedMapPeek(...)`](../../raw_ops/orderedmappeek): Op peeks at the values at the specified key. If the
[`OrderedMapSize(...)`](../../raw_ops/orderedmapsize): Op returns the number of elements in the underlying container.
[`OrderedMapStage(...)`](../../raw_ops/orderedmapstage): Stage (key, values) in the underlying container which behaves like a ordered
[`OrderedMapUnstage(...)`](../../raw_ops/orderedmapunstage): Op removes and returns the values associated with the key
[`OrderedMapUnstageNoKey(...)`](../../raw_ops/orderedmapunstagenokey): Op removes and returns the (key, value) element with the smallest
[`OutfeedDequeue(...)`](../../raw_ops/outfeeddequeue): Retrieves a single tensor from the computation outfeed.
[`OutfeedDequeueTuple(...)`](../../raw_ops/outfeeddequeuetuple): Retrieve multiple values from the computation outfeed.
[`OutfeedDequeueTupleV2(...)`](../../raw_ops/outfeeddequeuetuplev2): Retrieve multiple values from the computation outfeed. Device ordinal is a
[`OutfeedDequeueV2(...)`](../../raw_ops/outfeeddequeuev2): Retrieves a single tensor from the computation outfeed. Device ordinal is a
[`OutfeedEnqueue(...)`](../../raw_ops/outfeedenqueue): Enqueue a Tensor on the computation outfeed.
[`OutfeedEnqueueTuple(...)`](../../raw_ops/outfeedenqueuetuple): Enqueue multiple Tensor values on the computation outfeed.
[`Pack(...)`](../../raw_ops/pack): Packs a list of `N` rank-`R` tensors into one rank-`(R+1)` tensor.
[`Pad(...)`](../../raw_ops/pad): Pads a tensor with zeros.
[`PadV2(...)`](../../raw_ops/padv2): Pads a tensor.
[`PaddedBatchDataset(...)`](../../raw_ops/paddedbatchdataset): Creates a dataset that batches and pads `batch_size` elements from the input.
[`PaddedBatchDatasetV2(...)`](../../raw_ops/paddedbatchdatasetv2): Creates a dataset that batches and pads `batch_size` elements from the input.
[`PaddingFIFOQueue(...)`](../../raw_ops/paddingfifoqueue): A queue that produces elements in first-in first-out order.
[`PaddingFIFOQueueV2(...)`](../../raw_ops/paddingfifoqueuev2): A queue that produces elements in first-in first-out order.
[`ParallelBatchDataset(...)`](../../raw_ops/parallelbatchdataset)
[`ParallelConcat(...)`](../../raw_ops/parallelconcat): Concatenates a list of `N` tensors along the first dimension.
[`ParallelDynamicStitch(...)`](../../raw_ops/paralleldynamicstitch): Interleave the values from the `data` tensors into a single tensor.
[`ParallelFilterDataset(...)`](../../raw_ops/parallelfilterdataset): Creates a dataset containing elements of `input_dataset` matching `predicate`.
[`ParallelInterleaveDataset(...)`](../../raw_ops/parallelinterleavedataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParallelInterleaveDatasetV2(...)`](../../raw_ops/parallelinterleavedatasetv2): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParallelInterleaveDatasetV3(...)`](../../raw_ops/parallelinterleavedatasetv3): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParallelInterleaveDatasetV4(...)`](../../raw_ops/parallelinterleavedatasetv4): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParallelMapDataset(...)`](../../raw_ops/parallelmapdataset): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParallelMapDatasetV2(...)`](../../raw_ops/parallelmapdatasetv2): Creates a dataset that applies `f` to the outputs of `input_dataset`.
[`ParameterizedTruncatedNormal(...)`](../../raw_ops/parameterizedtruncatednormal): Outputs random values from a normal distribution. The parameters may each be a
[`ParseExample(...)`](../../raw_ops/parseexample): Transforms a vector of brain.Example protos (as strings) into typed tensors.
[`ParseExampleDataset(...)`](../../raw_ops/parseexampledataset): Transforms `input_dataset` containing `Example` protos as vectors of DT\_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features.
[`ParseExampleDatasetV2(...)`](../../raw_ops/parseexampledatasetv2): Transforms `input_dataset` containing `Example` protos as vectors of DT\_STRING into a dataset of `Tensor` or `SparseTensor` objects representing the parsed features.
[`ParseExampleV2(...)`](../../raw_ops/parseexamplev2): Transforms a vector of tf.Example protos (as strings) into typed tensors.
[`ParseSequenceExample(...)`](../../raw_ops/parsesequenceexample): Transforms a vector of brain.SequenceExample protos (as strings) into typed tensors.
[`ParseSequenceExampleV2(...)`](../../raw_ops/parsesequenceexamplev2): Transforms a vector of tf.io.SequenceExample protos (as strings) into
[`ParseSingleExample(...)`](../../raw_ops/parsesingleexample): Transforms a tf.Example proto (as a string) into typed tensors.
[`ParseSingleSequenceExample(...)`](../../raw_ops/parsesinglesequenceexample): Transforms a scalar brain.SequenceExample proto (as strings) into typed tensors.
[`ParseTensor(...)`](../../raw_ops/parsetensor): Transforms a serialized tensorflow.TensorProto proto into a Tensor.
[`PartitionedCall(...)`](../../raw_ops/partitionedcall): returns `f(inputs)`, where `f`'s body is placed and partitioned.
[`Placeholder(...)`](../../raw_ops/placeholder): A placeholder op for a value that will be fed into the computation.
[`PlaceholderV2(...)`](../../raw_ops/placeholderv2): A placeholder op for a value that will be fed into the computation.
[`PlaceholderWithDefault(...)`](../../raw_ops/placeholderwithdefault): A placeholder op that passes through `input` when its output is not fed.
[`Polygamma(...)`](../../raw_ops/polygamma): Compute the polygamma function \(\psi^{(n)}(x)\).
[`PopulationCount(...)`](../../raw_ops/populationcount): Computes element-wise population count (a.k.a. popcount, bitsum, bitcount).
[`Pow(...)`](../../raw_ops/pow): Computes the power of one value to another.
[`PrefetchDataset(...)`](../../raw_ops/prefetchdataset): Creates a dataset that asynchronously prefetches elements from `input_dataset`.
[`Prelinearize(...)`](../../raw_ops/prelinearize): An op which linearizes one Tensor value to an opaque variant tensor.
[`PrelinearizeTuple(...)`](../../raw_ops/prelinearizetuple): An op which linearizes multiple Tensor values to an opaque variant tensor.
[`PreventGradient(...)`](../../raw_ops/preventgradient): An identity op that triggers an error if a gradient is requested.
[`Print(...)`](../../raw_ops/print): Prints a list of tensors.
[`PrintV2(...)`](../../raw_ops/printv2): Prints a string scalar.
[`PriorityQueue(...)`](../../raw_ops/priorityqueue): A queue that produces elements sorted by the first component value.
[`PriorityQueueV2(...)`](../../raw_ops/priorityqueuev2): A queue that produces elements sorted by the first component value.
[`PrivateThreadPoolDataset(...)`](../../raw_ops/privatethreadpooldataset): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`Prod(...)`](../../raw_ops/prod): Computes the product of elements across dimensions of a tensor.
[`PyFunc(...)`](../../raw_ops/pyfunc): Invokes a python function to compute func(input)->output.
[`PyFuncStateless(...)`](../../raw_ops/pyfuncstateless): A stateless version of PyFunc.
[`Qr(...)`](../../raw_ops/qr): Computes the QR decompositions of one or more matrices.
[`QuantizeAndDequantize(...)`](../../raw_ops/quantizeanddequantize): Use QuantizeAndDequantizeV2 instead.
[`QuantizeAndDequantizeV2(...)`](../../raw_ops/quantizeanddequantizev2): Quantizes then dequantizes a tensor.
[`QuantizeAndDequantizeV3(...)`](../../raw_ops/quantizeanddequantizev3): Quantizes then dequantizes a tensor.
[`QuantizeAndDequantizeV4(...)`](../../raw_ops/quantizeanddequantizev4): Quantizes then dequantizes a tensor.
[`QuantizeAndDequantizeV4Grad(...)`](../../raw_ops/quantizeanddequantizev4grad): Returns the gradient of `QuantizeAndDequantizeV4`.
[`QuantizeDownAndShrinkRange(...)`](../../raw_ops/quantizedownandshrinkrange): Convert the quantized 'input' tensor into a lower-precision 'output', using the
[`QuantizeV2(...)`](../../raw_ops/quantizev2): Quantize the 'input' tensor of type float to 'output' tensor of type 'T'.
[`QuantizedAdd(...)`](../../raw_ops/quantizedadd): Returns x + y element-wise, working on quantized buffers.
[`QuantizedAvgPool(...)`](../../raw_ops/quantizedavgpool): Produces the average pool of the input tensor for quantized types.
[`QuantizedBatchNormWithGlobalNormalization(...)`](../../raw_ops/quantizedbatchnormwithglobalnormalization): Quantized Batch normalization.
[`QuantizedBiasAdd(...)`](../../raw_ops/quantizedbiasadd): Adds Tensor 'bias' to Tensor 'input' for Quantized types.
[`QuantizedConcat(...)`](../../raw_ops/quantizedconcat): Concatenates quantized tensors along one dimension.
[`QuantizedConv2D(...)`](../../raw_ops/quantizedconv2d): Computes a 2D convolution given quantized 4D input and filter tensors.
[`QuantizedConv2DAndRelu(...)`](../../raw_ops/quantizedconv2dandrelu)
[`QuantizedConv2DAndReluAndRequantize(...)`](../../raw_ops/quantizedconv2dandreluandrequantize)
[`QuantizedConv2DAndRequantize(...)`](../../raw_ops/quantizedconv2dandrequantize)
[`QuantizedConv2DPerChannel(...)`](../../raw_ops/quantizedconv2dperchannel): Computes QuantizedConv2D per channel.
[`QuantizedConv2DWithBias(...)`](../../raw_ops/quantizedconv2dwithbias)
[`QuantizedConv2DWithBiasAndRelu(...)`](../../raw_ops/quantizedconv2dwithbiasandrelu)
[`QuantizedConv2DWithBiasAndReluAndRequantize(...)`](../../raw_ops/quantizedconv2dwithbiasandreluandrequantize)
[`QuantizedConv2DWithBiasAndRequantize(...)`](../../raw_ops/quantizedconv2dwithbiasandrequantize)
[`QuantizedConv2DWithBiasSignedSumAndReluAndRequantize(...)`](../../raw_ops/quantizedconv2dwithbiassignedsumandreluandrequantize)
[`QuantizedConv2DWithBiasSumAndRelu(...)`](../../raw_ops/quantizedconv2dwithbiassumandrelu)
[`QuantizedConv2DWithBiasSumAndReluAndRequantize(...)`](../../raw_ops/quantizedconv2dwithbiassumandreluandrequantize)
[`QuantizedDepthwiseConv2D(...)`](../../raw_ops/quantizeddepthwiseconv2d): Computes quantized depthwise Conv2D.
[`QuantizedDepthwiseConv2DWithBias(...)`](../../raw_ops/quantizeddepthwiseconv2dwithbias): Computes quantized depthwise Conv2D with Bias.
[`QuantizedDepthwiseConv2DWithBiasAndRelu(...)`](../../raw_ops/quantizeddepthwiseconv2dwithbiasandrelu): Computes quantized depthwise Conv2D with Bias and Relu.
[`QuantizedDepthwiseConv2DWithBiasAndReluAndRequantize(...)`](../../raw_ops/quantizeddepthwiseconv2dwithbiasandreluandrequantize): Computes quantized depthwise Conv2D with Bias, Relu and Requantize.
[`QuantizedInstanceNorm(...)`](../../raw_ops/quantizedinstancenorm): Quantized Instance normalization.
[`QuantizedMatMul(...)`](../../raw_ops/quantizedmatmul): Perform a quantized matrix multiplication of `a` by the matrix `b`.
[`QuantizedMatMulWithBias(...)`](../../raw_ops/quantizedmatmulwithbias): Performs a quantized matrix multiplication of `a` by the matrix `b` with bias
[`QuantizedMatMulWithBiasAndDequantize(...)`](../../raw_ops/quantizedmatmulwithbiasanddequantize)
[`QuantizedMatMulWithBiasAndRelu(...)`](../../raw_ops/quantizedmatmulwithbiasandrelu): Perform a quantized matrix multiplication of `a` by the matrix `b` with bias
[`QuantizedMatMulWithBiasAndReluAndRequantize(...)`](../../raw_ops/quantizedmatmulwithbiasandreluandrequantize): Perform a quantized matrix multiplication of `a` by the matrix `b` with bias
[`QuantizedMatMulWithBiasAndRequantize(...)`](../../raw_ops/quantizedmatmulwithbiasandrequantize)
[`QuantizedMaxPool(...)`](../../raw_ops/quantizedmaxpool): Produces the max pool of the input tensor for quantized types.
[`QuantizedMul(...)`](../../raw_ops/quantizedmul): Returns x \* y element-wise, working on quantized buffers.
[`QuantizedRelu(...)`](../../raw_ops/quantizedrelu): Computes Quantized Rectified Linear: `max(features, 0)`
[`QuantizedRelu6(...)`](../../raw_ops/quantizedrelu6): Computes Quantized Rectified Linear 6: `min(max(features, 0), 6)`
[`QuantizedReluX(...)`](../../raw_ops/quantizedrelux): Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)`
[`QuantizedReshape(...)`](../../raw_ops/quantizedreshape): Reshapes a quantized tensor as per the Reshape op.
[`QuantizedResizeBilinear(...)`](../../raw_ops/quantizedresizebilinear): Resize quantized `images` to `size` using quantized bilinear interpolation.
[`QueueClose(...)`](../../raw_ops/queueclose): Closes the given queue.
[`QueueCloseV2(...)`](../../raw_ops/queueclosev2): Closes the given queue.
[`QueueDequeue(...)`](../../raw_ops/queuedequeue): Dequeues a tuple of one or more tensors from the given queue.
[`QueueDequeueMany(...)`](../../raw_ops/queuedequeuemany): Dequeues `n` tuples of one or more tensors from the given queue.
[`QueueDequeueManyV2(...)`](../../raw_ops/queuedequeuemanyv2): Dequeues `n` tuples of one or more tensors from the given queue.
[`QueueDequeueUpTo(...)`](../../raw_ops/queuedequeueupto): Dequeues `n` tuples of one or more tensors from the given queue.
[`QueueDequeueUpToV2(...)`](../../raw_ops/queuedequeueuptov2): Dequeues `n` tuples of one or more tensors from the given queue.
[`QueueDequeueV2(...)`](../../raw_ops/queuedequeuev2): Dequeues a tuple of one or more tensors from the given queue.
[`QueueEnqueue(...)`](../../raw_ops/queueenqueue): Enqueues a tuple of one or more tensors in the given queue.
[`QueueEnqueueMany(...)`](../../raw_ops/queueenqueuemany): Enqueues zero or more tuples of one or more tensors in the given queue.
[`QueueEnqueueManyV2(...)`](../../raw_ops/queueenqueuemanyv2): Enqueues zero or more tuples of one or more tensors in the given queue.
[`QueueEnqueueV2(...)`](../../raw_ops/queueenqueuev2): Enqueues a tuple of one or more tensors in the given queue.
[`QueueIsClosed(...)`](../../raw_ops/queueisclosed): Returns true if queue is closed.
[`QueueIsClosedV2(...)`](../../raw_ops/queueisclosedv2): Returns true if queue is closed.
[`QueueSize(...)`](../../raw_ops/queuesize): Computes the number of elements in the given queue.
[`QueueSizeV2(...)`](../../raw_ops/queuesizev2): Computes the number of elements in the given queue.
[`RFFT(...)`](../../raw_ops/rfft): Real-valued fast Fourier transform.
[`RFFT2D(...)`](../../raw_ops/rfft2d): 2D real-valued fast Fourier transform.
[`RFFT3D(...)`](../../raw_ops/rfft3d): 3D real-valued fast Fourier transform.
[`RGBToHSV(...)`](../../raw_ops/rgbtohsv): Converts one or more images from RGB to HSV.
[`RaggedBincount(...)`](../../raw_ops/raggedbincount): Counts the number of occurrences of each value in an integer array.
[`RaggedCountSparseOutput(...)`](../../raw_ops/raggedcountsparseoutput): Performs sparse-output bin counting for a ragged tensor input.
[`RaggedCross(...)`](../../raw_ops/raggedcross): Generates a feature cross from a list of tensors, and returns it as a
[`RaggedGather(...)`](../../raw_ops/raggedgather): Gather ragged slices from `params` axis `0` according to `indices`.
[`RaggedRange(...)`](../../raw_ops/raggedrange): Returns a `RaggedTensor` containing the specified sequences of numbers.
[`RaggedTensorFromVariant(...)`](../../raw_ops/raggedtensorfromvariant): Decodes a `variant` Tensor into a `RaggedTensor`.
[`RaggedTensorToSparse(...)`](../../raw_ops/raggedtensortosparse): Converts a `RaggedTensor` into a `SparseTensor` with the same values.
[`RaggedTensorToTensor(...)`](../../raw_ops/raggedtensortotensor): Create a dense tensor from a ragged tensor, possibly altering its shape.
[`RaggedTensorToVariant(...)`](../../raw_ops/raggedtensortovariant): Encodes a `RaggedTensor` into a `variant` Tensor.
[`RaggedTensorToVariantGradient(...)`](../../raw_ops/raggedtensortovariantgradient): Helper used to compute the gradient for `RaggedTensorToVariant`.
[`RandomCrop(...)`](../../raw_ops/randomcrop): Randomly crop `image`.
[`RandomDataset(...)`](../../raw_ops/randomdataset): Creates a Dataset that returns pseudorandom numbers.
[`RandomGamma(...)`](../../raw_ops/randomgamma): Outputs random values from the Gamma distribution(s) described by alpha.
[`RandomGammaGrad(...)`](../../raw_ops/randomgammagrad): Computes the derivative of a Gamma random sample w.r.t. `alpha`.
[`RandomIndexShuffle(...)`](../../raw_ops/randomindexshuffle): Outputs the position of `value` in a permutation of [0, ..., max\_index].
[`RandomPoisson(...)`](../../raw_ops/randompoisson): Use RandomPoissonV2 instead.
[`RandomPoissonV2(...)`](../../raw_ops/randompoissonv2): Outputs random values from the Poisson distribution(s) described by rate.
[`RandomShuffle(...)`](../../raw_ops/randomshuffle): Randomly shuffles a tensor along its first dimension.
[`RandomShuffleQueue(...)`](../../raw_ops/randomshufflequeue): A queue that randomizes the order of elements.
[`RandomShuffleQueueV2(...)`](../../raw_ops/randomshufflequeuev2): A queue that randomizes the order of elements.
[`RandomStandardNormal(...)`](../../raw_ops/randomstandardnormal): Outputs random values from a normal distribution.
[`RandomUniform(...)`](../../raw_ops/randomuniform): Outputs random values from a uniform distribution.
[`RandomUniformInt(...)`](../../raw_ops/randomuniformint): Outputs random integers from a uniform distribution.
[`Range(...)`](../../raw_ops/range): Creates a sequence of numbers.
[`RangeDataset(...)`](../../raw_ops/rangedataset): Creates a dataset with a range of values. Corresponds to python's xrange.
[`Rank(...)`](../../raw_ops/rank): Returns the rank of a tensor.
[`ReadFile(...)`](../../raw_ops/readfile): Reads and outputs the entire contents of the input filename.
[`ReadVariableOp(...)`](../../raw_ops/readvariableop): Reads the value of a variable.
[`ReadVariableXlaSplitND(...)`](../../raw_ops/readvariablexlasplitnd): Splits resource variable input tensor across all dimensions.
[`ReaderNumRecordsProduced(...)`](../../raw_ops/readernumrecordsproduced): Returns the number of records this Reader has produced.
[`ReaderNumRecordsProducedV2(...)`](../../raw_ops/readernumrecordsproducedv2): Returns the number of records this Reader has produced.
[`ReaderNumWorkUnitsCompleted(...)`](../../raw_ops/readernumworkunitscompleted): Returns the number of work units this Reader has finished processing.
[`ReaderNumWorkUnitsCompletedV2(...)`](../../raw_ops/readernumworkunitscompletedv2): Returns the number of work units this Reader has finished processing.
[`ReaderRead(...)`](../../raw_ops/readerread): Returns the next record (key, value pair) produced by a Reader.
[`ReaderReadUpTo(...)`](../../raw_ops/readerreadupto): Returns up to `num_records` (key, value) pairs produced by a Reader.
[`ReaderReadUpToV2(...)`](../../raw_ops/readerreaduptov2): Returns up to `num_records` (key, value) pairs produced by a Reader.
[`ReaderReadV2(...)`](../../raw_ops/readerreadv2): Returns the next record (key, value pair) produced by a Reader.
[`ReaderReset(...)`](../../raw_ops/readerreset): Restore a Reader to its initial clean state.
[`ReaderResetV2(...)`](../../raw_ops/readerresetv2): Restore a Reader to its initial clean state.
[`ReaderRestoreState(...)`](../../raw_ops/readerrestorestate): Restore a reader to a previously saved state.
[`ReaderRestoreStateV2(...)`](../../raw_ops/readerrestorestatev2): Restore a reader to a previously saved state.
[`ReaderSerializeState(...)`](../../raw_ops/readerserializestate): Produce a string tensor that encodes the state of a Reader.
[`ReaderSerializeStateV2(...)`](../../raw_ops/readerserializestatev2): Produce a string tensor that encodes the state of a Reader.
[`Real(...)`](../../raw_ops/real): Returns the real part of a complex number.
[`RealDiv(...)`](../../raw_ops/realdiv): Returns x / y element-wise for real types.
[`RebatchDataset(...)`](../../raw_ops/rebatchdataset): Creates a dataset that changes the batch size.
[`RebatchDatasetV2(...)`](../../raw_ops/rebatchdatasetv2): Creates a dataset that changes the batch size.
[`Reciprocal(...)`](../../raw_ops/reciprocal): Computes the reciprocal of x element-wise.
[`ReciprocalGrad(...)`](../../raw_ops/reciprocalgrad): Computes the gradient for the inverse of `x` wrt its input.
[`RecordInput(...)`](../../raw_ops/recordinput): Emits randomized records.
[`Recv(...)`](../../raw_ops/recv): Receives the named tensor from send\_device on recv\_device.
[`RecvTPUEmbeddingActivations(...)`](../../raw_ops/recvtpuembeddingactivations): An op that receives embedding activations on the TPU.
[`ReduceDataset(...)`](../../raw_ops/reducedataset): Reduces the input dataset to a singleton using a reduce function.
[`ReduceJoin(...)`](../../raw_ops/reducejoin): Joins a string Tensor across the given dimensions.
[`RefEnter(...)`](../../raw_ops/refenter): Creates or finds a child frame, and makes `data` available to the child frame.
[`RefExit(...)`](../../raw_ops/refexit): Exits the current frame to its parent frame.
[`RefIdentity(...)`](../../raw_ops/refidentity): Return the same ref tensor as the input ref tensor.
[`RefMerge(...)`](../../raw_ops/refmerge): Forwards the value of an available tensor from `inputs` to `output`.
[`RefNextIteration(...)`](../../raw_ops/refnextiteration): Makes its input available to the next iteration.
[`RefSelect(...)`](../../raw_ops/refselect): Forwards the `index`th element of `inputs` to `output`.
[`RefSwitch(...)`](../../raw_ops/refswitch): Forwards the ref tensor `data` to the output port determined by `pred`.
[`RegexFullMatch(...)`](../../raw_ops/regexfullmatch): Check if the input matches the regex pattern.
[`RegexReplace(...)`](../../raw_ops/regexreplace): Replaces matches of the `pattern` regular expression in `input` with the
[`RegisterDataset(...)`](../../raw_ops/registerdataset): Registers a dataset with the tf.data service.
[`Relu(...)`](../../raw_ops/relu): Computes rectified linear: `max(features, 0)`.
[`Relu6(...)`](../../raw_ops/relu6): Computes rectified linear 6: `min(max(features, 0), 6)`.
[`Relu6Grad(...)`](../../raw_ops/relu6grad): Computes rectified linear 6 gradients for a Relu6 operation.
[`ReluGrad(...)`](../../raw_ops/relugrad): Computes rectified linear gradients for a Relu operation.
[`RemoteCall(...)`](../../raw_ops/remotecall): Runs function `f` on a remote device indicated by `target`.
[`RepeatDataset(...)`](../../raw_ops/repeatdataset): Creates a dataset that emits the outputs of `input_dataset` `count` times.
[`RequantizationRange(...)`](../../raw_ops/requantizationrange): Computes a range that covers the actual values present in a quantized tensor.
[`RequantizationRangePerChannel(...)`](../../raw_ops/requantizationrangeperchannel): Computes requantization range per channel.
[`Requantize(...)`](../../raw_ops/requantize): Converts the quantized `input` tensor into a lower-precision `output`.
[`RequantizePerChannel(...)`](../../raw_ops/requantizeperchannel): Requantizes input with min and max values known per channel.
[`Reshape(...)`](../../raw_ops/reshape): Reshapes a tensor.
[`ResizeArea(...)`](../../raw_ops/resizearea): Resize `images` to `size` using area interpolation.
[`ResizeBicubic(...)`](../../raw_ops/resizebicubic): Resize `images` to `size` using bicubic interpolation.
[`ResizeBicubicGrad(...)`](../../raw_ops/resizebicubicgrad): Computes the gradient of bicubic interpolation.
[`ResizeBilinear(...)`](../../raw_ops/resizebilinear): Resize `images` to `size` using bilinear interpolation.
[`ResizeBilinearGrad(...)`](../../raw_ops/resizebilineargrad): Computes the gradient of bilinear interpolation.
[`ResizeNearestNeighbor(...)`](../../raw_ops/resizenearestneighbor): Resize `images` to `size` using nearest neighbor interpolation.
[`ResizeNearestNeighborGrad(...)`](../../raw_ops/resizenearestneighborgrad): Computes the gradient of nearest neighbor interpolation.
[`ResourceAccumulatorApplyGradient(...)`](../../raw_ops/resourceaccumulatorapplygradient): Applies a gradient to a given accumulator.
[`ResourceAccumulatorNumAccumulated(...)`](../../raw_ops/resourceaccumulatornumaccumulated): Returns the number of gradients aggregated in the given accumulators.
[`ResourceAccumulatorSetGlobalStep(...)`](../../raw_ops/resourceaccumulatorsetglobalstep): Updates the accumulator with a new value for global\_step.
[`ResourceAccumulatorTakeGradient(...)`](../../raw_ops/resourceaccumulatortakegradient): Extracts the average gradient in the given ConditionalAccumulator.
[`ResourceApplyAdaMax(...)`](../../raw_ops/resourceapplyadamax): Update '\*var' according to the AdaMax algorithm.
[`ResourceApplyAdadelta(...)`](../../raw_ops/resourceapplyadadelta): Update '\*var' according to the adadelta scheme.
[`ResourceApplyAdagrad(...)`](../../raw_ops/resourceapplyadagrad): Update '\*var' according to the adagrad scheme.
[`ResourceApplyAdagradDA(...)`](../../raw_ops/resourceapplyadagradda): Update '\*var' according to the proximal adagrad scheme.
[`ResourceApplyAdagradV2(...)`](../../raw_ops/resourceapplyadagradv2): Update '\*var' according to the adagrad scheme.
[`ResourceApplyAdam(...)`](../../raw_ops/resourceapplyadam): Update '\*var' according to the Adam algorithm.
[`ResourceApplyAdamWithAmsgrad(...)`](../../raw_ops/resourceapplyadamwithamsgrad): Update '\*var' according to the Adam algorithm.
[`ResourceApplyAddSign(...)`](../../raw_ops/resourceapplyaddsign): Update '\*var' according to the AddSign update.
[`ResourceApplyCenteredRMSProp(...)`](../../raw_ops/resourceapplycenteredrmsprop): Update '\*var' according to the centered RMSProp algorithm.
[`ResourceApplyFtrl(...)`](../../raw_ops/resourceapplyftrl): Update '\*var' according to the Ftrl-proximal scheme.
[`ResourceApplyFtrlV2(...)`](../../raw_ops/resourceapplyftrlv2): Update '\*var' according to the Ftrl-proximal scheme.
[`ResourceApplyGradientDescent(...)`](../../raw_ops/resourceapplygradientdescent): Update '\*var' by subtracting 'alpha' \* 'delta' from it.
[`ResourceApplyKerasMomentum(...)`](../../raw_ops/resourceapplykerasmomentum): Update '\*var' according to the momentum scheme.
[`ResourceApplyMomentum(...)`](../../raw_ops/resourceapplymomentum): Update '\*var' according to the momentum scheme.
[`ResourceApplyPowerSign(...)`](../../raw_ops/resourceapplypowersign): Update '\*var' according to the AddSign update.
[`ResourceApplyProximalAdagrad(...)`](../../raw_ops/resourceapplyproximaladagrad): Update '*var' and '*accum' according to FOBOS with Adagrad learning rate.
[`ResourceApplyProximalGradientDescent(...)`](../../raw_ops/resourceapplyproximalgradientdescent): Update '\*var' as FOBOS algorithm with fixed learning rate.
[`ResourceApplyRMSProp(...)`](../../raw_ops/resourceapplyrmsprop): Update '\*var' according to the RMSProp algorithm.
[`ResourceConditionalAccumulator(...)`](../../raw_ops/resourceconditionalaccumulator): A conditional accumulator for aggregating gradients.
[`ResourceCountUpTo(...)`](../../raw_ops/resourcecountupto): Increments variable pointed to by 'resource' until it reaches 'limit'.
[`ResourceGather(...)`](../../raw_ops/resourcegather): Gather slices from the variable pointed to by `resource` according to `indices`.
[`ResourceGatherNd(...)`](../../raw_ops/resourcegathernd)
[`ResourceScatterAdd(...)`](../../raw_ops/resourcescatteradd): Adds sparse updates to the variable referenced by `resource`.
[`ResourceScatterDiv(...)`](../../raw_ops/resourcescatterdiv): Divides sparse updates into the variable referenced by `resource`.
[`ResourceScatterMax(...)`](../../raw_ops/resourcescattermax): Reduces sparse updates into the variable referenced by `resource` using the `max` operation.
[`ResourceScatterMin(...)`](../../raw_ops/resourcescattermin): Reduces sparse updates into the variable referenced by `resource` using the `min` operation.
[`ResourceScatterMul(...)`](../../raw_ops/resourcescattermul): Multiplies sparse updates into the variable referenced by `resource`.
[`ResourceScatterNdAdd(...)`](../../raw_ops/resourcescatterndadd): Applies sparse addition to individual values or slices in a Variable.
[`ResourceScatterNdMax(...)`](../../raw_ops/resourcescatterndmax)
[`ResourceScatterNdMin(...)`](../../raw_ops/resourcescatterndmin)
[`ResourceScatterNdSub(...)`](../../raw_ops/resourcescatterndsub): Applies sparse subtraction to individual values or slices in a Variable.
[`ResourceScatterNdUpdate(...)`](../../raw_ops/resourcescatterndupdate): Applies sparse `updates` to individual values or slices within a given
[`ResourceScatterSub(...)`](../../raw_ops/resourcescattersub): Subtracts sparse updates from the variable referenced by `resource`.
[`ResourceScatterUpdate(...)`](../../raw_ops/resourcescatterupdate): Assigns sparse updates to the variable referenced by `resource`.
[`ResourceSparseApplyAdadelta(...)`](../../raw_ops/resourcesparseapplyadadelta): var: Should be from a Variable().
[`ResourceSparseApplyAdagrad(...)`](../../raw_ops/resourcesparseapplyadagrad): Update relevant entries in '*var' and '*accum' according to the adagrad scheme.
[`ResourceSparseApplyAdagradDA(...)`](../../raw_ops/resourcesparseapplyadagradda): Update entries in '*var' and '*accum' according to the proximal adagrad scheme.
[`ResourceSparseApplyAdagradV2(...)`](../../raw_ops/resourcesparseapplyadagradv2): Update relevant entries in '*var' and '*accum' according to the adagrad scheme.
[`ResourceSparseApplyCenteredRMSProp(...)`](../../raw_ops/resourcesparseapplycenteredrmsprop): Update '\*var' according to the centered RMSProp algorithm.
[`ResourceSparseApplyFtrl(...)`](../../raw_ops/resourcesparseapplyftrl): Update relevant entries in '\*var' according to the Ftrl-proximal scheme.
[`ResourceSparseApplyFtrlV2(...)`](../../raw_ops/resourcesparseapplyftrlv2): Update relevant entries in '\*var' according to the Ftrl-proximal scheme.
[`ResourceSparseApplyKerasMomentum(...)`](../../raw_ops/resourcesparseapplykerasmomentum): Update relevant entries in '*var' and '*accum' according to the momentum scheme.
[`ResourceSparseApplyMomentum(...)`](../../raw_ops/resourcesparseapplymomentum): Update relevant entries in '*var' and '*accum' according to the momentum scheme.
[`ResourceSparseApplyProximalAdagrad(...)`](../../raw_ops/resourcesparseapplyproximaladagrad): Sparse update entries in '*var' and '*accum' according to FOBOS algorithm.
[`ResourceSparseApplyProximalGradientDescent(...)`](../../raw_ops/resourcesparseapplyproximalgradientdescent): Sparse update '\*var' as FOBOS algorithm with fixed learning rate.
[`ResourceSparseApplyRMSProp(...)`](../../raw_ops/resourcesparseapplyrmsprop): Update '\*var' according to the RMSProp algorithm.
[`ResourceStridedSliceAssign(...)`](../../raw_ops/resourcestridedsliceassign): Assign `value` to the sliced l-value reference of `ref`.
[`Restore(...)`](../../raw_ops/restore): Restores a tensor from checkpoint files.
[`RestoreSlice(...)`](../../raw_ops/restoreslice): Restores a tensor from checkpoint files.
[`RestoreV2(...)`](../../raw_ops/restorev2): Restores tensors from a V2 checkpoint.
[`RetrieveTPUEmbeddingADAMParameters(...)`](../../raw_ops/retrievetpuembeddingadamparameters): Retrieve ADAM embedding parameters.
[`RetrieveTPUEmbeddingAdadeltaParameters(...)`](../../raw_ops/retrievetpuembeddingadadeltaparameters): Retrieve Adadelta embedding parameters.
[`RetrieveTPUEmbeddingAdagradMomentumParameters(...)`](../../raw_ops/retrievetpuembeddingadagradmomentumparameters): Retrieve Adagrad Momentum embedding parameters.
[`RetrieveTPUEmbeddingAdagradParameters(...)`](../../raw_ops/retrievetpuembeddingadagradparameters): Retrieve Adagrad embedding parameters.
[`RetrieveTPUEmbeddingCenteredRMSPropParameters(...)`](../../raw_ops/retrievetpuembeddingcenteredrmspropparameters): Retrieve centered RMSProp embedding parameters.
[`RetrieveTPUEmbeddingFTRLParameters(...)`](../../raw_ops/retrievetpuembeddingftrlparameters): Retrieve FTRL embedding parameters.
[`RetrieveTPUEmbeddingFrequencyEstimatorParameters(...)`](../../raw_ops/retrievetpuembeddingfrequencyestimatorparameters): Retrieve frequency estimator embedding parameters.
[`RetrieveTPUEmbeddingMDLAdagradLightParameters(...)`](../../raw_ops/retrievetpuembeddingmdladagradlightparameters): Retrieve MDL Adagrad Light embedding parameters.
[`RetrieveTPUEmbeddingMomentumParameters(...)`](../../raw_ops/retrievetpuembeddingmomentumparameters): Retrieve Momentum embedding parameters.
[`RetrieveTPUEmbeddingProximalAdagradParameters(...)`](../../raw_ops/retrievetpuembeddingproximaladagradparameters): Retrieve proximal Adagrad embedding parameters.
[`RetrieveTPUEmbeddingProximalYogiParameters(...)`](../../raw_ops/retrievetpuembeddingproximalyogiparameters)
[`RetrieveTPUEmbeddingRMSPropParameters(...)`](../../raw_ops/retrievetpuembeddingrmspropparameters): Retrieve RMSProp embedding parameters.
[`RetrieveTPUEmbeddingStochasticGradientDescentParameters(...)`](../../raw_ops/retrievetpuembeddingstochasticgradientdescentparameters): Retrieve SGD embedding parameters.
[`Reverse(...)`](../../raw_ops/reverse): Reverses specific dimensions of a tensor.
[`ReverseSequence(...)`](../../raw_ops/reversesequence): Reverses variable length slices.
[`ReverseV2(...)`](../../raw_ops/reversev2): Reverses specific dimensions of a tensor.
[`RightShift(...)`](../../raw_ops/rightshift): Elementwise computes the bitwise right-shift of `x` and `y`.
[`Rint(...)`](../../raw_ops/rint): Returns element-wise integer closest to x.
[`RngReadAndSkip(...)`](../../raw_ops/rngreadandskip): Advance the counter of a counter-based RNG.
[`RngSkip(...)`](../../raw_ops/rngskip): Advance the counter of a counter-based RNG.
[`Roll(...)`](../../raw_ops/roll): Rolls the elements of a tensor along an axis.
[`Round(...)`](../../raw_ops/round): Rounds the values of a tensor to the nearest integer, element-wise.
[`Rsqrt(...)`](../../raw_ops/rsqrt): Computes reciprocal of square root of x element-wise.
[`RsqrtGrad(...)`](../../raw_ops/rsqrtgrad): Computes the gradient for the rsqrt of `x` wrt its input.
[`SampleDistortedBoundingBox(...)`](../../raw_ops/sampledistortedboundingbox): Generate a single randomly distorted bounding box for an image.
[`SampleDistortedBoundingBoxV2(...)`](../../raw_ops/sampledistortedboundingboxv2): Generate a single randomly distorted bounding box for an image.
[`SamplingDataset(...)`](../../raw_ops/samplingdataset): Creates a dataset that takes a Bernoulli sample of the contents of another dataset.
[`Save(...)`](../../raw_ops/save): Saves the input tensors to disk.
[`SaveDataset(...)`](../../raw_ops/savedataset)
[`SaveDatasetV2(...)`](../../raw_ops/savedatasetv2)
[`SaveSlices(...)`](../../raw_ops/saveslices): Saves input tensors slices to disk.
[`SaveV2(...)`](../../raw_ops/savev2): Saves tensors in V2 checkpoint format.
[`ScalarSummary(...)`](../../raw_ops/scalarsummary): Outputs a `Summary` protocol buffer with scalar values.
[`ScaleAndTranslate(...)`](../../raw_ops/scaleandtranslate)
[`ScaleAndTranslateGrad(...)`](../../raw_ops/scaleandtranslategrad)
[`ScanDataset(...)`](../../raw_ops/scandataset): Creates a dataset successively reduces `f` over the elements of `input_dataset`.
[`ScatterAdd(...)`](../../raw_ops/scatteradd): Adds sparse updates to a variable reference.
[`ScatterDiv(...)`](../../raw_ops/scatterdiv): Divides a variable reference by sparse updates.
[`ScatterMax(...)`](../../raw_ops/scattermax): Reduces sparse updates into a variable reference using the `max` operation.
[`ScatterMin(...)`](../../raw_ops/scattermin): Reduces sparse updates into a variable reference using the `min` operation.
[`ScatterMul(...)`](../../raw_ops/scattermul): Multiplies sparse updates into a variable reference.
[`ScatterNd(...)`](../../raw_ops/scatternd): Scatters `updates` into a tensor of shape `shape` according to `indices`.
[`ScatterNdAdd(...)`](../../raw_ops/scatterndadd): Applies sparse addition to individual values or slices in a Variable.
[`ScatterNdMax(...)`](../../raw_ops/scatterndmax): Computes element-wise maximum.
[`ScatterNdMin(...)`](../../raw_ops/scatterndmin): Computes element-wise minimum.
[`ScatterNdNonAliasingAdd(...)`](../../raw_ops/scatterndnonaliasingadd): Applies sparse addition to `input` using individual values or slices
[`ScatterNdSub(...)`](../../raw_ops/scatterndsub): Applies sparse subtraction to individual values or slices in a Variable.
[`ScatterNdUpdate(...)`](../../raw_ops/scatterndupdate): Applies sparse `updates` to individual values or slices within a given
[`ScatterSub(...)`](../../raw_ops/scattersub): Subtracts sparse updates to a variable reference.
[`ScatterUpdate(...)`](../../raw_ops/scatterupdate): Applies sparse updates to a variable reference.
[`SdcaFprint(...)`](../../raw_ops/sdcafprint): Computes fingerprints of the input strings.
[`SdcaOptimizer(...)`](../../raw_ops/sdcaoptimizer): Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for
[`SdcaOptimizerV2(...)`](../../raw_ops/sdcaoptimizerv2): Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for
[`SdcaShrinkL1(...)`](../../raw_ops/sdcashrinkl1): Applies L1 regularization shrink step on the parameters.
[`SegmentMax(...)`](../../raw_ops/segmentmax): Computes the maximum along segments of a tensor.
[`SegmentMean(...)`](../../raw_ops/segmentmean): Computes the mean along segments of a tensor.
[`SegmentMin(...)`](../../raw_ops/segmentmin): Computes the minimum along segments of a tensor.
[`SegmentProd(...)`](../../raw_ops/segmentprod): Computes the product along segments of a tensor.
[`SegmentSum(...)`](../../raw_ops/segmentsum): Computes the sum along segments of a tensor.
[`Select(...)`](../../raw_ops/select): Selects elements from `x` or `y`, depending on `condition`.
[`SelectV2(...)`](../../raw_ops/selectv2)
[`SelfAdjointEig(...)`](../../raw_ops/selfadjointeig): Computes the Eigen Decomposition of a batch of square self-adjoint matrices.
[`SelfAdjointEigV2(...)`](../../raw_ops/selfadjointeigv2): Computes the eigen decomposition of one or more square self-adjoint matrices.
[`Selu(...)`](../../raw_ops/selu): Computes scaled exponential linear: `scale * alpha * (exp(features) - 1)`
[`SeluGrad(...)`](../../raw_ops/selugrad): Computes gradients for the scaled exponential linear (Selu) operation.
[`Send(...)`](../../raw_ops/send): Sends the named tensor from send\_device to recv\_device.
[`SendTPUEmbeddingGradients(...)`](../../raw_ops/sendtpuembeddinggradients): Performs gradient updates of embedding tables.
[`SerializeIterator(...)`](../../raw_ops/serializeiterator): Converts the given `resource_handle` representing an iterator to a variant tensor.
[`SerializeManySparse(...)`](../../raw_ops/serializemanysparse): Serialize an `N`-minibatch `SparseTensor` into an `[N, 3]` `Tensor` object.
[`SerializeSparse(...)`](../../raw_ops/serializesparse): Serialize a `SparseTensor` into a `[3]` `Tensor` object.
[`SerializeTensor(...)`](../../raw_ops/serializetensor): Transforms a Tensor into a serialized TensorProto proto.
[`SetSize(...)`](../../raw_ops/setsize): Number of unique elements along last dimension of input `set`.
[`SetStatsAggregatorDataset(...)`](../../raw_ops/setstatsaggregatordataset)
[`Shape(...)`](../../raw_ops/shape): Returns the shape of a tensor.
[`ShapeN(...)`](../../raw_ops/shapen): Returns shape of tensors.
[`ShardDataset(...)`](../../raw_ops/sharddataset): Creates a `Dataset` that includes only 1/`num_shards` of this dataset.
[`ShardedFilename(...)`](../../raw_ops/shardedfilename): Generate a sharded filename. The filename is printf formatted as
[`ShardedFilespec(...)`](../../raw_ops/shardedfilespec): Generate a glob pattern matching all sharded file names.
[`ShuffleAndRepeatDataset(...)`](../../raw_ops/shuffleandrepeatdataset): Creates a dataset that shuffles and repeats elements from `input_dataset`
[`ShuffleAndRepeatDatasetV2(...)`](../../raw_ops/shuffleandrepeatdatasetv2)
[`ShuffleDataset(...)`](../../raw_ops/shuffledataset): Creates a dataset that shuffles elements from `input_dataset` pseudorandomly.
[`ShuffleDatasetV2(...)`](../../raw_ops/shuffledatasetv2)
[`ShuffleDatasetV3(...)`](../../raw_ops/shuffledatasetv3)
[`ShutdownDistributedTPU(...)`](../../raw_ops/shutdowndistributedtpu): Shuts down a running distributed TPU system.
[`Sigmoid(...)`](../../raw_ops/sigmoid): Computes sigmoid of `x` element-wise.
[`SigmoidGrad(...)`](../../raw_ops/sigmoidgrad): Computes the gradient of the sigmoid of `x` wrt its input.
[`Sign(...)`](../../raw_ops/sign): Returns an element-wise indication of the sign of a number.
[`Sin(...)`](../../raw_ops/sin): Computes sine of x element-wise.
[`Sinh(...)`](../../raw_ops/sinh): Computes hyperbolic sine of x element-wise.
[`Size(...)`](../../raw_ops/size): Returns the size of a tensor.
[`SkipDataset(...)`](../../raw_ops/skipdataset): Creates a dataset that skips `count` elements from the `input_dataset`.
[`SleepDataset(...)`](../../raw_ops/sleepdataset)
[`Slice(...)`](../../raw_ops/slice): Return a slice from 'input'.
[`SlidingWindowDataset(...)`](../../raw_ops/slidingwindowdataset): Creates a dataset that passes a sliding window over `input_dataset`.
[`Snapshot(...)`](../../raw_ops/snapshot): Returns a copy of the input tensor.
[`SnapshotDataset(...)`](../../raw_ops/snapshotdataset): Creates a dataset that will write to / read from a snapshot.
[`SnapshotDatasetReader(...)`](../../raw_ops/snapshotdatasetreader)
[`SnapshotDatasetV2(...)`](../../raw_ops/snapshotdatasetv2): Creates a dataset that will write to / read from a snapshot.
[`SnapshotNestedDatasetReader(...)`](../../raw_ops/snapshotnesteddatasetreader)
[`SobolSample(...)`](../../raw_ops/sobolsample): Generates points from the Sobol sequence.
[`Softmax(...)`](../../raw_ops/softmax): Computes softmax activations.
[`SoftmaxCrossEntropyWithLogits(...)`](../../raw_ops/softmaxcrossentropywithlogits): Computes softmax cross entropy cost and gradients to backpropagate.
[`Softplus(...)`](../../raw_ops/softplus)
[`SoftplusGrad(...)`](../../raw_ops/softplusgrad): Computes softplus gradients for a softplus operation.
[`Softsign(...)`](../../raw_ops/softsign): Computes softsign: `features / (abs(features) + 1)`.
[`SoftsignGrad(...)`](../../raw_ops/softsigngrad): Computes softsign gradients for a softsign operation.
[`SpaceToBatch(...)`](../../raw_ops/spacetobatch): SpaceToBatch for 4-D tensors of type T.
[`SpaceToBatchND(...)`](../../raw_ops/spacetobatchnd): SpaceToBatch for N-D tensors of type T.
[`SpaceToDepth(...)`](../../raw_ops/spacetodepth): SpaceToDepth for tensors of type T.
[`SparseAccumulatorApplyGradient(...)`](../../raw_ops/sparseaccumulatorapplygradient): Applies a sparse gradient to a given accumulator.
[`SparseAccumulatorTakeGradient(...)`](../../raw_ops/sparseaccumulatortakegradient): Extracts the average sparse gradient in a SparseConditionalAccumulator.
[`SparseAdd(...)`](../../raw_ops/sparseadd): Adds two `SparseTensor` objects to produce another `SparseTensor`.
[`SparseAddGrad(...)`](../../raw_ops/sparseaddgrad): The gradient operator for the SparseAdd op.
[`SparseApplyAdadelta(...)`](../../raw_ops/sparseapplyadadelta): var: Should be from a Variable().
[`SparseApplyAdagrad(...)`](../../raw_ops/sparseapplyadagrad): Update relevant entries in '*var' and '*accum' according to the adagrad scheme.
[`SparseApplyAdagradDA(...)`](../../raw_ops/sparseapplyadagradda): Update entries in '*var' and '*accum' according to the proximal adagrad scheme.
[`SparseApplyAdagradV2(...)`](../../raw_ops/sparseapplyadagradv2): Update relevant entries in '*var' and '*accum' according to the adagrad scheme.
[`SparseApplyCenteredRMSProp(...)`](../../raw_ops/sparseapplycenteredrmsprop): Update '\*var' according to the centered RMSProp algorithm.
[`SparseApplyFtrl(...)`](../../raw_ops/sparseapplyftrl): Update relevant entries in '\*var' according to the Ftrl-proximal scheme.
[`SparseApplyFtrlV2(...)`](../../raw_ops/sparseapplyftrlv2): Update relevant entries in '\*var' according to the Ftrl-proximal scheme.
[`SparseApplyMomentum(...)`](../../raw_ops/sparseapplymomentum): Update relevant entries in '*var' and '*accum' according to the momentum scheme.
[`SparseApplyProximalAdagrad(...)`](../../raw_ops/sparseapplyproximaladagrad): Sparse update entries in '*var' and '*accum' according to FOBOS algorithm.
[`SparseApplyProximalGradientDescent(...)`](../../raw_ops/sparseapplyproximalgradientdescent): Sparse update '\*var' as FOBOS algorithm with fixed learning rate.
[`SparseApplyRMSProp(...)`](../../raw_ops/sparseapplyrmsprop): Update '\*var' according to the RMSProp algorithm.
[`SparseBincount(...)`](../../raw_ops/sparsebincount): Counts the number of occurrences of each value in an integer array.
[`SparseConcat(...)`](../../raw_ops/sparseconcat): Concatenates a list of `SparseTensor` along the specified dimension.
[`SparseConditionalAccumulator(...)`](../../raw_ops/sparseconditionalaccumulator): A conditional accumulator for aggregating sparse gradients.
[`SparseCountSparseOutput(...)`](../../raw_ops/sparsecountsparseoutput): Performs sparse-output bin counting for a sparse tensor input.
[`SparseCross(...)`](../../raw_ops/sparsecross): Generates sparse cross from a list of sparse and dense tensors.
[`SparseCrossHashed(...)`](../../raw_ops/sparsecrosshashed): Generates sparse cross from a list of sparse and dense tensors.
[`SparseCrossV2(...)`](../../raw_ops/sparsecrossv2): Generates sparse cross from a list of sparse and dense tensors.
[`SparseDenseCwiseAdd(...)`](../../raw_ops/sparsedensecwiseadd): Adds up a SparseTensor and a dense Tensor, using these special rules:
[`SparseDenseCwiseDiv(...)`](../../raw_ops/sparsedensecwisediv): Component-wise divides a SparseTensor by a dense Tensor.
[`SparseDenseCwiseMul(...)`](../../raw_ops/sparsedensecwisemul): Component-wise multiplies a SparseTensor by a dense Tensor.
[`SparseFillEmptyRows(...)`](../../raw_ops/sparsefillemptyrows): Fills empty rows in the input 2-D `SparseTensor` with a default value.
[`SparseFillEmptyRowsGrad(...)`](../../raw_ops/sparsefillemptyrowsgrad): The gradient of SparseFillEmptyRows.
[`SparseMatMul(...)`](../../raw_ops/sparsematmul): Multiply matrix "a" by matrix "b".
[`SparseMatrixAdd(...)`](../../raw_ops/sparsematrixadd): Sparse addition of two CSR matrices, C = alpha \* A + beta \* B.
[`SparseMatrixMatMul(...)`](../../raw_ops/sparsematrixmatmul): Matrix-multiplies a sparse matrix with a dense matrix.
[`SparseMatrixMul(...)`](../../raw_ops/sparsematrixmul): Element-wise multiplication of a sparse matrix with a dense tensor.
[`SparseMatrixNNZ(...)`](../../raw_ops/sparsematrixnnz): Returns the number of nonzeroes of `sparse_matrix`.
[`SparseMatrixOrderingAMD(...)`](../../raw_ops/sparsematrixorderingamd): Computes the Approximate Minimum Degree (AMD) ordering of `input`.
[`SparseMatrixSoftmax(...)`](../../raw_ops/sparsematrixsoftmax): Calculates the softmax of a CSRSparseMatrix.
[`SparseMatrixSoftmaxGrad(...)`](../../raw_ops/sparsematrixsoftmaxgrad): Calculates the gradient of the SparseMatrixSoftmax op.
[`SparseMatrixSparseCholesky(...)`](../../raw_ops/sparsematrixsparsecholesky): Computes the sparse Cholesky decomposition of `input`.
[`SparseMatrixSparseMatMul(...)`](../../raw_ops/sparsematrixsparsematmul): Sparse-matrix-multiplies two CSR matrices `a` and `b`.
[`SparseMatrixTranspose(...)`](../../raw_ops/sparsematrixtranspose): Transposes the inner (matrix) dimensions of a CSRSparseMatrix.
[`SparseMatrixZeros(...)`](../../raw_ops/sparsematrixzeros): Creates an all-zeros CSRSparseMatrix with shape `dense_shape`.
[`SparseReduceMax(...)`](../../raw_ops/sparsereducemax): Computes the max of elements across dimensions of a SparseTensor.
[`SparseReduceMaxSparse(...)`](../../raw_ops/sparsereducemaxsparse): Computes the max of elements across dimensions of a SparseTensor.
[`SparseReduceSum(...)`](../../raw_ops/sparsereducesum): Computes the sum of elements across dimensions of a SparseTensor.
[`SparseReduceSumSparse(...)`](../../raw_ops/sparsereducesumsparse): Computes the sum of elements across dimensions of a SparseTensor.
[`SparseReorder(...)`](../../raw_ops/sparsereorder): Reorders a SparseTensor into the canonical, row-major ordering.
[`SparseReshape(...)`](../../raw_ops/sparsereshape): Reshapes a SparseTensor to represent values in a new dense shape.
[`SparseSegmentMean(...)`](../../raw_ops/sparsesegmentmean): Computes the mean along sparse segments of a tensor.
[`SparseSegmentMeanGrad(...)`](../../raw_ops/sparsesegmentmeangrad): Computes gradients for SparseSegmentMean.
[`SparseSegmentMeanWithNumSegments(...)`](../../raw_ops/sparsesegmentmeanwithnumsegments): Computes the mean along sparse segments of a tensor.
[`SparseSegmentSqrtN(...)`](../../raw_ops/sparsesegmentsqrtn): Computes the sum along sparse segments of a tensor divided by the sqrt of N.
[`SparseSegmentSqrtNGrad(...)`](../../raw_ops/sparsesegmentsqrtngrad): Computes gradients for SparseSegmentSqrtN.
[`SparseSegmentSqrtNWithNumSegments(...)`](../../raw_ops/sparsesegmentsqrtnwithnumsegments): Computes the sum along sparse segments of a tensor divided by the sqrt of N.
[`SparseSegmentSum(...)`](../../raw_ops/sparsesegmentsum): Computes the sum along sparse segments of a tensor.
[`SparseSegmentSumGrad(...)`](../../raw_ops/sparsesegmentsumgrad): Computes gradients for SparseSegmentSum.
[`SparseSegmentSumWithNumSegments(...)`](../../raw_ops/sparsesegmentsumwithnumsegments): Computes the sum along sparse segments of a tensor.
[`SparseSlice(...)`](../../raw_ops/sparseslice): Slice a `SparseTensor` based on the `start` and `size`.
[`SparseSliceGrad(...)`](../../raw_ops/sparseslicegrad): The gradient operator for the SparseSlice op.
[`SparseSoftmax(...)`](../../raw_ops/sparsesoftmax): Applies softmax to a batched N-D `SparseTensor`.
[`SparseSoftmaxCrossEntropyWithLogits(...)`](../../raw_ops/sparsesoftmaxcrossentropywithlogits): Computes softmax cross entropy cost and gradients to backpropagate.
[`SparseSparseMaximum(...)`](../../raw_ops/sparsesparsemaximum): Returns the element-wise max of two SparseTensors.
[`SparseSparseMinimum(...)`](../../raw_ops/sparsesparseminimum): Returns the element-wise min of two SparseTensors.
[`SparseSplit(...)`](../../raw_ops/sparsesplit): Split a `SparseTensor` into `num_split` tensors along one dimension.
[`SparseTensorDenseAdd(...)`](../../raw_ops/sparsetensordenseadd): Adds up a `SparseTensor` and a dense `Tensor`, producing a dense `Tensor`.
[`SparseTensorDenseMatMul(...)`](../../raw_ops/sparsetensordensematmul): Multiply SparseTensor (of rank 2) "A" by dense matrix "B".
[`SparseTensorSliceDataset(...)`](../../raw_ops/sparsetensorslicedataset): Creates a dataset that splits a SparseTensor into elements row-wise.
[`SparseTensorToCSRSparseMatrix(...)`](../../raw_ops/sparsetensortocsrsparsematrix): Converts a SparseTensor to a (possibly batched) CSRSparseMatrix.
[`SparseToDense(...)`](../../raw_ops/sparsetodense): Converts a sparse representation into a dense tensor.
[`SparseToSparseSetOperation(...)`](../../raw_ops/sparsetosparsesetoperation): Applies set operation along last dimension of 2 `SparseTensor` inputs.
[`Spence(...)`](../../raw_ops/spence)
[`Split(...)`](../../raw_ops/split): Splits a tensor into `num_split` tensors along one dimension.
[`SplitV(...)`](../../raw_ops/splitv): Splits a tensor into `num_split` tensors along one dimension.
[`SqlDataset(...)`](../../raw_ops/sqldataset): Creates a dataset that executes a SQL query and emits rows of the result set.
[`Sqrt(...)`](../../raw_ops/sqrt): Computes square root of x element-wise.
[`SqrtGrad(...)`](../../raw_ops/sqrtgrad): Computes the gradient for the sqrt of `x` wrt its input.
[`Square(...)`](../../raw_ops/square): Computes square of x element-wise.
[`SquaredDifference(...)`](../../raw_ops/squareddifference): Returns conj(x - y)(x - y) element-wise.
[`Squeeze(...)`](../../raw_ops/squeeze): Removes dimensions of size 1 from the shape of a tensor.
[`Stack(...)`](../../raw_ops/stack): Deprecated, use StackV2.
[`StackClose(...)`](../../raw_ops/stackclose): Deprecated, use StackCloseV2.
[`StackCloseV2(...)`](../../raw_ops/stackclosev2): Delete the stack from its resource container.
[`StackPop(...)`](../../raw_ops/stackpop): Deprecated, use StackPopV2.
[`StackPopV2(...)`](../../raw_ops/stackpopv2): Pop the element at the top of the stack.
[`StackPush(...)`](../../raw_ops/stackpush): Deprecated, use StackPushV2.
[`StackPushV2(...)`](../../raw_ops/stackpushv2): Push an element onto the stack.
[`StackV2(...)`](../../raw_ops/stackv2): A stack that produces elements in first-in last-out order.
[`Stage(...)`](../../raw_ops/stage): Stage values similar to a lightweight Enqueue.
[`StageClear(...)`](../../raw_ops/stageclear): Op removes all elements in the underlying container.
[`StagePeek(...)`](../../raw_ops/stagepeek): Op peeks at the values at the specified index. If the
[`StageSize(...)`](../../raw_ops/stagesize): Op returns the number of elements in the underlying container.
[`StatefulPartitionedCall(...)`](../../raw_ops/statefulpartitionedcall): returns `f(inputs)`, where `f`'s body is placed and partitioned.
[`StatefulRandomBinomial(...)`](../../raw_ops/statefulrandombinomial)
[`StatefulStandardNormal(...)`](../../raw_ops/statefulstandardnormal): Outputs random values from a normal distribution. This op is deprecated in favor of op 'StatefulStandardNormalV2'
[`StatefulStandardNormalV2(...)`](../../raw_ops/statefulstandardnormalv2): Outputs random values from a normal distribution.
[`StatefulTruncatedNormal(...)`](../../raw_ops/statefultruncatednormal): Outputs random values from a truncated normal distribution.
[`StatefulUniform(...)`](../../raw_ops/statefuluniform): Outputs random values from a uniform distribution.
[`StatefulUniformFullInt(...)`](../../raw_ops/statefuluniformfullint): Outputs random integers from a uniform distribution.
[`StatefulUniformInt(...)`](../../raw_ops/statefuluniformint): Outputs random integers from a uniform distribution.
[`StatelessCase(...)`](../../raw_ops/statelesscase): An n-way switch statement which calls a single branch function.
[`StatelessIf(...)`](../../raw_ops/statelessif): output = cond ? then\_branch(input) : else\_branch(input)
[`StatelessMultinomial(...)`](../../raw_ops/statelessmultinomial): Draws samples from a multinomial distribution.
[`StatelessParameterizedTruncatedNormal(...)`](../../raw_ops/statelessparameterizedtruncatednormal)
[`StatelessRandomBinomial(...)`](../../raw_ops/statelessrandombinomial): Outputs deterministic pseudorandom random numbers from a binomial distribution.
[`StatelessRandomGammaV2(...)`](../../raw_ops/statelessrandomgammav2): Outputs deterministic pseudorandom random numbers from a gamma distribution.
[`StatelessRandomGetAlg(...)`](../../raw_ops/statelessrandomgetalg): Picks the best counter-based RNG algorithm based on device.
[`StatelessRandomGetKeyCounter(...)`](../../raw_ops/statelessrandomgetkeycounter): Scrambles seed into key and counter, using the best algorithm based on device.
[`StatelessRandomGetKeyCounterAlg(...)`](../../raw_ops/statelessrandomgetkeycounteralg): Picks the best algorithm based on device, and scrambles seed into key and counter.
[`StatelessRandomNormal(...)`](../../raw_ops/statelessrandomnormal): Outputs deterministic pseudorandom values from a normal distribution.
[`StatelessRandomNormalV2(...)`](../../raw_ops/statelessrandomnormalv2): Outputs deterministic pseudorandom values from a normal distribution.
[`StatelessRandomPoisson(...)`](../../raw_ops/statelessrandompoisson): Outputs deterministic pseudorandom random numbers from a Poisson distribution.
[`StatelessRandomUniform(...)`](../../raw_ops/statelessrandomuniform): Outputs deterministic pseudorandom random values from a uniform distribution.
[`StatelessRandomUniformFullInt(...)`](../../raw_ops/statelessrandomuniformfullint): Outputs deterministic pseudorandom random integers from a uniform distribution.
[`StatelessRandomUniformFullIntV2(...)`](../../raw_ops/statelessrandomuniformfullintv2): Outputs deterministic pseudorandom random integers from a uniform distribution.
[`StatelessRandomUniformInt(...)`](../../raw_ops/statelessrandomuniformint): Outputs deterministic pseudorandom random integers from a uniform distribution.
[`StatelessRandomUniformIntV2(...)`](../../raw_ops/statelessrandomuniformintv2): Outputs deterministic pseudorandom random integers from a uniform distribution.
[`StatelessRandomUniformV2(...)`](../../raw_ops/statelessrandomuniformv2): Outputs deterministic pseudorandom random values from a uniform distribution.
[`StatelessSampleDistortedBoundingBox(...)`](../../raw_ops/statelesssampledistortedboundingbox): Generate a randomly distorted bounding box for an image deterministically.
[`StatelessTruncatedNormal(...)`](../../raw_ops/statelesstruncatednormal): Outputs deterministic pseudorandom values from a truncated normal distribution.
[`StatelessTruncatedNormalV2(...)`](../../raw_ops/statelesstruncatednormalv2): Outputs deterministic pseudorandom values from a truncated normal distribution.
[`StatelessWhile(...)`](../../raw_ops/statelesswhile): output = input; While (Cond(output)) { output = Body(output) }
[`StaticRegexFullMatch(...)`](../../raw_ops/staticregexfullmatch): Check if the input matches the regex pattern.
[`StaticRegexReplace(...)`](../../raw_ops/staticregexreplace): Replaces the match of pattern in input with rewrite.
[`StatsAggregatorHandle(...)`](../../raw_ops/statsaggregatorhandle): Creates a statistics manager resource.
[`StatsAggregatorHandleV2(...)`](../../raw_ops/statsaggregatorhandlev2)
[`StatsAggregatorSetSummaryWriter(...)`](../../raw_ops/statsaggregatorsetsummarywriter): Set a summary\_writer\_interface to record statistics using given stats\_aggregator.
[`StatsAggregatorSummary(...)`](../../raw_ops/statsaggregatorsummary): Produces a summary of any statistics recorded by the given statistics manager.
[`StopGradient(...)`](../../raw_ops/stopgradient): Stops gradient computation.
[`StridedSlice(...)`](../../raw_ops/stridedslice): Return a strided slice from `input`.
[`StridedSliceAssign(...)`](../../raw_ops/stridedsliceassign): Assign `value` to the sliced l-value reference of `ref`.
[`StridedSliceGrad(...)`](../../raw_ops/stridedslicegrad): Returns the gradient of `StridedSlice`.
[`StringFormat(...)`](../../raw_ops/stringformat): Formats a string template using a list of tensors.
[`StringJoin(...)`](../../raw_ops/stringjoin): Joins the strings in the given list of string tensors into one tensor;
[`StringLength(...)`](../../raw_ops/stringlength): String lengths of `input`.
[`StringLower(...)`](../../raw_ops/stringlower): Converts all uppercase characters into their respective lowercase replacements.
[`StringNGrams(...)`](../../raw_ops/stringngrams): Creates ngrams from ragged string data.
[`StringSplit(...)`](../../raw_ops/stringsplit): Split elements of `input` based on `delimiter` into a `SparseTensor`.
[`StringSplitV2(...)`](../../raw_ops/stringsplitv2): Split elements of `source` based on `sep` into a `SparseTensor`.
[`StringStrip(...)`](../../raw_ops/stringstrip): Strip leading and trailing whitespaces from the Tensor.
[`StringToHashBucket(...)`](../../raw_ops/stringtohashbucket): Converts each string in the input Tensor to its hash mod by a number of buckets.
[`StringToHashBucketFast(...)`](../../raw_ops/stringtohashbucketfast): Converts each string in the input Tensor to its hash mod by a number of buckets.
[`StringToHashBucketStrong(...)`](../../raw_ops/stringtohashbucketstrong): Converts each string in the input Tensor to its hash mod by a number of buckets.
[`StringToNumber(...)`](../../raw_ops/stringtonumber): Converts each string in the input Tensor to the specified numeric type.
[`StringUpper(...)`](../../raw_ops/stringupper): Converts all lowercase characters into their respective uppercase replacements.
[`Sub(...)`](../../raw_ops/sub): Returns x - y element-wise.
[`Substr(...)`](../../raw_ops/substr): Return substrings from `Tensor` of strings.
[`Sum(...)`](../../raw_ops/sum): Computes the sum of elements across dimensions of a tensor.
[`SummaryWriter(...)`](../../raw_ops/summarywriter)
[`Svd(...)`](../../raw_ops/svd): Computes the singular value decompositions of one or more matrices.
[`Switch(...)`](../../raw_ops/switch): Forwards `data` to the output port determined by `pred`.
[`SymbolicGradient(...)`](../../raw_ops/symbolicgradient): Computes the gradient function for function f via backpropagation.
[`TFRecordDataset(...)`](../../raw_ops/tfrecorddataset): Creates a dataset that emits the records from one or more TFRecord files.
[`TFRecordReader(...)`](../../raw_ops/tfrecordreader): A Reader that outputs the records from a TensorFlow Records file.
[`TFRecordReaderV2(...)`](../../raw_ops/tfrecordreaderv2): A Reader that outputs the records from a TensorFlow Records file.
[`TPUCompilationResult(...)`](../../raw_ops/tpucompilationresult): Returns the result of a TPU compilation.
[`TPUEmbeddingActivations(...)`](../../raw_ops/tpuembeddingactivations): An op enabling differentiation of TPU Embeddings.
[`TPUOrdinalSelector(...)`](../../raw_ops/tpuordinalselector): A TPU core selector Op.
[`TPUPartitionedCall(...)`](../../raw_ops/tpupartitionedcall): Calls a function placed on a specified TPU device.
[`TPUPartitionedInput(...)`](../../raw_ops/tpupartitionedinput): An op that groups a list of partitioned inputs together. This op
[`TPUPartitionedOutput(...)`](../../raw_ops/tpupartitionedoutput): An op that demultiplexes a tensor to be sharded by XLA to a list of partitioned
[`TPUReplicateMetadata(...)`](../../raw_ops/tpureplicatemetadata): Metadata indicating how the TPU computation should be replicated.
[`TPUReplicatedInput(...)`](../../raw_ops/tpureplicatedinput): Connects N inputs to an N-way replicated TPU computation.
[`TPUReplicatedOutput(...)`](../../raw_ops/tpureplicatedoutput): Connects N outputs from an N-way replicated TPU computation.
[`TakeDataset(...)`](../../raw_ops/takedataset): Creates a dataset that contains `count` elements from the `input_dataset`.
[`TakeManySparseFromTensorsMap(...)`](../../raw_ops/takemanysparsefromtensorsmap): Read `SparseTensors` from a `SparseTensorsMap` and concatenate them.
[`TakeWhileDataset(...)`](../../raw_ops/takewhiledataset): Creates a dataset that stops iteration when predicate` is false.
[`Tan(...)`](../../raw_ops/tan): Computes tan of x element-wise.
[`Tanh(...)`](../../raw_ops/tanh): Computes hyperbolic tangent of `x` element-wise.
[`TanhGrad(...)`](../../raw_ops/tanhgrad): Computes the gradient for the tanh of `x` wrt its input.
[`TemporaryVariable(...)`](../../raw_ops/temporaryvariable): Returns a tensor that may be mutated, but only persists within a single step.
[`TensorArray(...)`](../../raw_ops/tensorarray)
[`TensorArrayClose(...)`](../../raw_ops/tensorarrayclose)
[`TensorArrayCloseV2(...)`](../../raw_ops/tensorarrayclosev2): Deprecated. Use TensorArrayCloseV3
[`TensorArrayCloseV3(...)`](../../raw_ops/tensorarrayclosev3): Delete the TensorArray from its resource container.
[`TensorArrayConcat(...)`](../../raw_ops/tensorarrayconcat)
[`TensorArrayConcatV2(...)`](../../raw_ops/tensorarrayconcatv2): Deprecated. Use TensorArrayConcatV3
[`TensorArrayConcatV3(...)`](../../raw_ops/tensorarrayconcatv3): Concat the elements from the TensorArray into value `value`.
[`TensorArrayGather(...)`](../../raw_ops/tensorarraygather)
[`TensorArrayGatherV2(...)`](../../raw_ops/tensorarraygatherv2): Deprecated. Use TensorArrayGatherV3
[`TensorArrayGatherV3(...)`](../../raw_ops/tensorarraygatherv3): Gather specific elements from the TensorArray into output `value`.
[`TensorArrayGrad(...)`](../../raw_ops/tensorarraygrad)
[`TensorArrayGradV2(...)`](../../raw_ops/tensorarraygradv2): Deprecated. Use TensorArrayGradV3
[`TensorArrayGradV3(...)`](../../raw_ops/tensorarraygradv3): Creates a TensorArray for storing the gradients of values in the given handle.
[`TensorArrayGradWithShape(...)`](../../raw_ops/tensorarraygradwithshape): Creates a TensorArray for storing multiple gradients of values in the given handle.
[`TensorArrayPack(...)`](../../raw_ops/tensorarraypack)
[`TensorArrayRead(...)`](../../raw_ops/tensorarrayread)
[`TensorArrayReadV2(...)`](../../raw_ops/tensorarrayreadv2): Deprecated. Use TensorArrayReadV3
[`TensorArrayReadV3(...)`](../../raw_ops/tensorarrayreadv3): Read an element from the TensorArray into output `value`.
[`TensorArrayScatter(...)`](../../raw_ops/tensorarrayscatter)
[`TensorArrayScatterV2(...)`](../../raw_ops/tensorarrayscatterv2): Deprecated. Use TensorArrayScatterV3
[`TensorArrayScatterV3(...)`](../../raw_ops/tensorarrayscatterv3): Scatter the data from the input value into specific TensorArray elements.
[`TensorArraySize(...)`](../../raw_ops/tensorarraysize)
[`TensorArraySizeV2(...)`](../../raw_ops/tensorarraysizev2): Deprecated. Use TensorArraySizeV3
[`TensorArraySizeV3(...)`](../../raw_ops/tensorarraysizev3): Get the current size of the TensorArray.
[`TensorArraySplit(...)`](../../raw_ops/tensorarraysplit)
[`TensorArraySplitV2(...)`](../../raw_ops/tensorarraysplitv2): Deprecated. Use TensorArraySplitV3
[`TensorArraySplitV3(...)`](../../raw_ops/tensorarraysplitv3): Split the data from the input value into TensorArray elements.
[`TensorArrayUnpack(...)`](../../raw_ops/tensorarrayunpack)
[`TensorArrayV2(...)`](../../raw_ops/tensorarrayv2): Deprecated. Use TensorArrayV3
[`TensorArrayV3(...)`](../../raw_ops/tensorarrayv3): An array of Tensors of given size.
[`TensorArrayWrite(...)`](../../raw_ops/tensorarraywrite)
[`TensorArrayWriteV2(...)`](../../raw_ops/tensorarraywritev2): Deprecated. Use TensorArrayGradV3
[`TensorArrayWriteV3(...)`](../../raw_ops/tensorarraywritev3): Push an element onto the tensor\_array.
[`TensorDataset(...)`](../../raw_ops/tensordataset): Creates a dataset that emits `components` as a tuple of tensors once.
[`TensorListConcat(...)`](../../raw_ops/tensorlistconcat): Concats all tensors in the list along the 0th dimension.
[`TensorListConcatLists(...)`](../../raw_ops/tensorlistconcatlists)
[`TensorListConcatV2(...)`](../../raw_ops/tensorlistconcatv2): Concats all tensors in the list along the 0th dimension.
[`TensorListElementShape(...)`](../../raw_ops/tensorlistelementshape): The shape of the elements of the given list, as a tensor.
[`TensorListFromTensor(...)`](../../raw_ops/tensorlistfromtensor): Creates a TensorList which, when stacked, has the value of `tensor`.
[`TensorListGather(...)`](../../raw_ops/tensorlistgather): Creates a Tensor by indexing into the TensorList.
[`TensorListGetItem(...)`](../../raw_ops/tensorlistgetitem): Returns the item in the list with the given index.
[`TensorListLength(...)`](../../raw_ops/tensorlistlength): Returns the number of tensors in the input tensor list.
[`TensorListPopBack(...)`](../../raw_ops/tensorlistpopback): Returns the last element of the input list as well as a list with all but that element.
[`TensorListPushBack(...)`](../../raw_ops/tensorlistpushback): Returns a list which has the passed-in `Tensor` as last element and the other elements of the given list in `input_handle`.
[`TensorListPushBackBatch(...)`](../../raw_ops/tensorlistpushbackbatch)
[`TensorListReserve(...)`](../../raw_ops/tensorlistreserve): List of the given size with empty elements.
[`TensorListResize(...)`](../../raw_ops/tensorlistresize): Resizes the list.
[`TensorListScatter(...)`](../../raw_ops/tensorlistscatter): Creates a TensorList by indexing into a Tensor.
[`TensorListScatterIntoExistingList(...)`](../../raw_ops/tensorlistscatterintoexistinglist): Scatters tensor at indices in an input list.
[`TensorListScatterV2(...)`](../../raw_ops/tensorlistscatterv2): Creates a TensorList by indexing into a Tensor.
[`TensorListSetItem(...)`](../../raw_ops/tensorlistsetitem): Sets the index-th position of the list to contain the given tensor.
[`TensorListSplit(...)`](../../raw_ops/tensorlistsplit): Splits a tensor into a list.
[`TensorListStack(...)`](../../raw_ops/tensorliststack): Stacks all tensors in the list.
[`TensorScatterAdd(...)`](../../raw_ops/tensorscatteradd): Adds sparse `updates` to an existing tensor according to `indices`.
[`TensorScatterMax(...)`](../../raw_ops/tensorscattermax): Apply a sparse update to a tensor taking the element-wise maximum.
[`TensorScatterMin(...)`](../../raw_ops/tensorscattermin)
[`TensorScatterSub(...)`](../../raw_ops/tensorscattersub): Subtracts sparse `updates` from an existing tensor according to `indices`.
[`TensorScatterUpdate(...)`](../../raw_ops/tensorscatterupdate): Scatter `updates` into an existing tensor according to `indices`.
[`TensorSliceDataset(...)`](../../raw_ops/tensorslicedataset): Creates a dataset that emits each dim-0 slice of `components` once.
[`TensorStridedSliceUpdate(...)`](../../raw_ops/tensorstridedsliceupdate): Assign `value` to the sliced l-value reference of `input`.
[`TensorSummary(...)`](../../raw_ops/tensorsummary): Outputs a `Summary` protocol buffer with a tensor.
[`TensorSummaryV2(...)`](../../raw_ops/tensorsummaryv2): Outputs a `Summary` protocol buffer with a tensor and per-plugin data.
[`TextLineDataset(...)`](../../raw_ops/textlinedataset): Creates a dataset that emits the lines of one or more text files.
[`TextLineReader(...)`](../../raw_ops/textlinereader): A Reader that outputs the lines of a file delimited by '\n'.
[`TextLineReaderV2(...)`](../../raw_ops/textlinereaderv2): A Reader that outputs the lines of a file delimited by '\n'.
[`ThreadPoolDataset(...)`](../../raw_ops/threadpooldataset): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`ThreadPoolHandle(...)`](../../raw_ops/threadpoolhandle): Creates a dataset that uses a custom thread pool to compute `input_dataset`.
[`ThreadUnsafeUnigramCandidateSampler(...)`](../../raw_ops/threadunsafeunigramcandidatesampler): Generates labels for candidate sampling with a learned unigram distribution.
[`Tile(...)`](../../raw_ops/tile): Constructs a tensor by tiling a given tensor.
[`TileGrad(...)`](../../raw_ops/tilegrad): Returns the gradient of `Tile`.
[`Timestamp(...)`](../../raw_ops/timestamp): Provides the time since epoch in seconds.
[`ToBool(...)`](../../raw_ops/tobool): Converts a tensor to a scalar predicate.
[`TopK(...)`](../../raw_ops/topk): Finds values and indices of the `k` largest elements for the last dimension.
[`TopKV2(...)`](../../raw_ops/topkv2): Finds values and indices of the `k` largest elements for the last dimension.
[`Transpose(...)`](../../raw_ops/transpose): Shuffle dimensions of x according to a permutation.
[`TridiagonalMatMul(...)`](../../raw_ops/tridiagonalmatmul): Calculate product with tridiagonal matrix.
[`TridiagonalSolve(...)`](../../raw_ops/tridiagonalsolve): Solves tridiagonal systems of equations.
[`TruncateDiv(...)`](../../raw_ops/truncatediv): Returns x / y element-wise for integer types.
[`TruncateMod(...)`](../../raw_ops/truncatemod): Returns element-wise remainder of division. This emulates C semantics in that
[`TruncatedNormal(...)`](../../raw_ops/truncatednormal): Outputs random values from a truncated normal distribution.
[`Unbatch(...)`](../../raw_ops/unbatch): Reverses the operation of Batch for a single output Tensor.
[`UnbatchDataset(...)`](../../raw_ops/unbatchdataset): A dataset that splits the elements of its input into multiple elements.
[`UnbatchGrad(...)`](../../raw_ops/unbatchgrad): Gradient of Unbatch.
[`UncompressElement(...)`](../../raw_ops/uncompresselement): Uncompresses a compressed dataset element.
[`UnicodeDecode(...)`](../../raw_ops/unicodedecode): Decodes each string in `input` into a sequence of Unicode code points.
[`UnicodeDecodeWithOffsets(...)`](../../raw_ops/unicodedecodewithoffsets): Decodes each string in `input` into a sequence of Unicode code points.
[`UnicodeEncode(...)`](../../raw_ops/unicodeencode): Encode a tensor of ints into unicode strings.
[`UnicodeScript(...)`](../../raw_ops/unicodescript): Determine the script codes of a given tensor of Unicode integer code points.
[`UnicodeTranscode(...)`](../../raw_ops/unicodetranscode): Transcode the input text from a source encoding to a destination encoding.
[`UniformCandidateSampler(...)`](../../raw_ops/uniformcandidatesampler): Generates labels for candidate sampling with a uniform distribution.
[`Unique(...)`](../../raw_ops/unique): Finds unique elements in a 1-D tensor.
[`UniqueDataset(...)`](../../raw_ops/uniquedataset): Creates a dataset that contains the unique elements of `input_dataset`.
[`UniqueV2(...)`](../../raw_ops/uniquev2): Finds unique elements along an axis of a tensor.
[`UniqueWithCounts(...)`](../../raw_ops/uniquewithcounts): Finds unique elements in a 1-D tensor.
[`UniqueWithCountsV2(...)`](../../raw_ops/uniquewithcountsv2): Finds unique elements along an axis of a tensor.
[`Unpack(...)`](../../raw_ops/unpack): Unpacks a given dimension of a rank-`R` tensor into `num` rank-`(R-1)` tensors.
[`UnravelIndex(...)`](../../raw_ops/unravelindex): Converts an array of flat indices into a tuple of coordinate arrays.
[`UnsortedSegmentJoin(...)`](../../raw_ops/unsortedsegmentjoin): Joins the elements of `inputs` based on `segment_ids`.
[`UnsortedSegmentMax(...)`](../../raw_ops/unsortedsegmentmax): Computes the maximum along segments of a tensor.
[`UnsortedSegmentMin(...)`](../../raw_ops/unsortedsegmentmin): Computes the minimum along segments of a tensor.
[`UnsortedSegmentProd(...)`](../../raw_ops/unsortedsegmentprod): Computes the product along segments of a tensor.
[`UnsortedSegmentSum(...)`](../../raw_ops/unsortedsegmentsum): Computes the sum along segments of a tensor.
[`Unstage(...)`](../../raw_ops/unstage): Op is similar to a lightweight Dequeue.
[`UnwrapDatasetVariant(...)`](../../raw_ops/unwrapdatasetvariant)
[`UpperBound(...)`](../../raw_ops/upperbound): Applies upper\_bound(sorted\_search\_values, values) along each row.
[`VarHandleOp(...)`](../../raw_ops/varhandleop): Creates a handle to a Variable resource.
[`VarIsInitializedOp(...)`](../../raw_ops/varisinitializedop): Checks whether a resource handle-based variable has been initialized.
[`Variable(...)`](../../raw_ops/variable): Use VariableV2 instead.
[`VariableShape(...)`](../../raw_ops/variableshape): Returns the shape of the variable pointed to by `resource`.
[`VariableV2(...)`](../../raw_ops/variablev2): Holds state in the form of a tensor that persists across steps.
[`Where(...)`](../../raw_ops/where): Returns locations of nonzero / true values in a tensor.
[`While(...)`](../../raw_ops/while): output = input; While (Cond(output)) { output = Body(output) }
[`WholeFileReader(...)`](../../raw_ops/wholefilereader): A Reader that outputs the entire contents of a file as a value.
[`WholeFileReaderV2(...)`](../../raw_ops/wholefilereaderv2): A Reader that outputs the entire contents of a file as a value.
[`WindowDataset(...)`](../../raw_ops/windowdataset): Combines (nests of) input elements into a dataset of (nests of) windows.
[`WindowOp(...)`](../../raw_ops/windowop)
[`WorkerHeartbeat(...)`](../../raw_ops/workerheartbeat): Worker heartbeat op.
[`WrapDatasetVariant(...)`](../../raw_ops/wrapdatasetvariant)
[`WriteAudioSummary(...)`](../../raw_ops/writeaudiosummary): Writes an audio summary.
[`WriteFile(...)`](../../raw_ops/writefile): Writes `contents` to the file at input `filename`.
[`WriteGraphSummary(...)`](../../raw_ops/writegraphsummary): Writes a graph summary.
[`WriteHistogramSummary(...)`](../../raw_ops/writehistogramsummary): Writes a histogram summary.
[`WriteImageSummary(...)`](../../raw_ops/writeimagesummary): Writes an image summary.
[`WriteRawProtoSummary(...)`](../../raw_ops/writerawprotosummary): Writes a serialized proto summary.
[`WriteScalarSummary(...)`](../../raw_ops/writescalarsummary): Writes a scalar summary.
[`WriteSummary(...)`](../../raw_ops/writesummary): Writes a tensor summary.
[`Xdivy(...)`](../../raw_ops/xdivy): Returns 0 if x == 0, and x / y otherwise, elementwise.
[`XlaConcatND(...)`](../../raw_ops/xlaconcatnd): Concats input tensor across all dimensions.
[`XlaSplitND(...)`](../../raw_ops/xlasplitnd): Splits input tensor across all dimensions.
[`Xlog1py(...)`](../../raw_ops/xlog1py): Returns 0 if x == 0, and x \* log1p(y) otherwise, elementwise.
[`Xlogy(...)`](../../raw_ops/xlogy): Returns 0 if x == 0, and x \* log(y) otherwise, elementwise.
[`ZerosLike(...)`](../../raw_ops/zeroslike): Returns a tensor of zeros with the same shape and type as x.
[`Zeta(...)`](../../raw_ops/zeta): Compute the Hurwitz zeta function \(\zeta(x, q)\).
[`ZipDataset(...)`](../../raw_ops/zipdataset): Creates a dataset that zips together `input_datasets`.
| programming_docs |
tensorflow Module: tf.compat.v1.tpu Module: tf.compat.v1.tpu
========================
Ops related to Tensor Processing Units.
Modules
-------
[`experimental`](tpu/experimental) module: Public API for tf.tpu.experimental namespace.
Classes
-------
[`class CrossShardOptimizer`](tpu/crossshardoptimizer): An optimizer that averages gradients across TPU shards.
[`class PaddingSpec`](tpu/paddingspec): Represents the type of padding policies for tpu.replicate.
[`class XLAOptions`](../../tpu/xlaoptions): XLA compilation options.
Functions
---------
[`batch_parallel(...)`](tpu/batch_parallel): Shards `computation` along the batch dimension for parallel execution.
[`bfloat16_scope(...)`](tpu/bfloat16_scope): Scope class for bfloat16 variables so that the model uses custom getter.
[`core(...)`](tpu/core): Returns the device name for a core in a replicated TPU computation.
[`cross_replica_sum(...)`](tpu/cross_replica_sum): Sum the input tensor across replicas according to group\_assignment.
[`initialize_system(...)`](tpu/initialize_system): Initializes a distributed TPU system for use with TensorFlow.
[`outside_compilation(...)`](tpu/outside_compilation): Builds part of a computation outside any current TPU replicate scope.
[`replicate(...)`](tpu/replicate): Builds a graph operator that runs a replicated TPU computation.
[`rewrite(...)`](tpu/rewrite): Rewrites `computation` for execution on a TPU system.
[`shard(...)`](tpu/shard): Shards `computation` for parallel execution.
[`shutdown_system(...)`](tpu/shutdown_system): Shuts down a running a distributed TPU system.
tensorflow tf.compat.v1.assert_equal tf.compat.v1.assert\_equal
==========================
Assert the condition `x == y` holds element-wise.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.debugging.assert_equal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/assert_equal)
```
tf.compat.v1.assert_equal(
x, y, data=None, summarize=None, message=None, name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.assert_equal`](assert_equal) is compatible with eager execution and [`tf.function`](../../function). Please use [`tf.debugging.assert_equal`](../../debugging/assert_equal) instead when migrating to TF2. Apart from `data`, all arguments are supported with the same argument name.
If you want to ensure the assert statements run before the potentially-invalid computation, please use [`tf.control_dependencies`](../../control_dependencies), as tf.function auto-control dependencies are insufficient for assert statements.
#### Structural Mapping to Native TF2
Before:
```
tf.compat.v1.assert_equal(
x=x, y=y, data=data, summarize=summarize,
message=message, name=name)
```
After:
```
tf.debugging.assert_equal(
x=x, y=y, message=message,
summarize=summarize, name=name)
```
#### TF1 & TF2 Usage Example
TF1:
```
g = tf.Graph()
with g.as_default():
a = tf.compat.v1.placeholder(tf.float32, [2])
b = tf.compat.v1.placeholder(tf.float32, [2])
result = tf.compat.v1.assert_equal(a, b,
message='"a == b" does not hold for the given inputs')
with tf.compat.v1.control_dependencies([result]):
sum_node = a + b
sess = tf.compat.v1.Session(graph=g)
val = sess.run(sum_node, feed_dict={a: [1, 2], b:[1, 2]})
```
TF2:
```
a = tf.Variable([1, 2], dtype=tf.float32)
b = tf.Variable([1, 2], dtype=tf.float32)
assert_op = tf.debugging.assert_equal(a, b, message=
'"a == b" does not hold for the given inputs')
# When working with tf.control_dependencies
with tf.control_dependencies([assert_op]):
val = a + b
```
Description
-----------
This condition holds if for every pair of (possibly broadcast) elements `x[i]`, `y[i]`, we have `x[i] == y[i]`. If both `x` and `y` are empty, this is trivially satisfied.
When running in graph mode, you should add a dependency on this operation to ensure that it runs. Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.compat.v1.assert_equal(x, y)]):
output = tf.reduce_sum(x)
```
| Args |
| `x` | Numeric `Tensor`. |
| `y` | Numeric `Tensor`, same dtype as and broadcastable to `x`. |
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of `x`, `y`. |
| `summarize` | Print this many entries of each tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_equal". |
| Returns |
| Op that raises `InvalidArgumentError` if `x == y` is False. |
| Raises |
| `InvalidArgumentError` | if the check can be performed immediately and `x == y` is False. The check can be performed immediately during eager execution or if `x` and `y` are statically known. |
tensorflow Module: tf.compat.v1.metrics Module: tf.compat.v1.metrics
============================
Evaluation-related metrics.
Functions
---------
[`accuracy(...)`](metrics/accuracy): Calculates how often `predictions` matches `labels`.
[`auc(...)`](metrics/auc): Computes the approximate AUC via a Riemann sum. (deprecated)
[`average_precision_at_k(...)`](metrics/average_precision_at_k): Computes average precision@k of predictions with respect to sparse labels.
[`false_negatives(...)`](metrics/false_negatives): Computes the total number of false negatives.
[`false_negatives_at_thresholds(...)`](metrics/false_negatives_at_thresholds): Computes false negatives at provided threshold values.
[`false_positives(...)`](metrics/false_positives): Sum the weights of false positives.
[`false_positives_at_thresholds(...)`](metrics/false_positives_at_thresholds): Computes false positives at provided threshold values.
[`mean(...)`](metrics/mean): Computes the (weighted) mean of the given values.
[`mean_absolute_error(...)`](metrics/mean_absolute_error): Computes the mean absolute error between the labels and predictions.
[`mean_cosine_distance(...)`](metrics/mean_cosine_distance): Computes the cosine distance between the labels and predictions.
[`mean_iou(...)`](metrics/mean_iou): Calculate per-step mean Intersection-Over-Union (mIOU).
[`mean_per_class_accuracy(...)`](metrics/mean_per_class_accuracy): Calculates the mean of the per-class accuracies.
[`mean_relative_error(...)`](metrics/mean_relative_error): Computes the mean relative error by normalizing with the given values.
[`mean_squared_error(...)`](metrics/mean_squared_error): Computes the mean squared error between the labels and predictions.
[`mean_tensor(...)`](metrics/mean_tensor): Computes the element-wise (weighted) mean of the given tensors.
[`percentage_below(...)`](metrics/percentage_below): Computes the percentage of values less than the given threshold.
[`precision(...)`](metrics/precision): Computes the precision of the predictions with respect to the labels.
[`precision_at_k(...)`](metrics/precision_at_k): Computes precision@k of the predictions with respect to sparse labels.
[`precision_at_thresholds(...)`](metrics/precision_at_thresholds): Computes precision values for different `thresholds` on `predictions`.
[`precision_at_top_k(...)`](metrics/precision_at_top_k): Computes precision@k of the predictions with respect to sparse labels.
[`recall(...)`](metrics/recall): Computes the recall of the predictions with respect to the labels.
[`recall_at_k(...)`](metrics/recall_at_k): Computes recall@k of the predictions with respect to sparse labels.
[`recall_at_thresholds(...)`](metrics/recall_at_thresholds): Computes various recall values for different `thresholds` on `predictions`.
[`recall_at_top_k(...)`](metrics/recall_at_top_k): Computes recall@k of top-k predictions with respect to sparse labels.
[`root_mean_squared_error(...)`](metrics/root_mean_squared_error): Computes the root mean squared error between the labels and predictions.
[`sensitivity_at_specificity(...)`](metrics/sensitivity_at_specificity): Computes the specificity at a given sensitivity.
[`sparse_average_precision_at_k(...)`](metrics/sparse_average_precision_at_k): Renamed to `average_precision_at_k`, please use that method instead. (deprecated)
[`sparse_precision_at_k(...)`](metrics/sparse_precision_at_k): Renamed to `precision_at_k`, please use that method instead. (deprecated)
[`specificity_at_sensitivity(...)`](metrics/specificity_at_sensitivity): Computes the specificity at a given sensitivity.
[`true_negatives(...)`](metrics/true_negatives): Sum the weights of true\_negatives.
[`true_negatives_at_thresholds(...)`](metrics/true_negatives_at_thresholds): Computes true negatives at provided threshold values.
[`true_positives(...)`](metrics/true_positives): Sum the weights of true\_positives.
[`true_positives_at_thresholds(...)`](metrics/true_positives_at_thresholds): Computes true positives at provided threshold values.
tensorflow tf.compat.v1.variable_axis_size_partitioner tf.compat.v1.variable\_axis\_size\_partitioner
==============================================
Get a partitioner for VariableScope to keep shards below `max_shard_bytes`.
```
tf.compat.v1.variable_axis_size_partitioner(
max_shard_bytes, axis=0, bytes_per_string_element=16, max_shards=None
)
```
This partitioner will shard a Variable along one axis, attempting to keep the maximum shard size below `max_shard_bytes`. In practice, this is not always possible when sharding along only one axis. When this happens, this axis is sharded as much as possible (i.e., every dimension becomes a separate shard).
If the partitioner hits the `max_shards` limit, then each shard may end up larger than `max_shard_bytes`. By default `max_shards` equals `None` and no limit on the number of shards is enforced.
One reasonable value for `max_shard_bytes` is `(64 << 20) - 1`, or almost `64MB`, to keep below the protobuf byte limit.
| Args |
| `max_shard_bytes` | The maximum size any given shard is allowed to be. |
| `axis` | The axis to partition along. Default: outermost axis. |
| `bytes_per_string_element` | If the `Variable` is of type string, this provides an estimate of how large each scalar in the `Variable` is. |
| `max_shards` | The maximum number of shards in int created taking precedence over `max_shard_bytes`. |
| Returns |
| A partition function usable as the `partitioner` argument to `variable_scope` and `get_variable`. |
| Raises |
| `ValueError` | If any of the byte counts are non-positive. |
tensorflow tf.compat.v1.ConfigProto tf.compat.v1.ConfigProto
========================
A ProtocolMessage
| Attributes |
| `allow_soft_placement` | `bool allow_soft_placement` |
| `cluster_def` | `ClusterDef cluster_def` |
| `device_count` | `repeated DeviceCountEntry device_count` |
| `device_filters` | `repeated string device_filters` |
| `experimental` | `Experimental experimental` |
| `gpu_options` | `GPUOptions gpu_options` |
| `graph_options` | `GraphOptions graph_options` |
| `inter_op_parallelism_threads` | `int32 inter_op_parallelism_threads` |
| `intra_op_parallelism_threads` | `int32 intra_op_parallelism_threads` |
| `isolate_session_state` | `bool isolate_session_state` |
| `log_device_placement` | `bool log_device_placement` |
| `operation_timeout_in_ms` | `int64 operation_timeout_in_ms` |
| `placement_period` | `int32 placement_period` |
| `rpc_options` | `RPCOptions rpc_options` |
| `session_inter_op_thread_pool` | `repeated ThreadPoolOptionProto session_inter_op_thread_pool` |
| `share_cluster_devices_in_session` | `bool share_cluster_devices_in_session` |
| `use_per_session_threads` | `bool use_per_session_threads` |
Child Classes
-------------
[`class DeviceCountEntry`](configproto/devicecountentry)
[`class Experimental`](configproto/experimental)
tensorflow Module: tf.compat.v1.autograph.experimental Module: tf.compat.v1.autograph.experimental
===========================================
Public API for tf.autograph.experimental namespace.
Classes
-------
[`class Feature`](../../../autograph/experimental/feature): This enumeration represents optional conversion options.
Functions
---------
[`do_not_convert(...)`](../../../autograph/experimental/do_not_convert): Decorator that suppresses the conversion of a function.
[`set_loop_options(...)`](../../../autograph/experimental/set_loop_options): Specifies additional arguments to be passed to the enclosing while\_loop.
tensorflow tf.compat.v1.autograph.to_code tf.compat.v1.autograph.to\_code
===============================
Returns the source code generated by AutoGraph, as a string.
```
tf.compat.v1.autograph.to_code(
entity,
recursive=True,
arg_values=None,
arg_types=None,
indentation=' ',
experimental_optional_features=None
)
```
#### Example usage:
```
def f(x):
if x < 0:
x = -x
return x
tf.autograph.to_code(f)
"...def tf__f(x):..."
```
Also see: [`tf.autograph.to_graph`](../../../autograph/to_graph).
>
> **Note:** If a function has been decorated with [`tf.function`](../../../function), pass its underlying Python function, rather than the callable that `tf.function creates:
>
```
@tf.function
def f(x):
if x < 0:
x = -x
return x
tf.autograph.to_code(f.python_function)
"...def tf__f(x):..."
```
| Args |
| `entity` | Python callable or class. |
| `recursive` | Whether to recursively convert any functions that the converted function may call. |
| `arg_values` | Deprecated. |
| `arg_types` | Deprecated. |
| `indentation` | Deprecated. |
| `experimental_optional_features` | `None`, a tuple of, or a single [`tf.autograph.experimental.Feature`](../../../autograph/experimental/feature) value. |
| Returns |
| The converted code as string. |
tensorflow tf.compat.v1.autograph.to_graph tf.compat.v1.autograph.to\_graph
================================
Converts a Python entity into a TensorFlow graph.
```
tf.compat.v1.autograph.to_graph(
entity,
recursive=True,
arg_values=None,
arg_types=None,
experimental_optional_features=None
)
```
Also see: [`tf.autograph.to_code`](../../../autograph/to_code), [`tf.function`](../../../function).
Unlike [`tf.function`](../../../function), `to_graph` is a low-level transpiler that converts Python code to TensorFlow graph code. It does not implement any caching, variable management or create any actual ops, and is best used where greater control over the generated TensorFlow graph is desired. Another difference from [`tf.function`](../../../function) is that `to_graph` will not wrap the graph into a TensorFlow function or a Python callable. Internally, [`tf.function`](../../../function) uses `to_graph`.
*Example Usage*
```
def foo(x):
if x > 0:
y = x * x
else:
y = -x
return y
converted_foo = to_graph(foo)
x = tf.constant(1)
y = converted_foo(x) # converted_foo is a TensorFlow Op-like.
assert is_tensor(y)
```
Supported Python entities include:
* functions
* classes
* object methods
Functions are converted into new functions with converted code.
Classes are converted by generating a new class whose methods use converted code.
Methods are converted into unbound function that have an additional first argument called `self`.
| Args |
| `entity` | Python callable or class to convert. |
| `recursive` | Whether to recursively convert any functions that the converted function may call. |
| `arg_values` | Deprecated. |
| `arg_types` | Deprecated. |
| `experimental_optional_features` | `None`, a tuple of, or a single [`tf.autograph.experimental.Feature`](../../../autograph/experimental/feature) value. |
| Returns |
| Same as `entity`, the converted Python function or class. |
| Raises |
| `ValueError` | If the entity could not be converted. |
tensorflow Module: tf.compat.v1.xla.experimental Module: tf.compat.v1.xla.experimental
=====================================
Public API for tf.xla.experimental namespace.
Functions
---------
[`compile(...)`](../../../xla/experimental/compile): Builds an operator that compiles and runs `computation` with XLA. (deprecated)
[`jit_scope(...)`](../../../xla/experimental/jit_scope): Enable or disable JIT compilation of operators within the scope.
tensorflow Module: tf.compat.v1.keras.regularizers Module: tf.compat.v1.keras.regularizers
=======================================
Built-in regularizers.
Classes
-------
[`class L1`](../../../keras/regularizers/l1): A regularizer that applies a L1 regularization penalty.
[`class L1L2`](../../../keras/regularizers/l1l2): A regularizer that applies both L1 and L2 regularization penalties.
[`class L2`](../../../keras/regularizers/l2): A regularizer that applies a L2 regularization penalty.
[`class Regularizer`](../../../keras/regularizers/regularizer): Regularizer base class.
[`class l1`](../../../keras/regularizers/l1): A regularizer that applies a L1 regularization penalty.
[`class l2`](../../../keras/regularizers/l2): A regularizer that applies a L2 regularization penalty.
Functions
---------
[`deserialize(...)`](../../../keras/regularizers/deserialize)
[`get(...)`](../../../keras/regularizers/get): Retrieve a regularizer instance from a config or identifier.
[`l1_l2(...)`](../../../keras/regularizers/l1_l2): Create a regularizer that applies both L1 and L2 penalties.
[`serialize(...)`](../../../keras/regularizers/serialize)
tensorflow Module: tf.compat.v1.keras.layers Module: tf.compat.v1.keras.layers
=================================
Keras layers API.
Modules
-------
[`experimental`](layers/experimental) module: Public API for tf.keras.layers.experimental namespace.
Classes
-------
[`class AbstractRNNCell`](../../../keras/layers/abstractrnncell): Abstract object representing an RNN cell.
[`class Activation`](../../../keras/layers/activation): Applies an activation function to an output.
[`class ActivityRegularization`](../../../keras/layers/activityregularization): Layer that applies an update to the cost function based input activity.
[`class Add`](../../../keras/layers/add): Layer that adds a list of inputs.
[`class AdditiveAttention`](../../../keras/layers/additiveattention): Additive attention layer, a.k.a. Bahdanau-style attention.
[`class AlphaDropout`](../../../keras/layers/alphadropout): Applies Alpha Dropout to the input.
[`class Attention`](../../../keras/layers/attention): Dot-product attention layer, a.k.a. Luong-style attention.
[`class Average`](../../../keras/layers/average): Layer that averages a list of inputs element-wise.
[`class AveragePooling1D`](../../../keras/layers/averagepooling1d): Average pooling for temporal data.
[`class AveragePooling2D`](../../../keras/layers/averagepooling2d): Average pooling operation for spatial data.
[`class AveragePooling3D`](../../../keras/layers/averagepooling3d): Average pooling operation for 3D data (spatial or spatio-temporal).
[`class AvgPool1D`](../../../keras/layers/averagepooling1d): Average pooling for temporal data.
[`class AvgPool2D`](../../../keras/layers/averagepooling2d): Average pooling operation for spatial data.
[`class AvgPool3D`](../../../keras/layers/averagepooling3d): Average pooling operation for 3D data (spatial or spatio-temporal).
[`class BatchNormalization`](layers/batchnormalization): Layer that normalizes its inputs.
[`class Bidirectional`](../../../keras/layers/bidirectional): Bidirectional wrapper for RNNs.
[`class CategoryEncoding`](../../../keras/layers/categoryencoding): A preprocessing layer which encodes integer features.
[`class CenterCrop`](../../../keras/layers/centercrop): A preprocessing layer which crops images.
[`class Concatenate`](../../../keras/layers/concatenate): Layer that concatenates a list of inputs.
[`class Conv1D`](../../../keras/layers/conv1d): 1D convolution layer (e.g. temporal convolution).
[`class Conv1DTranspose`](../../../keras/layers/conv1dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class Conv2D`](../../../keras/layers/conv2d): 2D convolution layer (e.g. spatial convolution over images).
[`class Conv2DTranspose`](../../../keras/layers/conv2dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class Conv3D`](../../../keras/layers/conv3d): 3D convolution layer (e.g. spatial convolution over volumes).
[`class Conv3DTranspose`](../../../keras/layers/conv3dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class ConvLSTM1D`](../../../keras/layers/convlstm1d): 1D Convolutional LSTM.
[`class ConvLSTM2D`](../../../keras/layers/convlstm2d): 2D Convolutional LSTM.
[`class ConvLSTM3D`](../../../keras/layers/convlstm3d): 3D Convolutional LSTM.
[`class Convolution1D`](../../../keras/layers/conv1d): 1D convolution layer (e.g. temporal convolution).
[`class Convolution1DTranspose`](../../../keras/layers/conv1dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class Convolution2D`](../../../keras/layers/conv2d): 2D convolution layer (e.g. spatial convolution over images).
[`class Convolution2DTranspose`](../../../keras/layers/conv2dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class Convolution3D`](../../../keras/layers/conv3d): 3D convolution layer (e.g. spatial convolution over volumes).
[`class Convolution3DTranspose`](../../../keras/layers/conv3dtranspose): Transposed convolution layer (sometimes called Deconvolution).
[`class Cropping1D`](../../../keras/layers/cropping1d): Cropping layer for 1D input (e.g. temporal sequence).
[`class Cropping2D`](../../../keras/layers/cropping2d): Cropping layer for 2D input (e.g. picture).
[`class Cropping3D`](../../../keras/layers/cropping3d): Cropping layer for 3D data (e.g. spatial or spatio-temporal).
[`class CuDNNGRU`](layers/cudnngru): Fast GRU implementation backed by cuDNN.
[`class CuDNNLSTM`](layers/cudnnlstm): Fast LSTM implementation backed by cuDNN.
[`class Dense`](../../../keras/layers/dense): Just your regular densely-connected NN layer.
[`class DenseFeatures`](layers/densefeatures): A layer that produces a dense `Tensor` based on given `feature_columns`.
[`class DepthwiseConv1D`](../../../keras/layers/depthwiseconv1d): Depthwise 1D convolution.
[`class DepthwiseConv2D`](../../../keras/layers/depthwiseconv2d): Depthwise 2D convolution.
[`class Discretization`](../../../keras/layers/discretization): A preprocessing layer which buckets continuous features by ranges.
[`class Dot`](../../../keras/layers/dot): Layer that computes a dot product between samples in two tensors.
[`class Dropout`](../../../keras/layers/dropout): Applies Dropout to the input.
[`class ELU`](../../../keras/layers/elu): Exponential Linear Unit.
[`class Embedding`](../../../keras/layers/embedding): Turns positive integers (indexes) into dense vectors of fixed size.
[`class Flatten`](../../../keras/layers/flatten): Flattens the input. Does not affect the batch size.
[`class GRU`](layers/gru): Gated Recurrent Unit - Cho et al. 2014.
[`class GRUCell`](layers/grucell): Cell class for the GRU layer.
[`class GaussianDropout`](../../../keras/layers/gaussiandropout): Apply multiplicative 1-centered Gaussian noise.
[`class GaussianNoise`](../../../keras/layers/gaussiannoise): Apply additive zero-centered Gaussian noise.
[`class GlobalAveragePooling1D`](../../../keras/layers/globalaveragepooling1d): Global average pooling operation for temporal data.
[`class GlobalAveragePooling2D`](../../../keras/layers/globalaveragepooling2d): Global average pooling operation for spatial data.
[`class GlobalAveragePooling3D`](../../../keras/layers/globalaveragepooling3d): Global Average pooling operation for 3D data.
[`class GlobalAvgPool1D`](../../../keras/layers/globalaveragepooling1d): Global average pooling operation for temporal data.
[`class GlobalAvgPool2D`](../../../keras/layers/globalaveragepooling2d): Global average pooling operation for spatial data.
[`class GlobalAvgPool3D`](../../../keras/layers/globalaveragepooling3d): Global Average pooling operation for 3D data.
[`class GlobalMaxPool1D`](../../../keras/layers/globalmaxpool1d): Global max pooling operation for 1D temporal data.
[`class GlobalMaxPool2D`](../../../keras/layers/globalmaxpool2d): Global max pooling operation for spatial data.
[`class GlobalMaxPool3D`](../../../keras/layers/globalmaxpool3d): Global Max pooling operation for 3D data.
[`class GlobalMaxPooling1D`](../../../keras/layers/globalmaxpool1d): Global max pooling operation for 1D temporal data.
[`class GlobalMaxPooling2D`](../../../keras/layers/globalmaxpool2d): Global max pooling operation for spatial data.
[`class GlobalMaxPooling3D`](../../../keras/layers/globalmaxpool3d): Global Max pooling operation for 3D data.
[`class Hashing`](../../../keras/layers/hashing): A preprocessing layer which hashes and bins categorical features.
[`class InputLayer`](../../../keras/layers/inputlayer): Layer to be used as an entry point into a Network (a graph of layers).
[`class InputSpec`](../../../keras/layers/inputspec): Specifies the rank, dtype and shape of every input to a layer.
[`class LSTM`](layers/lstm): Long Short-Term Memory layer - Hochreiter 1997.
[`class LSTMCell`](layers/lstmcell): Cell class for the LSTM layer.
[`class Lambda`](../../../keras/layers/lambda): Wraps arbitrary expressions as a `Layer` object.
[`class Layer`](../../../keras/layers/layer): This is the class from which all layers inherit.
[`class LayerNormalization`](../../../keras/layers/layernormalization): Layer normalization layer (Ba et al., 2016).
[`class LeakyReLU`](../../../keras/layers/leakyrelu): Leaky version of a Rectified Linear Unit.
[`class LocallyConnected1D`](../../../keras/layers/locallyconnected1d): Locally-connected layer for 1D inputs.
[`class LocallyConnected2D`](../../../keras/layers/locallyconnected2d): Locally-connected layer for 2D inputs.
[`class Masking`](../../../keras/layers/masking): Masks a sequence by using a mask value to skip timesteps.
[`class MaxPool1D`](../../../keras/layers/maxpool1d): Max pooling operation for 1D temporal data.
[`class MaxPool2D`](../../../keras/layers/maxpool2d): Max pooling operation for 2D spatial data.
[`class MaxPool3D`](../../../keras/layers/maxpool3d): Max pooling operation for 3D data (spatial or spatio-temporal).
[`class MaxPooling1D`](../../../keras/layers/maxpool1d): Max pooling operation for 1D temporal data.
[`class MaxPooling2D`](../../../keras/layers/maxpool2d): Max pooling operation for 2D spatial data.
[`class MaxPooling3D`](../../../keras/layers/maxpool3d): Max pooling operation for 3D data (spatial or spatio-temporal).
[`class Maximum`](../../../keras/layers/maximum): Layer that computes the maximum (element-wise) a list of inputs.
[`class Minimum`](../../../keras/layers/minimum): Layer that computes the minimum (element-wise) a list of inputs.
[`class MultiHeadAttention`](../../../keras/layers/multiheadattention): MultiHeadAttention layer.
[`class Multiply`](../../../keras/layers/multiply): Layer that multiplies (element-wise) a list of inputs.
[`class Normalization`](../../../keras/layers/normalization): A preprocessing layer which normalizes continuous features.
[`class PReLU`](../../../keras/layers/prelu): Parametric Rectified Linear Unit.
[`class Permute`](../../../keras/layers/permute): Permutes the dimensions of the input according to a given pattern.
[`class RNN`](../../../keras/layers/rnn): Base class for recurrent layers.
[`class ReLU`](../../../keras/layers/relu): Rectified Linear Unit activation function.
[`class RepeatVector`](../../../keras/layers/repeatvector): Repeats the input n times.
[`class Rescaling`](../../../keras/layers/rescaling): A preprocessing layer which rescales input values to a new range.
[`class Reshape`](../../../keras/layers/reshape): Layer that reshapes inputs into the given shape.
[`class Resizing`](../../../keras/layers/resizing): A preprocessing layer which resizes images.
[`class SeparableConv1D`](../../../keras/layers/separableconv1d): Depthwise separable 1D convolution.
[`class SeparableConv2D`](../../../keras/layers/separableconv2d): Depthwise separable 2D convolution.
[`class SeparableConvolution1D`](../../../keras/layers/separableconv1d): Depthwise separable 1D convolution.
[`class SeparableConvolution2D`](../../../keras/layers/separableconv2d): Depthwise separable 2D convolution.
[`class SimpleRNN`](../../../keras/layers/simplernn): Fully-connected RNN where the output is to be fed back to input.
[`class SimpleRNNCell`](../../../keras/layers/simplernncell): Cell class for SimpleRNN.
[`class Softmax`](../../../keras/layers/softmax): Softmax activation function.
[`class SpatialDropout1D`](../../../keras/layers/spatialdropout1d): Spatial 1D version of Dropout.
[`class SpatialDropout2D`](../../../keras/layers/spatialdropout2d): Spatial 2D version of Dropout.
[`class SpatialDropout3D`](../../../keras/layers/spatialdropout3d): Spatial 3D version of Dropout.
[`class StackedRNNCells`](../../../keras/layers/stackedrnncells): Wrapper allowing a stack of RNN cells to behave as a single cell.
[`class Subtract`](../../../keras/layers/subtract): Layer that subtracts two inputs.
[`class ThresholdedReLU`](../../../keras/layers/thresholdedrelu): Thresholded Rectified Linear Unit.
[`class TimeDistributed`](../../../keras/layers/timedistributed): This wrapper allows to apply a layer to every temporal slice of an input.
[`class UpSampling1D`](../../../keras/layers/upsampling1d): Upsampling layer for 1D inputs.
[`class UpSampling2D`](../../../keras/layers/upsampling2d): Upsampling layer for 2D inputs.
[`class UpSampling3D`](../../../keras/layers/upsampling3d): Upsampling layer for 3D inputs.
[`class Wrapper`](../../../keras/layers/wrapper): Abstract wrapper base class.
[`class ZeroPadding1D`](../../../keras/layers/zeropadding1d): Zero-padding layer for 1D input (e.g. temporal sequence).
[`class ZeroPadding2D`](../../../keras/layers/zeropadding2d): Zero-padding layer for 2D input (e.g. picture).
[`class ZeroPadding3D`](../../../keras/layers/zeropadding3d): Zero-padding layer for 3D data (spatial or spatio-temporal).
Functions
---------
[`Input(...)`](../../../keras/input): `Input()` is used to instantiate a Keras tensor.
[`add(...)`](../../../keras/layers/add): Functional interface to the [`tf.keras.layers.Add`](../../../keras/layers/add) layer.
[`average(...)`](../../../keras/layers/average): Functional interface to the [`tf.keras.layers.Average`](../../../keras/layers/average) layer.
[`concatenate(...)`](../../../keras/layers/concatenate): Functional interface to the `Concatenate` layer.
[`deserialize(...)`](../../../keras/layers/deserialize): Instantiates a layer from a config dictionary.
[`disable_v2_dtype_behavior(...)`](layers/disable_v2_dtype_behavior): Disables the V2 dtype behavior for Keras layers.
[`dot(...)`](../../../keras/layers/dot): Functional interface to the `Dot` layer.
[`enable_v2_dtype_behavior(...)`](layers/enable_v2_dtype_behavior): Enable the V2 dtype behavior for Keras layers.
[`maximum(...)`](../../../keras/layers/maximum): Functional interface to compute maximum (element-wise) list of `inputs`.
[`minimum(...)`](../../../keras/layers/minimum): Functional interface to the `Minimum` layer.
[`multiply(...)`](../../../keras/layers/multiply): Functional interface to the `Multiply` layer.
[`serialize(...)`](../../../keras/layers/serialize): Serializes a `Layer` object into a JSON-compatible representation.
[`subtract(...)`](../../../keras/layers/subtract): Functional interface to the `Subtract` layer.
| programming_docs |
tensorflow Module: tf.compat.v1.keras.backend Module: tf.compat.v1.keras.backend
==================================
Keras backend API.
Classes
-------
[`class name_scope`](backend/name_scope): A context manager for use when defining a Python op.
Functions
---------
[`clear_session(...)`](../../../keras/backend/clear_session): Resets all state generated by Keras.
[`epsilon(...)`](../../../keras/backend/epsilon): Returns the value of the fuzz factor used in numeric expressions.
[`floatx(...)`](../../../keras/backend/floatx): Returns the default float type, as a string.
[`get_session(...)`](backend/get_session): Returns the TF session to be used by the backend.
[`get_uid(...)`](../../../keras/backend/get_uid): Associates a string prefix with an integer counter in a TensorFlow graph.
[`image_data_format(...)`](../../../keras/backend/image_data_format): Returns the default image data format convention.
[`is_keras_tensor(...)`](../../../keras/backend/is_keras_tensor): Returns whether `x` is a Keras tensor.
[`reset_uids(...)`](../../../keras/backend/reset_uids): Resets graph identifiers.
[`rnn(...)`](../../../keras/backend/rnn): Iterates over the time dimension of a tensor.
[`set_epsilon(...)`](../../../keras/backend/set_epsilon): Sets the value of the fuzz factor used in numeric expressions.
[`set_floatx(...)`](../../../keras/backend/set_floatx): Sets the default float type.
[`set_image_data_format(...)`](../../../keras/backend/set_image_data_format): Sets the value of the image data format convention.
[`set_session(...)`](backend/set_session): Sets the global TensorFlow session.
tensorflow Module: tf.compat.v1.keras.preprocessing Module: tf.compat.v1.keras.preprocessing
========================================
Utilities to preprocess data before training.
Modules
-------
[`image`](preprocessing/image) module: Utilies for image preprocessing and augmentation.
[`sequence`](preprocessing/sequence) module: Utilities for preprocessing sequence data.
[`text`](preprocessing/text) module: Utilities for text input preprocessing.
tensorflow Module: tf.compat.v1.keras.callbacks Module: tf.compat.v1.keras.callbacks
====================================
Callbacks: utilities called at certain points during model training.
Classes
-------
[`class BaseLogger`](../../../keras/callbacks/baselogger): Callback that accumulates epoch averages of metrics.
[`class CSVLogger`](../../../keras/callbacks/csvlogger): Callback that streams epoch results to a CSV file.
[`class Callback`](../../../keras/callbacks/callback): Abstract base class used to build new callbacks.
[`class CallbackList`](../../../keras/callbacks/callbacklist): Container abstracting a list of callbacks.
[`class EarlyStopping`](../../../keras/callbacks/earlystopping): Stop training when a monitored metric has stopped improving.
[`class History`](../../../keras/callbacks/history): Callback that records events into a `History` object.
[`class LambdaCallback`](../../../keras/callbacks/lambdacallback): Callback for creating simple, custom callbacks on-the-fly.
[`class LearningRateScheduler`](../../../keras/callbacks/learningratescheduler): Learning rate scheduler.
[`class ModelCheckpoint`](../../../keras/callbacks/modelcheckpoint): Callback to save the Keras model or model weights at some frequency.
[`class ProgbarLogger`](../../../keras/callbacks/progbarlogger): Callback that prints metrics to stdout.
[`class ReduceLROnPlateau`](../../../keras/callbacks/reducelronplateau): Reduce learning rate when a metric has stopped improving.
[`class RemoteMonitor`](../../../keras/callbacks/remotemonitor): Callback used to stream events to a server.
[`class TensorBoard`](callbacks/tensorboard): Enable visualizations for TensorBoard.
[`class TerminateOnNaN`](../../../keras/callbacks/terminateonnan): Callback that terminates training when a NaN loss is encountered.
tensorflow Module: tf.compat.v1.keras.constraints Module: tf.compat.v1.keras.constraints
======================================
Constraints: functions that impose constraints on weight values.
Classes
-------
[`class Constraint`](../../../keras/constraints/constraint): Base class for weight constraints.
[`class MaxNorm`](../../../keras/constraints/maxnorm): MaxNorm weight constraint.
[`class MinMaxNorm`](../../../keras/constraints/minmaxnorm): MinMaxNorm weight constraint.
[`class NonNeg`](../../../keras/constraints/nonneg): Constrains the weights to be non-negative.
[`class RadialConstraint`](../../../keras/constraints/radialconstraint): Constrains `Conv2D` kernel weights to be the same for each radius.
[`class UnitNorm`](../../../keras/constraints/unitnorm): Constrains the weights incident to each hidden unit to have unit norm.
[`class max_norm`](../../../keras/constraints/maxnorm): MaxNorm weight constraint.
[`class min_max_norm`](../../../keras/constraints/minmaxnorm): MinMaxNorm weight constraint.
[`class non_neg`](../../../keras/constraints/nonneg): Constrains the weights to be non-negative.
[`class radial_constraint`](../../../keras/constraints/radialconstraint): Constrains `Conv2D` kernel weights to be the same for each radius.
[`class unit_norm`](../../../keras/constraints/unitnorm): Constrains the weights incident to each hidden unit to have unit norm.
Functions
---------
[`deserialize(...)`](../../../keras/constraints/deserialize)
[`get(...)`](../../../keras/constraints/get): Retrieves a Keras constraint function.
[`serialize(...)`](../../../keras/constraints/serialize)
tensorflow Module: tf.compat.v1.keras.mixed_precision Module: tf.compat.v1.keras.mixed\_precision
===========================================
Keras mixed precision API.
See [the mixed precision guide](https://www.tensorflow.org/guide/keras/mixed_precision) to learn how to use the API.
Classes
-------
[`class LossScaleOptimizer`](../../../keras/mixed_precision/lossscaleoptimizer): An optimizer that applies loss scaling to prevent numeric underflow.
tensorflow Module: tf.compat.v1.keras.applications Module: tf.compat.v1.keras.applications
=======================================
Keras Applications are premade architectures with pre-trained weights.
Modules
-------
[`densenet`](applications/densenet) module: DenseNet models for Keras.
[`efficientnet`](applications/efficientnet) module: EfficientNet models for Keras.
[`efficientnet_v2`](applications/efficientnet_v2) module: EfficientNet V2 models for Keras.
[`imagenet_utils`](applications/imagenet_utils) module: Utilities for ImageNet data preprocessing & prediction decoding.
[`inception_resnet_v2`](applications/inception_resnet_v2) module: Inception-ResNet V2 model for Keras.
[`inception_v3`](applications/inception_v3) module: Inception V3 model for Keras.
[`mobilenet`](applications/mobilenet) module: MobileNet v1 models for Keras.
[`mobilenet_v2`](applications/mobilenet_v2) module: MobileNet v2 models for Keras.
[`mobilenet_v3`](applications/mobilenet_v3) module: MobileNet v3 models for Keras.
[`nasnet`](applications/nasnet) module: NASNet-A models for Keras.
[`regnet`](applications/regnet) module: RegNet models for Keras.
[`resnet`](applications/resnet) module: ResNet models for Keras.
[`resnet50`](applications/resnet50) module: Public API for tf.keras.applications.resnet50 namespace.
[`resnet_rs`](applications/resnet_rs) module: ResNet-RS models for Keras.
[`resnet_v2`](applications/resnet_v2) module: ResNet v2 models for Keras.
[`vgg16`](applications/vgg16) module: VGG16 model for Keras.
[`vgg19`](applications/vgg19) module: VGG19 model for Keras.
[`xception`](applications/xception) module: Xception V1 model for Keras.
Functions
---------
[`DenseNet121(...)`](../../../keras/applications/densenet/densenet121): Instantiates the Densenet121 architecture.
[`DenseNet169(...)`](../../../keras/applications/densenet/densenet169): Instantiates the Densenet169 architecture.
[`DenseNet201(...)`](../../../keras/applications/densenet/densenet201): Instantiates the Densenet201 architecture.
[`EfficientNetB0(...)`](../../../keras/applications/efficientnet/efficientnetb0): Instantiates the EfficientNetB0 architecture.
[`EfficientNetB1(...)`](../../../keras/applications/efficientnet/efficientnetb1): Instantiates the EfficientNetB1 architecture.
[`EfficientNetB2(...)`](../../../keras/applications/efficientnet/efficientnetb2): Instantiates the EfficientNetB2 architecture.
[`EfficientNetB3(...)`](../../../keras/applications/efficientnet/efficientnetb3): Instantiates the EfficientNetB3 architecture.
[`EfficientNetB4(...)`](../../../keras/applications/efficientnet/efficientnetb4): Instantiates the EfficientNetB4 architecture.
[`EfficientNetB5(...)`](../../../keras/applications/efficientnet/efficientnetb5): Instantiates the EfficientNetB5 architecture.
[`EfficientNetB6(...)`](../../../keras/applications/efficientnet/efficientnetb6): Instantiates the EfficientNetB6 architecture.
[`EfficientNetB7(...)`](../../../keras/applications/efficientnet/efficientnetb7): Instantiates the EfficientNetB7 architecture.
[`EfficientNetV2B0(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2b0): Instantiates the EfficientNetV2B0 architecture.
[`EfficientNetV2B1(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2b1): Instantiates the EfficientNetV2B1 architecture.
[`EfficientNetV2B2(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2b2): Instantiates the EfficientNetV2B2 architecture.
[`EfficientNetV2B3(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2b3): Instantiates the EfficientNetV2B3 architecture.
[`EfficientNetV2L(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2l): Instantiates the EfficientNetV2L architecture.
[`EfficientNetV2M(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2m): Instantiates the EfficientNetV2M architecture.
[`EfficientNetV2S(...)`](../../../keras/applications/efficientnet_v2/efficientnetv2s): Instantiates the EfficientNetV2S architecture.
[`InceptionResNetV2(...)`](../../../keras/applications/inception_resnet_v2/inceptionresnetv2): Instantiates the Inception-ResNet v2 architecture.
[`InceptionV3(...)`](../../../keras/applications/inception_v3/inceptionv3): Instantiates the Inception v3 architecture.
[`MobileNet(...)`](../../../keras/applications/mobilenet/mobilenet): Instantiates the MobileNet architecture.
[`MobileNetV2(...)`](../../../keras/applications/mobilenet_v2/mobilenetv2): Instantiates the MobileNetV2 architecture.
[`MobileNetV3Large(...)`](../../../keras/applications/mobilenetv3large): Instantiates the MobileNetV3Large architecture.
[`MobileNetV3Small(...)`](../../../keras/applications/mobilenetv3small): Instantiates the MobileNetV3Small architecture.
[`NASNetLarge(...)`](../../../keras/applications/nasnet/nasnetlarge): Instantiates a NASNet model in ImageNet mode.
[`NASNetMobile(...)`](../../../keras/applications/nasnet/nasnetmobile): Instantiates a Mobile NASNet model in ImageNet mode.
[`RegNetX002(...)`](../../../keras/applications/regnet/regnetx002): Instantiates the RegNetX002 architecture.
[`RegNetX004(...)`](../../../keras/applications/regnet/regnetx004): Instantiates the RegNetX004 architecture.
[`RegNetX006(...)`](../../../keras/applications/regnet/regnetx006): Instantiates the RegNetX006 architecture.
[`RegNetX008(...)`](../../../keras/applications/regnet/regnetx008): Instantiates the RegNetX008 architecture.
[`RegNetX016(...)`](../../../keras/applications/regnet/regnetx016): Instantiates the RegNetX016 architecture.
[`RegNetX032(...)`](../../../keras/applications/regnet/regnetx032): Instantiates the RegNetX032 architecture.
[`RegNetX040(...)`](../../../keras/applications/regnet/regnetx040): Instantiates the RegNetX040 architecture.
[`RegNetX064(...)`](../../../keras/applications/regnet/regnetx064): Instantiates the RegNetX064 architecture.
[`RegNetX080(...)`](../../../keras/applications/regnet/regnetx080): Instantiates the RegNetX080 architecture.
[`RegNetX120(...)`](../../../keras/applications/regnet/regnetx120): Instantiates the RegNetX120 architecture.
[`RegNetX160(...)`](../../../keras/applications/regnet/regnetx160): Instantiates the RegNetX160 architecture.
[`RegNetX320(...)`](../../../keras/applications/regnet/regnetx320): Instantiates the RegNetX320 architecture.
[`RegNetY002(...)`](../../../keras/applications/regnet/regnety002): Instantiates the RegNetY002 architecture.
[`RegNetY004(...)`](../../../keras/applications/regnet/regnety004): Instantiates the RegNetY004 architecture.
[`RegNetY006(...)`](../../../keras/applications/regnet/regnety006): Instantiates the RegNetY006 architecture.
[`RegNetY008(...)`](../../../keras/applications/regnet/regnety008): Instantiates the RegNetY008 architecture.
[`RegNetY016(...)`](../../../keras/applications/regnet/regnety016): Instantiates the RegNetY016 architecture.
[`RegNetY032(...)`](../../../keras/applications/regnet/regnety032): Instantiates the RegNetY032 architecture.
[`RegNetY040(...)`](../../../keras/applications/regnet/regnety040): Instantiates the RegNetY040 architecture.
[`RegNetY064(...)`](../../../keras/applications/regnet/regnety064): Instantiates the RegNetY064 architecture.
[`RegNetY080(...)`](../../../keras/applications/regnet/regnety080): Instantiates the RegNetY080 architecture.
[`RegNetY120(...)`](../../../keras/applications/regnet/regnety120): Instantiates the RegNetY120 architecture.
[`RegNetY160(...)`](../../../keras/applications/regnet/regnety160): Instantiates the RegNetY160 architecture.
[`RegNetY320(...)`](../../../keras/applications/regnet/regnety320): Instantiates the RegNetY320 architecture.
[`ResNet101(...)`](../../../keras/applications/resnet/resnet101): Instantiates the ResNet101 architecture.
[`ResNet101V2(...)`](../../../keras/applications/resnet_v2/resnet101v2): Instantiates the ResNet101V2 architecture.
[`ResNet152(...)`](../../../keras/applications/resnet/resnet152): Instantiates the ResNet152 architecture.
[`ResNet152V2(...)`](../../../keras/applications/resnet_v2/resnet152v2): Instantiates the ResNet152V2 architecture.
[`ResNet50(...)`](../../../keras/applications/resnet50/resnet50): Instantiates the ResNet50 architecture.
[`ResNet50V2(...)`](../../../keras/applications/resnet_v2/resnet50v2): Instantiates the ResNet50V2 architecture.
[`ResNetRS101(...)`](../../../keras/applications/resnet_rs/resnetrs101): Build ResNet-RS101 model.
[`ResNetRS152(...)`](../../../keras/applications/resnet_rs/resnetrs152): Instantiates the ResNetRS152 architecture.
[`ResNetRS200(...)`](../../../keras/applications/resnet_rs/resnetrs200): Instantiates the ResNetRS200 architecture.
[`ResNetRS270(...)`](../../../keras/applications/resnet_rs/resnetrs270): Instantiates the ResNetRS270 architecture.
[`ResNetRS350(...)`](../../../keras/applications/resnet_rs/resnetrs350): Instantiates the ResNetRS350 architecture.
[`ResNetRS420(...)`](../../../keras/applications/resnet_rs/resnetrs420): Instantiates the ResNetRS420 architecture.
[`ResNetRS50(...)`](../../../keras/applications/resnet_rs/resnetrs50): Instantiates the ResNetRS50 architecture.
[`VGG16(...)`](../../../keras/applications/vgg16/vgg16): Instantiates the VGG16 model.
[`VGG19(...)`](../../../keras/applications/vgg19/vgg19): Instantiates the VGG19 architecture.
[`Xception(...)`](../../../keras/applications/xception/xception): Instantiates the Xception architecture.
tensorflow Module: tf.compat.v1.keras.losses Module: tf.compat.v1.keras.losses
=================================
Built-in loss functions.
Classes
-------
[`class BinaryCrossentropy`](../../../keras/losses/binarycrossentropy): Computes the cross-entropy loss between true labels and predicted labels.
[`class BinaryFocalCrossentropy`](../../../keras/losses/binaryfocalcrossentropy): Computes the focal cross-entropy loss between true labels and predictions.
[`class CategoricalCrossentropy`](../../../keras/losses/categoricalcrossentropy): Computes the crossentropy loss between the labels and predictions.
[`class CategoricalHinge`](../../../keras/losses/categoricalhinge): Computes the categorical hinge loss between `y_true` and `y_pred`.
[`class CosineSimilarity`](../../../keras/losses/cosinesimilarity): Computes the cosine similarity between labels and predictions.
[`class Hinge`](../../../keras/losses/hinge): Computes the hinge loss between `y_true` and `y_pred`.
[`class Huber`](../../../keras/losses/huber): Computes the Huber loss between `y_true` and `y_pred`.
[`class KLDivergence`](../../../keras/losses/kldivergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`class LogCosh`](../../../keras/losses/logcosh): Computes the logarithm of the hyperbolic cosine of the prediction error.
[`class Loss`](../../../keras/losses/loss): Loss base class.
[`class MeanAbsoluteError`](../../../keras/losses/meanabsoluteerror): Computes the mean of absolute difference between labels and predictions.
[`class MeanAbsolutePercentageError`](../../../keras/losses/meanabsolutepercentageerror): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`class MeanSquaredError`](../../../keras/losses/meansquarederror): Computes the mean of squares of errors between labels and predictions.
[`class MeanSquaredLogarithmicError`](../../../keras/losses/meansquaredlogarithmicerror): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`class Poisson`](../../../keras/losses/poisson): Computes the Poisson loss between `y_true` and `y_pred`.
[`class SparseCategoricalCrossentropy`](../../../keras/losses/sparsecategoricalcrossentropy): Computes the crossentropy loss between the labels and predictions.
[`class SquaredHinge`](../../../keras/losses/squaredhinge): Computes the squared hinge loss between `y_true` and `y_pred`.
Functions
---------
[`KLD(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`MAE(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`MAPE(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`MSE(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`MSLE(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`binary_crossentropy(...)`](../../../keras/metrics/binary_crossentropy): Computes the binary crossentropy loss.
[`binary_focal_crossentropy(...)`](../../../keras/metrics/binary_focal_crossentropy): Computes the binary focal crossentropy loss.
[`categorical_crossentropy(...)`](../../../keras/metrics/categorical_crossentropy): Computes the categorical crossentropy loss.
[`categorical_hinge(...)`](../../../keras/losses/categorical_hinge): Computes the categorical hinge loss between `y_true` and `y_pred`.
[`cosine(...)`](../../../keras/losses/cosine_similarity): Computes the cosine similarity between labels and predictions.
[`cosine_proximity(...)`](../../../keras/losses/cosine_similarity): Computes the cosine similarity between labels and predictions.
[`cosine_similarity(...)`](../../../keras/losses/cosine_similarity): Computes the cosine similarity between labels and predictions.
[`deserialize(...)`](../../../keras/losses/deserialize): Deserializes a serialized loss class/function instance.
[`get(...)`](../../../keras/losses/get): Retrieves a Keras loss as a `function`/`Loss` class instance.
[`hinge(...)`](../../../keras/metrics/hinge): Computes the hinge loss between `y_true` and `y_pred`.
[`kl_divergence(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`kld(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`kullback_leibler_divergence(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`log_cosh(...)`](../../../keras/losses/log_cosh): Logarithm of the hyperbolic cosine of the prediction error.
[`logcosh(...)`](../../../keras/losses/log_cosh): Logarithm of the hyperbolic cosine of the prediction error.
[`mae(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`mape(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`mean_absolute_error(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`mean_absolute_percentage_error(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`mean_squared_error(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`mean_squared_logarithmic_error(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`mse(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`msle(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`poisson(...)`](../../../keras/metrics/poisson): Computes the Poisson loss between y\_true and y\_pred.
[`serialize(...)`](../../../keras/losses/serialize): Serializes loss function or `Loss` instance.
[`sparse_categorical_crossentropy(...)`](../../../keras/metrics/sparse_categorical_crossentropy): Computes the sparse categorical crossentropy loss.
[`squared_hinge(...)`](../../../keras/metrics/squared_hinge): Computes the squared hinge loss between `y_true` and `y_pred`.
| programming_docs |
tensorflow Module: tf.compat.v1.keras.utils Module: tf.compat.v1.keras.utils
================================
Public Keras utilities.
Classes
-------
[`class CustomObjectScope`](../../../keras/utils/custom_object_scope): Exposes custom classes/functions to Keras deserialization internals.
[`class DeterministicRandomTestTool`](utils/deterministicrandomtesttool): DeterministicRandomTestTool is a testing tool.
[`class GeneratorEnqueuer`](../../../keras/utils/generatorenqueuer): Builds a queue out of a data generator.
[`class OrderedEnqueuer`](../../../keras/utils/orderedenqueuer): Builds a Enqueuer from a Sequence.
[`class Progbar`](../../../keras/utils/progbar): Displays a progress bar.
[`class Sequence`](../../../keras/utils/sequence): Base object for fitting to a sequence of data, such as a dataset.
[`class SequenceEnqueuer`](../../../keras/utils/sequenceenqueuer): Base class to enqueue inputs.
[`class custom_object_scope`](../../../keras/utils/custom_object_scope): Exposes custom classes/functions to Keras deserialization internals.
Functions
---------
[`array_to_img(...)`](../../../keras/utils/array_to_img): Converts a 3D Numpy array to a PIL Image instance.
[`deserialize_keras_object(...)`](../../../keras/utils/deserialize_keras_object): Turns the serialized form of a Keras object back into an actual object.
[`disable_interactive_logging(...)`](../../../keras/utils/disable_interactive_logging): Turn off interactive logging.
[`enable_interactive_logging(...)`](../../../keras/utils/enable_interactive_logging): Turn on interactive logging.
[`get_custom_objects(...)`](../../../keras/utils/get_custom_objects): Retrieves a live reference to the global dictionary of custom objects.
[`get_file(...)`](../../../keras/utils/get_file): Downloads a file from a URL if it not already in the cache.
[`get_or_create_layer(...)`](utils/get_or_create_layer): Use this method to track nested keras models in a shim-decorated method.
[`get_registered_name(...)`](../../../keras/utils/get_registered_name): Returns the name registered to an object within the Keras framework.
[`get_registered_object(...)`](../../../keras/utils/get_registered_object): Returns the class associated with `name` if it is registered with Keras.
[`get_source_inputs(...)`](../../../keras/utils/get_source_inputs): Returns the list of input tensors necessary to compute `tensor`.
[`img_to_array(...)`](../../../keras/utils/img_to_array): Converts a PIL Image instance to a Numpy array.
[`is_interactive_logging_enabled(...)`](../../../keras/utils/is_interactive_logging_enabled): Check if interactive logging is enabled.
[`load_img(...)`](../../../keras/utils/load_img): Loads an image into PIL format.
[`model_to_dot(...)`](../../../keras/utils/model_to_dot): Convert a Keras model to dot format.
[`normalize(...)`](../../../keras/utils/normalize): Normalizes a Numpy array.
[`pad_sequences(...)`](../../../keras/utils/pad_sequences): Pads sequences to the same length.
[`plot_model(...)`](../../../keras/utils/plot_model): Converts a Keras model to dot format and save to a file.
[`register_keras_serializable(...)`](../../../keras/utils/register_keras_serializable): Registers an object with the Keras serialization framework.
[`save_img(...)`](../../../keras/utils/save_img): Saves an image stored as a Numpy array to a path or file object.
[`serialize_keras_object(...)`](../../../keras/utils/serialize_keras_object): Serialize a Keras object into a JSON-compatible representation.
[`to_categorical(...)`](../../../keras/utils/to_categorical): Converts a class vector (integers) to binary class matrix.
[`track_tf1_style_variables(...)`](utils/track_tf1_style_variables): Wrap layer & module methods in this decorator to capture tf1-style weights.
tensorflow Module: tf.compat.v1.keras.initializers Module: tf.compat.v1.keras.initializers
=======================================
Keras initializer serialization / deserialization.
Classes
-------
[`class Constant`](initializers/constant): Initializer that generates tensors with constant values.
[`class Identity`](initializers/identity): Initializer that generates the identity matrix.
[`class Initializer`](../../../keras/initializers/initializer): Initializer base class: all Keras initializers inherit from this class.
[`class Ones`](initializers/ones): Initializer that generates tensors initialized to 1.
[`class Orthogonal`](initializers/orthogonal): Initializer that generates an orthogonal matrix.
[`class RandomNormal`](initializers/randomnormal): Initializer that generates a normal distribution.
[`class RandomUniform`](initializers/randomuniform): Initializer that generates tensors with a uniform distribution.
[`class TruncatedNormal`](initializers/truncatednormal): Initializer that generates a truncated normal distribution.
[`class VarianceScaling`](initializers/variancescaling): Initializer capable of adapting its scale to the shape of weights tensors.
[`class Zeros`](initializers/zeros): Initializer that generates tensors initialized to 0.
[`class constant`](initializers/constant): Initializer that generates tensors with constant values.
[`class glorot_normal`](initializers/glorot_normal): The Glorot normal initializer, also called Xavier normal initializer.
[`class glorot_uniform`](initializers/glorot_uniform): The Glorot uniform initializer, also called Xavier uniform initializer.
[`class he_normal`](initializers/he_normal): Initializer capable of adapting its scale to the shape of weights tensors.
[`class he_uniform`](initializers/he_uniform): Initializer capable of adapting its scale to the shape of weights tensors.
[`class identity`](initializers/identity): Initializer that generates the identity matrix.
[`class lecun_normal`](initializers/lecun_normal): Initializer capable of adapting its scale to the shape of weights tensors.
[`class lecun_uniform`](initializers/lecun_uniform): Initializer capable of adapting its scale to the shape of weights tensors.
[`class normal`](initializers/randomnormal): Initializer that generates a normal distribution.
[`class ones`](initializers/ones): Initializer that generates tensors initialized to 1.
[`class orthogonal`](initializers/orthogonal): Initializer that generates an orthogonal matrix.
[`class random_normal`](initializers/randomnormal): Initializer that generates a normal distribution.
[`class random_uniform`](initializers/randomuniform): Initializer that generates tensors with a uniform distribution.
[`class truncated_normal`](initializers/truncatednormal): Initializer that generates a truncated normal distribution.
[`class uniform`](initializers/randomuniform): Initializer that generates tensors with a uniform distribution.
[`class zeros`](initializers/zeros): Initializer that generates tensors initialized to 0.
Functions
---------
[`deserialize(...)`](../../../keras/initializers/deserialize): Return an `Initializer` object from its config.
[`get(...)`](../../../keras/initializers/get): Retrieve a Keras initializer by the identifier.
[`serialize(...)`](../../../keras/initializers/serialize)
tensorflow Module: tf.compat.v1.keras.datasets Module: tf.compat.v1.keras.datasets
===================================
Small NumPy datasets for debugging/testing.
Modules
-------
[`boston_housing`](datasets/boston_housing) module: Boston housing price regression dataset.
[`cifar10`](datasets/cifar10) module: CIFAR10 small images classification dataset.
[`cifar100`](datasets/cifar100) module: CIFAR100 small images classification dataset.
[`fashion_mnist`](datasets/fashion_mnist) module: Fashion-MNIST dataset.
[`imdb`](datasets/imdb) module: IMDB sentiment classification dataset.
[`mnist`](datasets/mnist) module: MNIST handwritten digits dataset.
[`reuters`](datasets/reuters) module: Reuters topic classification dataset.
tensorflow Module: tf.compat.v1.keras.optimizers Module: tf.compat.v1.keras.optimizers
=====================================
Built-in optimizer classes.
For more examples see the base class [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer).
Modules
-------
[`legacy`](optimizers/legacy) module: Public API for tf.keras.optimizers.legacy namespace.
[`schedules`](optimizers/schedules) module: Public API for tf.keras.optimizers.schedules namespace.
Classes
-------
[`class Adadelta`](../../../keras/optimizers/adadelta): Optimizer that implements the Adadelta algorithm.
[`class Adagrad`](../../../keras/optimizers/adagrad): Optimizer that implements the Adagrad algorithm.
[`class Adam`](../../../keras/optimizers/adam): Optimizer that implements the Adam algorithm.
[`class Adamax`](../../../keras/optimizers/adamax): Optimizer that implements the Adamax algorithm.
[`class Ftrl`](../../../keras/optimizers/ftrl): Optimizer that implements the FTRL algorithm.
[`class Nadam`](../../../keras/optimizers/nadam): Optimizer that implements the NAdam algorithm.
[`class Optimizer`](../../../keras/optimizers/optimizer): Base class for Keras optimizers.
[`class RMSprop`](../../../keras/optimizers/rmsprop): Optimizer that implements the RMSprop algorithm.
[`class SGD`](../../../keras/optimizers/sgd): Gradient descent (with momentum) optimizer.
Functions
---------
[`deserialize(...)`](../../../keras/optimizers/deserialize): Inverse of the `serialize` function.
[`get(...)`](../../../keras/optimizers/get): Retrieves a Keras Optimizer instance.
[`serialize(...)`](../../../keras/optimizers/serialize): Serialize the optimizer configuration to JSON compatible python dict.
tensorflow Module: tf.compat.v1.keras.experimental Module: tf.compat.v1.keras.experimental
=======================================
Public API for tf.keras.experimental namespace.
Classes
-------
[`class CosineDecay`](../../../keras/optimizers/schedules/cosinedecay): A LearningRateSchedule that uses a cosine decay schedule.
[`class CosineDecayRestarts`](../../../keras/optimizers/schedules/cosinedecayrestarts): A LearningRateSchedule that uses a cosine decay schedule with restarts.
[`class LinearModel`](../../../keras/experimental/linearmodel): Linear Model for regression and classification problems.
[`class SequenceFeatures`](../../../keras/experimental/sequencefeatures): A layer for sequence input.
[`class WideDeepModel`](../../../keras/experimental/widedeepmodel): Wide & Deep Model for regression and classification problems.
Functions
---------
[`export_saved_model(...)`](experimental/export_saved_model): Exports a [`tf.keras.Model`](../../../keras/model) as a Tensorflow SavedModel.
[`load_from_saved_model(...)`](experimental/load_from_saved_model): Loads a keras Model from a SavedModel created by `export_saved_model()`.
tensorflow Module: tf.compat.v1.keras.activations Module: tf.compat.v1.keras.activations
======================================
Built-in activation functions.
Functions
---------
[`deserialize(...)`](../../../keras/activations/deserialize): Returns activation function given a string identifier.
[`elu(...)`](../../../keras/activations/elu): Exponential Linear Unit.
[`exponential(...)`](../../../keras/activations/exponential): Exponential activation function.
[`get(...)`](../../../keras/activations/get): Returns function.
[`hard_sigmoid(...)`](../../../keras/activations/hard_sigmoid): Hard sigmoid activation function.
[`linear(...)`](../../../keras/activations/linear): Linear activation function (pass-through).
[`relu(...)`](../../../keras/activations/relu): Applies the rectified linear unit activation function.
[`selu(...)`](../../../keras/activations/selu): Scaled Exponential Linear Unit (SELU).
[`serialize(...)`](../../../keras/activations/serialize): Returns the string identifier of an activation function.
[`sigmoid(...)`](../../../keras/activations/sigmoid): Sigmoid activation function, `sigmoid(x) = 1 / (1 + exp(-x))`.
[`softmax(...)`](../../../keras/activations/softmax): Softmax converts a vector of values to a probability distribution.
[`softplus(...)`](../../../keras/activations/softplus): Softplus activation function, `softplus(x) = log(exp(x) + 1)`.
[`softsign(...)`](../../../keras/activations/softsign): Softsign activation function, `softsign(x) = x / (abs(x) + 1)`.
[`swish(...)`](../../../keras/activations/swish): Swish activation function, `swish(x) = x * sigmoid(x)`.
[`tanh(...)`](../../../keras/activations/tanh): Hyperbolic tangent activation function.
tensorflow Module: tf.compat.v1.keras.wrappers Module: tf.compat.v1.keras.wrappers
===================================
Public API for tf.keras.wrappers namespace.
Modules
-------
[`scikit_learn`](wrappers/scikit_learn) module: Wrapper for using the Scikit-Learn API with Keras models.
tensorflow Module: tf.compat.v1.keras.models Module: tf.compat.v1.keras.models
=================================
Keras models API.
Classes
-------
[`class LinearModel`](../../../keras/experimental/linearmodel): Linear Model for regression and classification problems.
[`class Model`](../../../keras/model): `Model` groups layers into an object with training and inference features.
[`class Sequential`](../../../keras/sequential): `Sequential` groups a linear stack of layers into a [`tf.keras.Model`](../../../keras/model).
[`class WideDeepModel`](../../../keras/experimental/widedeepmodel): Wide & Deep Model for regression and classification problems.
Functions
---------
[`clone_model(...)`](../../../keras/models/clone_model): Clone a Functional or Sequential `Model` instance.
[`load_model(...)`](../../../keras/models/load_model): Loads a model saved via `model.save()`.
[`model_from_config(...)`](../../../keras/models/model_from_config): Instantiates a Keras model from its config.
[`model_from_json(...)`](../../../keras/models/model_from_json): Parses a JSON model configuration string and returns a model instance.
[`model_from_yaml(...)`](../../../keras/models/model_from_yaml): Parses a yaml model configuration file and returns a model instance.
[`save_model(...)`](../../../keras/models/save_model): Saves a model as a TensorFlow SavedModel or HDF5 file.
tensorflow Module: tf.compat.v1.keras.estimator Module: tf.compat.v1.keras.estimator
====================================
Keras estimator API.
Functions
---------
[`model_to_estimator(...)`](estimator/model_to_estimator): Constructs an `Estimator` instance from given keras model.
tensorflow Module: tf.compat.v1.keras.metrics Module: tf.compat.v1.keras.metrics
==================================
All Keras metrics.
Classes
-------
[`class AUC`](../../../keras/metrics/auc): Approximates the AUC (Area under the curve) of the ROC or PR curves.
[`class Accuracy`](../../../keras/metrics/accuracy): Calculates how often predictions equal labels.
[`class BinaryAccuracy`](../../../keras/metrics/binaryaccuracy): Calculates how often predictions match binary labels.
[`class BinaryCrossentropy`](../../../keras/metrics/binarycrossentropy): Computes the crossentropy metric between the labels and predictions.
[`class BinaryIoU`](../../../keras/metrics/binaryiou): Computes the Intersection-Over-Union metric for class 0 and/or 1.
[`class CategoricalAccuracy`](../../../keras/metrics/categoricalaccuracy): Calculates how often predictions match one-hot labels.
[`class CategoricalCrossentropy`](../../../keras/metrics/categoricalcrossentropy): Computes the crossentropy metric between the labels and predictions.
[`class CategoricalHinge`](../../../keras/metrics/categoricalhinge): Computes the categorical hinge metric between `y_true` and `y_pred`.
[`class CosineSimilarity`](../../../keras/metrics/cosinesimilarity): Computes the cosine similarity between the labels and predictions.
[`class FalseNegatives`](../../../keras/metrics/falsenegatives): Calculates the number of false negatives.
[`class FalsePositives`](../../../keras/metrics/falsepositives): Calculates the number of false positives.
[`class Hinge`](../../../keras/metrics/hinge): Computes the hinge metric between `y_true` and `y_pred`.
[`class IoU`](../../../keras/metrics/iou): Computes the Intersection-Over-Union metric for specific target classes.
[`class KLDivergence`](../../../keras/metrics/kldivergence): Computes Kullback-Leibler divergence metric between `y_true` and `y_pred`.
[`class LogCoshError`](../../../keras/metrics/logcosherror): Computes the logarithm of the hyperbolic cosine of the prediction error.
[`class Mean`](../../../keras/metrics/mean): Computes the (weighted) mean of the given values.
[`class MeanAbsoluteError`](../../../keras/metrics/meanabsoluteerror): Computes the mean absolute error between the labels and predictions.
[`class MeanAbsolutePercentageError`](../../../keras/metrics/meanabsolutepercentageerror): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`class MeanIoU`](../../../keras/metrics/meaniou): Computes the mean Intersection-Over-Union metric.
[`class MeanMetricWrapper`](../../../keras/metrics/meanmetricwrapper): Wraps a stateless metric function with the Mean metric.
[`class MeanRelativeError`](../../../keras/metrics/meanrelativeerror): Computes the mean relative error by normalizing with the given values.
[`class MeanSquaredError`](../../../keras/metrics/meansquarederror): Computes the mean squared error between `y_true` and `y_pred`.
[`class MeanSquaredLogarithmicError`](../../../keras/metrics/meansquaredlogarithmicerror): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`class MeanTensor`](../../../keras/metrics/meantensor): Computes the element-wise (weighted) mean of the given tensors.
[`class Metric`](../../../keras/metrics/metric): Encapsulates metric logic and state.
[`class OneHotIoU`](../../../keras/metrics/onehotiou): Computes the Intersection-Over-Union metric for one-hot encoded labels.
[`class OneHotMeanIoU`](../../../keras/metrics/onehotmeaniou): Computes mean Intersection-Over-Union metric for one-hot encoded labels.
[`class Poisson`](../../../keras/metrics/poisson): Computes the Poisson metric between `y_true` and `y_pred`.
[`class Precision`](../../../keras/metrics/precision): Computes the precision of the predictions with respect to the labels.
[`class PrecisionAtRecall`](../../../keras/metrics/precisionatrecall): Computes best precision where recall is >= specified value.
[`class Recall`](../../../keras/metrics/recall): Computes the recall of the predictions with respect to the labels.
[`class RecallAtPrecision`](../../../keras/metrics/recallatprecision): Computes best recall where precision is >= specified value.
[`class RootMeanSquaredError`](../../../keras/metrics/rootmeansquarederror): Computes root mean squared error metric between `y_true` and `y_pred`.
[`class SensitivityAtSpecificity`](../../../keras/metrics/sensitivityatspecificity): Computes best sensitivity where specificity is >= specified value.
[`class SparseCategoricalAccuracy`](../../../keras/metrics/sparsecategoricalaccuracy): Calculates how often predictions match integer labels.
[`class SparseCategoricalCrossentropy`](../../../keras/metrics/sparsecategoricalcrossentropy): Computes the crossentropy metric between the labels and predictions.
[`class SparseTopKCategoricalAccuracy`](../../../keras/metrics/sparsetopkcategoricalaccuracy): Computes how often integer targets are in the top `K` predictions.
[`class SpecificityAtSensitivity`](../../../keras/metrics/specificityatsensitivity): Computes best specificity where sensitivity is >= specified value.
[`class SquaredHinge`](../../../keras/metrics/squaredhinge): Computes the squared hinge metric between `y_true` and `y_pred`.
[`class Sum`](../../../keras/metrics/sum): Computes the (weighted) sum of the given values.
[`class TopKCategoricalAccuracy`](../../../keras/metrics/topkcategoricalaccuracy): Computes how often targets are in the top `K` predictions.
[`class TrueNegatives`](../../../keras/metrics/truenegatives): Calculates the number of true negatives.
[`class TruePositives`](../../../keras/metrics/truepositives): Calculates the number of true positives.
Functions
---------
[`KLD(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`MAE(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`MAPE(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`MSE(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`MSLE(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`binary_accuracy(...)`](../../../keras/metrics/binary_accuracy): Calculates how often predictions match binary labels.
[`binary_crossentropy(...)`](../../../keras/metrics/binary_crossentropy): Computes the binary crossentropy loss.
[`binary_focal_crossentropy(...)`](../../../keras/metrics/binary_focal_crossentropy): Computes the binary focal crossentropy loss.
[`categorical_accuracy(...)`](../../../keras/metrics/categorical_accuracy): Calculates how often predictions match one-hot labels.
[`categorical_crossentropy(...)`](../../../keras/metrics/categorical_crossentropy): Computes the categorical crossentropy loss.
[`cosine(...)`](../../../keras/losses/cosine_similarity): Computes the cosine similarity between labels and predictions.
[`cosine_proximity(...)`](../../../keras/losses/cosine_similarity): Computes the cosine similarity between labels and predictions.
[`deserialize(...)`](../../../keras/metrics/deserialize): Deserializes a serialized metric class/function instance.
[`get(...)`](../../../keras/metrics/get): Retrieves a Keras metric as a `function`/`Metric` class instance.
[`hinge(...)`](../../../keras/metrics/hinge): Computes the hinge loss between `y_true` and `y_pred`.
[`kl_divergence(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`kld(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`kullback_leibler_divergence(...)`](../../../keras/metrics/kl_divergence): Computes Kullback-Leibler divergence loss between `y_true` and `y_pred`.
[`log_cosh(...)`](../../../keras/losses/log_cosh): Logarithm of the hyperbolic cosine of the prediction error.
[`logcosh(...)`](../../../keras/losses/log_cosh): Logarithm of the hyperbolic cosine of the prediction error.
[`mae(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`mape(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`mean_absolute_error(...)`](../../../keras/metrics/mean_absolute_error): Computes the mean absolute error between labels and predictions.
[`mean_absolute_percentage_error(...)`](../../../keras/metrics/mean_absolute_percentage_error): Computes the mean absolute percentage error between `y_true` and `y_pred`.
[`mean_squared_error(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`mean_squared_logarithmic_error(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`mse(...)`](../../../keras/metrics/mean_squared_error): Computes the mean squared error between labels and predictions.
[`msle(...)`](../../../keras/metrics/mean_squared_logarithmic_error): Computes the mean squared logarithmic error between `y_true` and `y_pred`.
[`poisson(...)`](../../../keras/metrics/poisson): Computes the Poisson loss between y\_true and y\_pred.
[`serialize(...)`](../../../keras/metrics/serialize): Serializes metric function or `Metric` instance.
[`sparse_categorical_accuracy(...)`](../../../keras/metrics/sparse_categorical_accuracy): Calculates how often predictions match integer labels.
[`sparse_categorical_crossentropy(...)`](../../../keras/metrics/sparse_categorical_crossentropy): Computes the sparse categorical crossentropy loss.
[`sparse_top_k_categorical_accuracy(...)`](../../../keras/metrics/sparse_top_k_categorical_accuracy): Computes how often integer targets are in the top `K` predictions.
[`squared_hinge(...)`](../../../keras/metrics/squared_hinge): Computes the squared hinge loss between `y_true` and `y_pred`.
[`top_k_categorical_accuracy(...)`](../../../keras/metrics/top_k_categorical_accuracy): Computes how often targets are in the top `K` predictions.
| programming_docs |
tensorflow Module: tf.compat.v1.keras.wrappers.scikit_learn Module: tf.compat.v1.keras.wrappers.scikit\_learn
=================================================
Wrapper for using the Scikit-Learn API with Keras models.
tensorflow tf.compat.v1.keras.experimental.load_from_saved_model tf.compat.v1.keras.experimental.load\_from\_saved\_model
========================================================
Loads a keras Model from a SavedModel created by `export_saved_model()`.
```
tf.compat.v1.keras.experimental.load_from_saved_model(
saved_model_path, custom_objects=None
)
```
This function reinstantiates model state by:
1) loading model topology from json (this will eventually come from metagraph). 2) loading model weights from checkpoint.
#### Example:
```
import tensorflow as tf
# Create a tf.keras model.
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=[10]))
model.summary()
# Save the tf.keras model in the SavedModel format.
path = '/tmp/simple_keras_model'
tf.keras.experimental.export_saved_model(model, path)
# Load the saved keras model back.
new_model = tf.keras.experimental.load_from_saved_model(path)
new_model.summary()
```
| Args |
| `saved_model_path` | a string specifying the path to an existing SavedModel. |
| `custom_objects` | Optional dictionary mapping names (strings) to custom classes or functions to be considered during deserialization. |
| Returns |
| a keras.Model instance. |
tensorflow tf.compat.v1.keras.experimental.export_saved_model tf.compat.v1.keras.experimental.export\_saved\_model
====================================================
Exports a [`tf.keras.Model`](../../../../keras/model) as a Tensorflow SavedModel.
```
tf.compat.v1.keras.experimental.export_saved_model(
model,
saved_model_path,
custom_objects=None,
as_text=False,
input_signature=None,
serving_only=False
)
```
Note that at this time, subclassed models can only be saved using `serving_only=True`.
The exported `SavedModel` is a standalone serialization of Tensorflow objects, and is supported by TF language APIs and the Tensorflow Serving system. To load the model, use the function `tf.keras.experimental.load_from_saved_model`.
The `SavedModel` contains:
1. a checkpoint containing the model weights.
2. a `SavedModel` proto containing the Tensorflow backend graph. Separate graphs are saved for prediction (serving), train, and evaluation. If the model has not been compiled, then only the graph computing predictions will be exported.
3. the model's json config. If the model is subclassed, this will only be included if the model's `get_config()` method is overwritten.
#### Example:
```
import tensorflow as tf
# Create a tf.keras model.
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(1, input_shape=[10]))
model.summary()
# Save the tf.keras model in the SavedModel format.
path = '/tmp/simple_keras_model'
tf.keras.experimental.export_saved_model(model, path)
# Load the saved keras model back.
new_model = tf.keras.experimental.load_from_saved_model(path)
new_model.summary()
```
| Args |
| `model` | A [`tf.keras.Model`](../../../../keras/model) to be saved. If the model is subclassed, the flag `serving_only` must be set to True. |
| `saved_model_path` | a string specifying the path to the SavedModel directory. |
| `custom_objects` | Optional dictionary mapping string names to custom classes or functions (e.g. custom loss functions). |
| `as_text` | bool, `False` by default. Whether to write the `SavedModel` proto in text format. Currently unavailable in serving-only mode. |
| `input_signature` | A possibly nested sequence of [`tf.TensorSpec`](../../../../tensorspec) objects, used to specify the expected model inputs. See [`tf.function`](../../../../function) for more details. |
| `serving_only` | bool, `False` by default. When this is true, only the prediction graph is saved. |
| Raises |
| `NotImplementedError` | If the model is a subclassed model, and serving\_only is False. |
| `ValueError` | If the input signature cannot be inferred from the model. |
| `AssertionError` | If the SavedModel directory already exists and isn't empty. |
tensorflow tf.compat.v1.keras.layers.LSTM tf.compat.v1.keras.layers.LSTM
==============================
Long Short-Term Memory layer - Hochreiter 1997.
Inherits From: [`RNN`](../../../../keras/layers/rnn), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.LSTM(
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
unit_forget_bias=True,
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.0,
recurrent_dropout=0.0,
return_sequences=False,
return_state=False,
go_backwards=False,
stateful=False,
unroll=False,
**kwargs
)
```
Note that this cell is not optimized for performance on GPU. Please use [`tf.compat.v1.keras.layers.CuDNNLSTM`](cudnnlstm) for better performance on GPU.
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `activation` | Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `recurrent_activation` | Activation function to use for the recurrent step. Default: hard sigmoid (`hard_sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `use_bias` | Boolean, whether the layer uses a bias vector. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs.. |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `unit_forget_bias` | Boolean. If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf). |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `activity_regularizer` | Regularizer function applied to the output of the layer (its "activation"). |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. |
| `recurrent_dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. |
| `return_sequences` | Boolean. Whether to return the last output in the output sequence, or the full sequence. |
| `return_state` | Boolean. Whether to return the last state in addition to the output. |
| `go_backwards` | Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. |
| `stateful` | Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. |
| `unroll` | Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. |
| `time_major` | The shape format of the `inputs` and `outputs` tensors. If True, the inputs and outputs will be in shape `(timesteps, batch, ...)`, whereas in the False case, it will be `(batch, timesteps, ...)`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. |
#### Call arguments:
* **`inputs`**: A 3D tensor.
* **`mask`**: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored.
* **`training`**: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` is used.
* **`initial_state`**: List of initial state tensors to be passed to the first call of the cell.
| Attributes |
| `activation` | |
| `bias_constraint` | |
| `bias_initializer` | |
| `bias_regularizer` | |
| `dropout` | |
| `implementation` | |
| `kernel_constraint` | |
| `kernel_initializer` | |
| `kernel_regularizer` | |
| `recurrent_activation` | |
| `recurrent_constraint` | |
| `recurrent_dropout` | |
| `recurrent_initializer` | |
| `recurrent_regularizer` | |
| `states` | |
| `unit_forget_bias` | |
| `units` | |
| `use_bias` | |
Methods
-------
### `reset_states`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_rnn.py#L752-L831)
```
reset_states(
states=None
)
```
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with `stateful` = `True`. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.
| Raises |
| `AttributeError` | When the RNN layer is not stateful. |
| `ValueError` | When the batch size of the RNN layer is unknown. |
| `ValueError` | When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise. |
tensorflow tf.compat.v1.keras.layers.GRUCell tf.compat.v1.keras.layers.GRUCell
=================================
Cell class for the GRU layer.
Inherits From: [`GRUCell`](../../../../keras/layers/grucell), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.GRUCell(
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.0,
recurrent_dropout=0.0,
reset_after=False,
**kwargs
)
```
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `activation` | Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass None, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `recurrent_activation` | Activation function to use for the recurrent step. Default: hard sigmoid (`hard_sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `use_bias` | Boolean, whether the layer uses a bias vector. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. |
| `recurrent_dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. |
| `reset_after` | GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before" (default), True = "after" (cuDNN compatible). |
#### Call arguments:
* **`inputs`**: A 2D tensor.
* **`states`**: List of state tensors corresponding to the previous timestep.
* **`training`**: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when `dropout` or `recurrent_dropout` is used.
Methods
-------
### `get_dropout_mask_for_cell`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L106-L125)
```
get_dropout_mask_for_cell(
inputs, training, count=1
)
```
Get the dropout mask for RNN cell's input.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
| Args |
| `inputs` | The input tensor whose shape will be used to generate dropout mask. |
| `training` | Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. |
| `count` | Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. |
| Returns |
| List of mask tensor, generated or cached mask based on context. |
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/gru.py#L345-L347)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_recurrent_dropout_mask_for_cell`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L127-L146)
```
get_recurrent_dropout_mask_for_cell(
inputs, training, count=1
)
```
Get the recurrent dropout mask for RNN cell.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
| Args |
| `inputs` | The input tensor whose shape will be used to generate dropout mask. |
| `training` | Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. |
| `count` | Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. |
| Returns |
| List of mask tensor, generated or cached mask based on context. |
### `reset_dropout_mask`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L68-L77)
```
reset_dropout_mask()
```
Reset the cached dropout masks if any.
This is important for the RNN layer to invoke this in it `call()` method so that the cached mask is cleared before calling the `cell.call()`. The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
### `reset_recurrent_dropout_mask`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L79-L88)
```
reset_recurrent_dropout_mask()
```
Reset the cached recurrent dropout masks if any.
This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
tensorflow tf.compat.v1.keras.layers.GRU tf.compat.v1.keras.layers.GRU
=============================
Gated Recurrent Unit - Cho et al. 2014.
Inherits From: [`RNN`](../../../../keras/layers/rnn), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.GRU(
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.0,
recurrent_dropout=0.0,
return_sequences=False,
return_state=False,
go_backwards=False,
stateful=False,
unroll=False,
reset_after=False,
**kwargs
)
```
There are two variants. The default one is based on 1406.1078v3 and has reset gate applied to hidden state before matrix multiplication. The other one is based on original 1406.1078v1 and has the order reversed.
The second variant is compatible with CuDNNGRU (GPU-only) and allows inference on CPU. Thus it has separate biases for `kernel` and `recurrent_kernel`. Use `'reset_after'=True` and `recurrent_activation='sigmoid'`.
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `activation` | Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `recurrent_activation` | Activation function to use for the recurrent step. Default: hard sigmoid (`hard_sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `use_bias` | Boolean, whether the layer uses a bias vector. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `activity_regularizer` | Regularizer function applied to the output of the layer (its "activation").. |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. |
| `recurrent_dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. |
| `return_sequences` | Boolean. Whether to return the last output in the output sequence, or the full sequence. |
| `return_state` | Boolean. Whether to return the last state in addition to the output. |
| `go_backwards` | Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. |
| `stateful` | Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. |
| `unroll` | Boolean (default False). If True, the network will be unrolled, else a symbolic loop will be used. Unrolling can speed-up a RNN, although it tends to be more memory-intensive. Unrolling is only suitable for short sequences. |
| `time_major` | The shape format of the `inputs` and `outputs` tensors. If True, the inputs and outputs will be in shape `(timesteps, batch, ...)`, whereas in the False case, it will be `(batch, timesteps, ...)`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. |
| `reset_after` | GRU convention (whether to apply reset gate after or before matrix multiplication). False = "before" (default), True = "after" (cuDNN compatible). |
#### Call arguments:
* **`inputs`**: A 3D tensor.
* **`mask`**: Binary tensor of shape `(samples, timesteps)` indicating whether a given timestep should be masked. An individual `True` entry indicates that the corresponding timestep should be utilized, while a `False` entry indicates that the corresponding timestep should be ignored.
* **`training`**: Python boolean indicating whether the layer should behave in training mode or in inference mode. This argument is passed to the cell when calling it. This is only relevant if `dropout` or `recurrent_dropout` is used.
* **`initial_state`**: List of initial state tensors to be passed to the first call of the cell.
| Attributes |
| `activation` | |
| `bias_constraint` | |
| `bias_initializer` | |
| `bias_regularizer` | |
| `dropout` | |
| `implementation` | |
| `kernel_constraint` | |
| `kernel_initializer` | |
| `kernel_regularizer` | |
| `recurrent_activation` | |
| `recurrent_constraint` | |
| `recurrent_dropout` | |
| `recurrent_initializer` | |
| `recurrent_regularizer` | |
| `reset_after` | |
| `states` | |
| `units` | |
| `use_bias` | |
Methods
-------
### `reset_states`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_rnn.py#L752-L831)
```
reset_states(
states=None
)
```
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with `stateful` = `True`. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.
| Raises |
| `AttributeError` | When the RNN layer is not stateful. |
| `ValueError` | When the batch size of the RNN layer is unknown. |
| `ValueError` | When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise. |
| programming_docs |
tensorflow tf.compat.v1.keras.layers.BatchNormalization tf.compat.v1.keras.layers.BatchNormalization
============================================
Layer that normalizes its inputs.
Inherits From: [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.BatchNormalization(
axis=-1,
momentum=0.99,
epsilon=0.001,
center=True,
scale=True,
beta_initializer='zeros',
gamma_initializer='ones',
moving_mean_initializer='zeros',
moving_variance_initializer='ones',
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
renorm=False,
renorm_clipping=None,
renorm_momentum=0.99,
fused=None,
trainable=True,
virtual_batch_size=None,
adjustment=None,
name=None,
**kwargs
)
```
Batch normalization applies a transformation that maintains the mean output close to 0 and the output standard deviation close to 1.
Importantly, batch normalization works differently during training and during inference.
**During training** (i.e. when using `fit()` or when calling the layer/model with the argument `training=True`), the layer normalizes its output using the mean and standard deviation of the current batch of inputs. That is to say, for each channel being normalized, the layer returns `gamma * (batch - mean(batch)) / sqrt(var(batch) + epsilon) + beta`, where:
* `epsilon` is small constant (configurable as part of the constructor arguments)
* `gamma` is a learned scaling factor (initialized as 1), which can be disabled by passing `scale=False` to the constructor.
* `beta` is a learned offset factor (initialized as 0), which can be disabled by passing `center=False` to the constructor.
**During inference** (i.e. when using `evaluate()` or `predict()`) or when calling the layer/model with the argument `training=False` (which is the default), the layer normalizes its output using a moving average of the mean and standard deviation of the batches it has seen during training. That is to say, it returns `gamma * (batch - self.moving_mean) / sqrt(self.moving_var + epsilon) + beta`.
`self.moving_mean` and `self.moving_var` are non-trainable variables that are updated each time the layer in called in training mode, as such:
* `moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum)`
* `moving_var = moving_var * momentum + var(batch) * (1 - momentum)`
As such, the layer will only normalize its inputs during inference *after having been trained on data that has similar statistics as the inference data*.
| Args |
| `axis` | Integer or a list of integers, the axis that should be normalized (typically the features axis). For instance, after a `Conv2D` layer with `data_format="channels_first"`, set `axis=1` in `BatchNormalization`. |
| `momentum` | Momentum for the moving average. |
| `epsilon` | Small float added to variance to avoid dividing by zero. |
| `center` | If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. |
| `scale` | If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. [`nn.relu`](https://www.tensorflow.org/api_docs/python/tf/nn/relu)), this can be disabled since the scaling will be done by the next layer. |
| `beta_initializer` | Initializer for the beta weight. |
| `gamma_initializer` | Initializer for the gamma weight. |
| `moving_mean_initializer` | Initializer for the moving mean. |
| `moving_variance_initializer` | Initializer for the moving variance. |
| `beta_regularizer` | Optional regularizer for the beta weight. |
| `gamma_regularizer` | Optional regularizer for the gamma weight. |
| `beta_constraint` | Optional constraint for the beta weight. |
| `gamma_constraint` | Optional constraint for the gamma weight. |
| `renorm` | Whether to use [Batch Renormalization](https://arxiv.org/abs/1702.03275). This adds extra variables during training. The inference is the same for either value of this parameter. |
| `renorm_clipping` | A dictionary that may map keys 'rmax', 'rmin', 'dmax' to scalar `Tensors` used to clip the renorm correction. The correction `(r, d)` is used as `corrected_value = normalized_value * r + d`, with `r` clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin, dmax are set to inf, 0, inf, respectively. |
| `renorm_momentum` | Momentum used to update the moving means and standard deviations with renorm. Unlike `momentum`, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). Note that `momentum` is still applied to get the means and variances for inference. |
| `fused` | if `True`, use a faster, fused implementation, or raise a ValueError if the fused implementation cannot be used. If `None`, use the faster implementation if possible. If False, do not used the fused implementation. Note that in TensorFlow 1.x, the meaning of `fused=True` is different: if `False`, the layer uses the system-recommended implementation. |
| `trainable` | Boolean, if `True` the variables will be marked as trainable. |
| `virtual_batch_size` | An `int`. By default, `virtual_batch_size` is `None`, which means batch normalization is performed across the whole batch. When `virtual_batch_size` is not `None`, instead perform "Ghost Batch Normalization", which creates virtual sub-batches which are each normalized separately (with shared gamma, beta, and moving statistics). Must divide the actual batch size during execution. |
| `adjustment` | A function taking the `Tensor` containing the (dynamic) shape of the input tensor and returning a pair (scale, bias) to apply to the normalized values (before gamma and beta), only during training. For example, if `axis=-1`, `adjustment = lambda shape: ( tf.random.uniform(shape[-1:], 0.93, 1.07), tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized value by up to 7% up or down, then shift the result by up to 0.1 (with independent scaling and bias for each feature but shared across all examples), and finally apply gamma and/or beta. If `None`, no adjustment is applied. Cannot be specified if virtual\_batch\_size is specified. |
#### Call arguments:
* **`inputs`**: Input tensor (of any rank).
* **`training`**: Python boolean indicating whether the layer should behave in training mode or in inference mode.
+ `training=True`: The layer will normalize its inputs using the mean and variance of the current batch of inputs.
+ `training=False`: The layer will normalize its inputs using the mean and variance of its moving statistics, learned during training.
Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model.
Output shape: Same shape as input.
#### Reference:
* [Ioffe and Szegedy, 2015](https://arxiv.org/abs/1502.03167).
tensorflow tf.compat.v1.keras.layers.disable_v2_dtype_behavior tf.compat.v1.keras.layers.disable\_v2\_dtype\_behavior
======================================================
Disables the V2 dtype behavior for Keras layers.
```
tf.compat.v1.keras.layers.disable_v2_dtype_behavior()
```
See [`tf.compat.v1.keras.layers.enable_v2_dtype_behavior`](enable_v2_dtype_behavior).
tensorflow tf.compat.v1.keras.layers.enable_v2_dtype_behavior tf.compat.v1.keras.layers.enable\_v2\_dtype\_behavior
=====================================================
Enable the V2 dtype behavior for Keras layers.
```
tf.compat.v1.keras.layers.enable_v2_dtype_behavior()
```
By default, the V2 dtype behavior is enabled in TensorFlow 2, so this function is only useful if [`tf.compat.v1.disable_v2_behavior`](../../disable_v2_behavior) has been called. Since mixed precision requires V2 dtype behavior to be enabled, this function allows you to use mixed precision in Keras layers if `disable_v2_behavior` has been called.
When enabled, the dtype of Keras layers defaults to floatx (which is typically float32) instead of None. In addition, layers will automatically cast floating-point inputs to the layer's dtype.
```
x = tf.ones((4, 4, 4, 4), dtype='float64')
layer = tf.keras.layers.Conv2D(filters=4, kernel_size=2)
print(layer.dtype) # float32 since V2 dtype behavior is enabled
float32
y = layer(x) # Layer casts inputs since V2 dtype behavior is enabled
print(y.dtype.name)
float32
```
A layer author can opt-out their layer from the automatic input casting by passing `autocast=False` to the base Layer's constructor. This disables the autocasting part of the V2 behavior for that layer, but not the defaulting to floatx part of the V2 behavior.
When a global [`tf.keras.mixed_precision.Policy`](../../../../keras/mixed_precision/policy) is set, a Keras layer's dtype will default to the global policy instead of floatx. Layers will automatically cast inputs to the policy's compute\_dtype.
tensorflow Module: tf.compat.v1.keras.layers.experimental Module: tf.compat.v1.keras.layers.experimental
==============================================
Public API for tf.keras.layers.experimental namespace.
Modules
-------
[`preprocessing`](experimental/preprocessing) module: Public API for tf.keras.layers.experimental.preprocessing namespace.
Classes
-------
[`class EinsumDense`](../../../../keras/layers/experimental/einsumdense): A layer that uses tf.einsum as the backing computation.
[`class RandomFourierFeatures`](../../../../keras/layers/experimental/randomfourierfeatures): Layer that projects its inputs into a random feature space.
tensorflow tf.compat.v1.keras.layers.DenseFeatures tf.compat.v1.keras.layers.DenseFeatures
=======================================
A layer that produces a dense `Tensor` based on given `feature_columns`.
Inherits From: [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.DenseFeatures(
feature_columns, trainable=True, name=None, partitioner=None, **kwargs
)
```
Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column-oriented data should be converted to a single `Tensor`.
This layer can be called multiple times with different features.
This is the V1 version of this layer that uses variable\_scope's or partitioner to create variables which works well with PartitionedVariables. Variable scopes are deprecated in V2, so the V2 version uses name\_scopes instead. But currently that lacks support for partitioned variables. Use this if you need partitioned variables. Use the partitioner argument if you have a Keras model and uses [`tf.compat.v1.keras.estimator.model_to_estimator`](../estimator/model_to_estimator) for training.
#### Example:
```
price = tf.feature_column.numeric_column('price')
keywords_embedded = tf.feature_column.embedding_column(
tf.feature_column.categorical_column_with_hash_bucket("keywords", 10K),
dimension=16)
columns = [price, keywords_embedded, ...]
partitioner = tf.compat.v1.fixed_size_partitioner(num_shards=4)
feature_layer = tf.compat.v1.keras.layers.DenseFeatures(
feature_columns=columns, partitioner=partitioner)
features = tf.io.parse_example(
..., features=tf.feature_column.make_parse_example_spec(columns))
dense_tensor = feature_layer(features)
for units in [128, 64, 32]:
dense_tensor = tf.compat.v1.keras.layers.Dense(
units, activation='relu')(dense_tensor)
prediction = tf.compat.v1.keras.layers.Dense(1)(dense_tensor)
```
| Args |
| `feature_columns` | An iterable containing the FeatureColumns to use as inputs to your model. All items should be instances of classes derived from `DenseColumn` such as `numeric_column`, `embedding_column`, `bucketized_column`, `indicator_column`. If you have categorical features, you can wrap them with an `embedding_column` or `indicator_column`. |
| `trainable` | Boolean, whether the layer's variables will be updated via gradient descent during training. |
| `name` | Name to give to the DenseFeatures. |
| `partitioner` | Partitioner for input layer. Defaults to None. |
| `**kwargs` | Keyword arguments to construct a layer. |
| Raises |
| `ValueError` | if an item in `feature_columns` is not a `DenseColumn`. |
tensorflow tf.compat.v1.keras.layers.CuDNNGRU tf.compat.v1.keras.layers.CuDNNGRU
==================================
Fast GRU implementation backed by cuDNN.
Inherits From: [`RNN`](../../../../keras/layers/rnn), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.CuDNNGRU(
units,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
return_sequences=False,
return_state=False,
go_backwards=False,
stateful=False,
**kwargs
)
```
More information about cuDNN can be found on the [NVIDIA developer website](https://developer.nvidia.com/cudnn). Can only be run on GPU.
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `activity_regularizer` | Regularizer function applied to the output of the layer (its "activation"). |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `return_sequences` | Boolean. Whether to return the last output in the output sequence, or the full sequence. |
| `return_state` | Boolean. Whether to return the last state in addition to the output. |
| `go_backwards` | Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. |
| `stateful` | Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. |
| Attributes |
| `cell` | |
| `states` | |
Methods
-------
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_cudnn_rnn.py#L143-L145)
```
get_losses_for(
inputs=None
)
```
### `reset_states`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_rnn.py#L752-L831)
```
reset_states(
states=None
)
```
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with `stateful` = `True`. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.
| Raises |
| `AttributeError` | When the RNN layer is not stateful. |
| `ValueError` | When the batch size of the RNN layer is unknown. |
| `ValueError` | When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise. |
tensorflow tf.compat.v1.keras.layers.LSTMCell tf.compat.v1.keras.layers.LSTMCell
==================================
Cell class for the LSTM layer.
Inherits From: [`LSTMCell`](../../../../keras/layers/lstmcell), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.LSTMCell(
units,
activation='tanh',
recurrent_activation='hard_sigmoid',
use_bias=True,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
unit_forget_bias=True,
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
dropout=0.0,
recurrent_dropout=0.0,
**kwargs
)
```
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `activation` | Activation function to use. Default: hyperbolic tangent (`tanh`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `recurrent_activation` | Activation function to use for the recurrent step. Default: hard sigmoid (`hard_sigmoid`). If you pass `None`, no activation is applied (ie. "linear" activation: `a(x) = x`). |
| `use_bias` | Boolean, whether the layer uses a bias vector. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `unit_forget_bias` | Boolean. If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al., 2015](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the inputs. |
| `recurrent_dropout` | Float between 0 and 1. Fraction of the units to drop for the linear transformation of the recurrent state. |
#### Call arguments:
* **`inputs`**: A 2D tensor.
* **`states`**: List of state tensors corresponding to the previous timestep.
* **`training`**: Python boolean indicating whether the layer should behave in training mode or in inference mode. Only relevant when `dropout` or `recurrent_dropout` is used.
Methods
-------
### `get_dropout_mask_for_cell`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L106-L125)
```
get_dropout_mask_for_cell(
inputs, training, count=1
)
```
Get the dropout mask for RNN cell's input.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
| Args |
| `inputs` | The input tensor whose shape will be used to generate dropout mask. |
| `training` | Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. |
| `count` | Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. |
| Returns |
| List of mask tensor, generated or cached mask based on context. |
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/lstm.py#L341-L343)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_recurrent_dropout_mask_for_cell`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L127-L146)
```
get_recurrent_dropout_mask_for_cell(
inputs, training, count=1
)
```
Get the recurrent dropout mask for RNN cell.
It will create mask based on context if there isn't any existing cached mask. If a new mask is generated, it will update the cache in the cell.
| Args |
| `inputs` | The input tensor whose shape will be used to generate dropout mask. |
| `training` | Boolean tensor, whether its in training mode, dropout will be ignored in non-training mode. |
| `count` | Int, how many dropout mask will be generated. It is useful for cell that has internal weights fused together. |
| Returns |
| List of mask tensor, generated or cached mask based on context. |
### `reset_dropout_mask`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L68-L77)
```
reset_dropout_mask()
```
Reset the cached dropout masks if any.
This is important for the RNN layer to invoke this in it `call()` method so that the cached mask is cleared before calling the `cell.call()`. The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
### `reset_recurrent_dropout_mask`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/dropout_rnn_cell_mixin.py#L79-L88)
```
reset_recurrent_dropout_mask()
```
Reset the cached recurrent dropout masks if any.
This is important for the RNN layer to invoke this in it call() method so that the cached mask is cleared before calling the cell.call(). The mask should be cached across the timestep within the same batch, but shouldn't be cached between batches. Otherwise it will introduce unreasonable bias against certain index of data within the batch.
| programming_docs |
tensorflow tf.compat.v1.keras.layers.CuDNNLSTM tf.compat.v1.keras.layers.CuDNNLSTM
===================================
Fast LSTM implementation backed by cuDNN.
Inherits From: [`RNN`](../../../../keras/layers/rnn), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.keras.layers.CuDNNLSTM(
units,
kernel_initializer='glorot_uniform',
recurrent_initializer='orthogonal',
bias_initializer='zeros',
unit_forget_bias=True,
kernel_regularizer=None,
recurrent_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
recurrent_constraint=None,
bias_constraint=None,
return_sequences=False,
return_state=False,
go_backwards=False,
stateful=False,
**kwargs
)
```
More information about cuDNN can be found on the [NVIDIA developer website](https://developer.nvidia.com/cudnn). Can only be run on GPU.
| Args |
| `units` | Positive integer, dimensionality of the output space. |
| `kernel_initializer` | Initializer for the `kernel` weights matrix, used for the linear transformation of the inputs. |
| `unit_forget_bias` | Boolean. If True, add 1 to the bias of the forget gate at initialization. Setting it to true will also force `bias_initializer="zeros"`. This is recommended in [Jozefowicz et al.](http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf) |
| `recurrent_initializer` | Initializer for the `recurrent_kernel` weights matrix, used for the linear transformation of the recurrent state. |
| `bias_initializer` | Initializer for the bias vector. |
| `kernel_regularizer` | Regularizer function applied to the `kernel` weights matrix. |
| `recurrent_regularizer` | Regularizer function applied to the `recurrent_kernel` weights matrix. |
| `bias_regularizer` | Regularizer function applied to the bias vector. |
| `activity_regularizer` | Regularizer function applied to the output of the layer (its "activation"). |
| `kernel_constraint` | Constraint function applied to the `kernel` weights matrix. |
| `recurrent_constraint` | Constraint function applied to the `recurrent_kernel` weights matrix. |
| `bias_constraint` | Constraint function applied to the bias vector. |
| `return_sequences` | Boolean. Whether to return the last output. in the output sequence, or the full sequence. |
| `return_state` | Boolean. Whether to return the last state in addition to the output. |
| `go_backwards` | Boolean (default False). If True, process the input sequence backwards and return the reversed sequence. |
| `stateful` | Boolean (default False). If True, the last state for each sample at index i in a batch will be used as initial state for the sample of index i in the following batch. |
| Attributes |
| `cell` | |
| `states` | |
Methods
-------
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_cudnn_rnn.py#L143-L145)
```
get_losses_for(
inputs=None
)
```
### `reset_states`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/base_rnn.py#L752-L831)
```
reset_states(
states=None
)
```
Reset the recorded states for the stateful RNN layer.
Can only be used when RNN layer is constructed with `stateful` = `True`. Args: states: Numpy arrays that contains the value for the initial state, which will be feed to cell at the first time step. When the value is None, zero filled numpy array will be created based on the cell state size.
| Raises |
| `AttributeError` | When the RNN layer is not stateful. |
| `ValueError` | When the batch size of the RNN layer is unknown. |
| `ValueError` | When the input numpy array is not compatible with the RNN layer state, either size wise or dtype wise. |
tensorflow Module: tf.compat.v1.keras.layers.experimental.preprocessing Module: tf.compat.v1.keras.layers.experimental.preprocessing
============================================================
Public API for tf.keras.layers.experimental.preprocessing namespace.
Classes
-------
[`class CategoryEncoding`](../../../../../keras/layers/categoryencoding): A preprocessing layer which encodes integer features.
[`class CenterCrop`](../../../../../keras/layers/centercrop): A preprocessing layer which crops images.
[`class Discretization`](../../../../../keras/layers/discretization): A preprocessing layer which buckets continuous features by ranges.
[`class HashedCrossing`](../../../../../keras/layers/experimental/preprocessing/hashedcrossing): A preprocessing layer which crosses features using the "hashing trick".
[`class Hashing`](../../../../../keras/layers/hashing): A preprocessing layer which hashes and bins categorical features.
[`class Normalization`](../../../../../keras/layers/normalization): A preprocessing layer which normalizes continuous features.
[`class PreprocessingLayer`](../../../../../keras/layers/experimental/preprocessing/preprocessinglayer): Base class for Preprocessing Layers.
[`class Rescaling`](../../../../../keras/layers/rescaling): A preprocessing layer which rescales input values to a new range.
[`class Resizing`](../../../../../keras/layers/resizing): A preprocessing layer which resizes images.
tensorflow tf.compat.v1.keras.callbacks.TensorBoard tf.compat.v1.keras.callbacks.TensorBoard
========================================
Enable visualizations for TensorBoard.
Inherits From: [`TensorBoard`](../../../../keras/callbacks/tensorboard), [`Callback`](../../../../keras/callbacks/callback)
```
tf.compat.v1.keras.callbacks.TensorBoard(
log_dir='./logs',
histogram_freq=0,
batch_size=32,
write_graph=True,
write_grads=False,
write_images=False,
embeddings_freq=0,
embeddings_layer_names=None,
embeddings_metadata=None,
embeddings_data=None,
update_freq='epoch',
profile_batch=2
)
```
TensorBoard is a visualization tool provided with TensorFlow.
This callback logs events for TensorBoard, including:
* Metrics summary plots
* Training graph visualization
* Activation histograms
* Sampled profiling
If you have installed TensorFlow with pip, you should be able to launch TensorBoard from the command line:
```
tensorboard --logdir=path_to_your_logs
```
You can find more information about TensorBoard [here](https://www.tensorflow.org/get_started/summaries_and_tensorboard).
| Args |
| `log_dir` | the path of the directory where to save the log files to be parsed by TensorBoard. |
| `histogram_freq` | frequency (in epochs) at which to compute activation and weight histograms for the layers of the model. If set to 0, histograms won't be computed. Validation data (or split) must be specified for histogram visualizations. |
| `write_graph` | whether to visualize the graph in TensorBoard. The log file can become quite large when write\_graph is set to True. |
| `write_grads` | whether to visualize gradient histograms in TensorBoard. `histogram_freq` must be greater than 0. |
| `batch_size` | size of batch of inputs to feed to the network for histograms computation. |
| `write_images` | whether to write model weights to visualize as image in TensorBoard. |
| `embeddings_freq` | frequency (in epochs) at which selected embedding layers will be saved. If set to 0, embeddings won't be computed. Data to be visualized in TensorBoard's Embedding tab must be passed as `embeddings_data`. |
| `embeddings_layer_names` | a list of names of layers to keep eye on. If None or empty list all the embedding layer will be watched. |
| `embeddings_metadata` | a dictionary which maps layer name to a file name in which metadata for this embedding layer is saved. [Here are details](https://www.tensorflow.org/how_tos/embedding_viz/#metadata_optional) about metadata files format. In case if the same metadata file is used for all embedding layers, string can be passed. |
| `embeddings_data` | data to be embedded at layers specified in `embeddings_layer_names`. Numpy array (if the model has a single input) or list of Numpy arrays (if the model has multiple inputs). Learn more about embeddings [in this guide](https://www.tensorflow.org/programmers_guide/embedding). |
| `update_freq` | `'batch'` or `'epoch'` or integer. When using `'batch'`, writes the losses and metrics to TensorBoard after each batch. The same applies for `'epoch'`. If using an integer, let's say `1000`, the callback will write the metrics and losses to TensorBoard every 1000 samples. Note that writing too frequently to TensorBoard can slow down your training. |
| `profile_batch` | Profile the batch to sample compute characteristics. By default, it will profile the second batch. Set profile\_batch=0 to disable profiling. |
| Raises |
| `ValueError` | If histogram\_freq is set and no validation data is provided. |
Methods
-------
### `set_model`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/callbacks_v1.py#L224-L302)
```
set_model(
model
)
```
Sets Keras model and creates summary ops.
### `set_params`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/callbacks.py#L644-L645)
```
set_params(
params
)
```
eager compatibility
-------------------
Using the `TensorBoard` callback will work when eager execution is enabled, with the restriction that outputting histogram summaries of weights and gradients is not supported. Consequently, `histogram_freq` will be ignored.
tensorflow tf.compat.v1.keras.estimator.model_to_estimator tf.compat.v1.keras.estimator.model\_to\_estimator
=================================================
Constructs an `Estimator` instance from given keras model.
```
tf.compat.v1.keras.estimator.model_to_estimator(
keras_model=None,
keras_model_path=None,
custom_objects=None,
model_dir=None,
config=None,
checkpoint_format='saver',
metric_names_map=None,
export_outputs=None
)
```
If you use infrastructure or other tooling that relies on Estimators, you can still build a Keras model and use model\_to\_estimator to convert the Keras model to an Estimator for use with downstream systems.
For usage example, please see: [Creating estimators from Keras Models](https://www.tensorflow.org/guide/estimator#create_an_estimator_from_a_keras_model).
#### Sample Weights:
Estimators returned by `model_to_estimator` are configured so that they can handle sample weights (similar to `keras_model.fit(x, y, sample_weights)`).
To pass sample weights when training or evaluating the Estimator, the first item returned by the input function should be a dictionary with keys `features` and `sample_weights`. Example below:
```
keras_model = tf.keras.Model(...)
keras_model.compile(...)
estimator = tf.keras.estimator.model_to_estimator(keras_model)
def input_fn():
return dataset_ops.Dataset.from_tensors(
({'features': features, 'sample_weights': sample_weights},
targets))
estimator.train(input_fn, steps=1)
```
Example with customized export signature:
```
inputs = {'a': tf.keras.Input(..., name='a'),
'b': tf.keras.Input(..., name='b')}
outputs = {'c': tf.keras.layers.Dense(..., name='c')(inputs['a']),
'd': tf.keras.layers.Dense(..., name='d')(inputs['b'])}
keras_model = tf.keras.Model(inputs, outputs)
keras_model.compile(...)
export_outputs = {'c': tf.estimator.export.RegressionOutput,
'd': tf.estimator.export.ClassificationOutput}
estimator = tf.keras.estimator.model_to_estimator(
keras_model, export_outputs=export_outputs)
def input_fn():
return dataset_ops.Dataset.from_tensors(
({'features': features, 'sample_weights': sample_weights},
targets))
estimator.train(input_fn, steps=1)
```
| Args |
| `keras_model` | A compiled Keras model object. This argument is mutually exclusive with `keras_model_path`. Estimator's `model_fn` uses the structure of the model to clone the model. Defaults to `None`. |
| `keras_model_path` | Path to a compiled Keras model saved on disk, in HDF5 format, which can be generated with the `save()` method of a Keras model. This argument is mutually exclusive with `keras_model`. Defaults to `None`. |
| `custom_objects` | Dictionary for cloning customized objects. This is used with classes that is not part of this pip package. For example, if user maintains a `relu6` class that inherits from [`tf.keras.layers.Layer`](../../../../keras/layers/layer), then pass `custom_objects={'relu6': relu6}`. Defaults to `None`. |
| `model_dir` | Directory to save `Estimator` model parameters, graph, summary files for TensorBoard, etc. If unset a directory will be created with `tempfile.mkdtemp` |
| `config` | `RunConfig` to config `Estimator`. Allows setting up things in `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`. Defaults to `None`. If both `config.model_dir` and the `model_dir` argument (above) are specified the `model_dir` **argument** takes precedence. |
| `checkpoint_format` | Sets the format of the checkpoint saved by the estimator when training. May be `saver` or `checkpoint`, depending on whether to save checkpoints from `tf.train.Saver` or [`tf.train.Checkpoint`](../../../../train/checkpoint). This argument currently defaults to `saver`. When 2.0 is released, the default will be `checkpoint`. Estimators use name-based `tf.train.Saver` checkpoints, while Keras models use object-based checkpoints from [`tf.train.Checkpoint`](../../../../train/checkpoint). Currently, saving object-based checkpoints from `model_to_estimator` is only supported by Functional and Sequential models. Defaults to 'saver'. |
| `metric_names_map` | Optional dictionary mapping Keras model output metric names to custom names. This can be used to override the default Keras model output metrics names in a multi IO model use case and provide custom names for the `eval_metric_ops` in Estimator. The Keras model metric names can be obtained using `model.metrics_names` excluding any loss metrics such as total loss and output losses. For example, if your Keras model has two outputs `out_1` and `out_2`, with `mse` loss and `acc` metric, then `model.metrics_names` will be `['loss', 'out_1_loss', 'out_2_loss', 'out_1_acc', 'out_2_acc']`. The model metric names excluding the loss metrics will be `['out_1_acc', 'out_2_acc']`. |
| `export_outputs` | Optional dictionary. This can be used to override the default Keras model output exports in a multi IO model use case and provide custom names for the `export_outputs` in [`tf.estimator.EstimatorSpec`](../../../../estimator/estimatorspec). Default is None, which is equivalent to {'serving\_default': [`tf.estimator.export.PredictOutput`](../../../../estimator/export/predictoutput)}. If not None, the keys must match the keys of `model.output_names`. A dict `{name: output}` where: * name: An arbitrary name for this output.
* output: an `ExportOutput` class such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. Single-headed models only need to specify one entry in this dictionary. Multi-headed models should specify one entry for each head, one of which must be named using `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY` If no entry is provided, a default `PredictOutput` mapping to `predictions` will be created.
|
| Returns |
| An Estimator from given keras model. |
| Raises |
| `ValueError` | If neither keras\_model nor keras\_model\_path was given. |
| `ValueError` | If both keras\_model and keras\_model\_path was given. |
| `ValueError` | If the keras\_model\_path is a GCS URI. |
| `ValueError` | If keras\_model has not been compiled. |
| `ValueError` | If an invalid checkpoint\_format was given. |
tensorflow Module: tf.compat.v1.keras.datasets.reuters Module: tf.compat.v1.keras.datasets.reuters
===========================================
Reuters topic classification dataset.
Functions
---------
[`get_word_index(...)`](../../../../keras/datasets/reuters/get_word_index): Retrieves a dict mapping words to their index in the Reuters dataset.
[`load_data(...)`](../../../../keras/datasets/reuters/load_data): Loads the Reuters newswire classification dataset.
tensorflow Module: tf.compat.v1.keras.datasets.cifar100 Module: tf.compat.v1.keras.datasets.cifar100
============================================
CIFAR100 small images classification dataset.
Functions
---------
[`load_data(...)`](../../../../keras/datasets/cifar100/load_data): Loads the CIFAR100 dataset.
tensorflow Module: tf.compat.v1.keras.datasets.cifar10 Module: tf.compat.v1.keras.datasets.cifar10
===========================================
CIFAR10 small images classification dataset.
Functions
---------
[`load_data(...)`](../../../../keras/datasets/cifar10/load_data): Loads the CIFAR10 dataset.
tensorflow Module: tf.compat.v1.keras.datasets.mnist Module: tf.compat.v1.keras.datasets.mnist
=========================================
MNIST handwritten digits dataset.
Functions
---------
[`load_data(...)`](../../../../keras/datasets/mnist/load_data): Loads the MNIST dataset.
tensorflow Module: tf.compat.v1.keras.datasets.imdb Module: tf.compat.v1.keras.datasets.imdb
========================================
IMDB sentiment classification dataset.
Functions
---------
[`get_word_index(...)`](../../../../keras/datasets/imdb/get_word_index): Retrieves a dict mapping words to their index in the IMDB dataset.
[`load_data(...)`](../../../../keras/datasets/imdb/load_data): Loads the [IMDB dataset](https://ai.stanford.edu/%7Eamaas/data/sentiment/).
tensorflow Module: tf.compat.v1.keras.datasets.fashion_mnist Module: tf.compat.v1.keras.datasets.fashion\_mnist
==================================================
Fashion-MNIST dataset.
Functions
---------
[`load_data(...)`](../../../../keras/datasets/fashion_mnist/load_data): Loads the Fashion-MNIST dataset.
tensorflow Module: tf.compat.v1.keras.datasets.boston_housing Module: tf.compat.v1.keras.datasets.boston\_housing
===================================================
Boston housing price regression dataset.
Functions
---------
[`load_data(...)`](../../../../keras/datasets/boston_housing/load_data): Loads the Boston Housing dataset.
tensorflow tf.compat.v1.keras.utils.DeterministicRandomTestTool tf.compat.v1.keras.utils.DeterministicRandomTestTool
====================================================
DeterministicRandomTestTool is a testing tool.
```
tf.compat.v1.keras.utils.DeterministicRandomTestTool(
seed: int = 42, mode='constant'
)
```
This tool is used to validate random number generation semantics match between TF1.x graphs/sessions and eager execution.
This is useful when you are migrating from TF 1.x to TF2 and need to make sure your computation is still happening correctly along the way. See the validating correctness migration guide for more info : <https://www.tensorflow.org/guide/migrate/validate_correctness>
The following DeterministicRandomTestTool object provides a context manager scope() that can make stateful random operations use the same seed across both TF1 graphs/sessions and eager execution,The tool provides two testing modes:
* constant which uses the same seed for every single operation no matter how many times it has been called and,
* num\_random\_ops which uses the number of previously-observed stateful random operations as the operation seed. The num\_random\_ops mode serves as a more sensitive validation check than the constant mode. It ensures that the random numbers initialization does not get accidentaly reused.(for example if several weights take on the same initializations), you can use the num\_random\_ops mode to avoid this. In the num\_random\_ops mode, the generated random numbers will depend on the ordering of random ops in the program.
This applies both to the stateful random operations used for creating and initializing variables, and to the stateful random operations used in computation (such as for dropout layers).
| Attributes |
| `operation_seed` | |
Methods
-------
### `scope`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/migration_utils.py#L65-L103)
```
scope()
```
set random seed.
| programming_docs |
tensorflow tf.compat.v1.keras.utils.track_tf1_style_variables tf.compat.v1.keras.utils.track\_tf1\_style\_variables
=====================================================
Wrap layer & module methods in this decorator to capture tf1-style weights.
```
tf.compat.v1.keras.utils.track_tf1_style_variables(
method
)
```
Decorating a `tf.keras.Layer`'s or [`tf.Module`](../../../../module)'s methods with this decorator will cause the layer/module to track weights created/used via [`tf.compat.v1.get_variable`](../../get_variable) (and by extension [`tf.compat.v1.layers`](../../layers)) inside the decorated method.
In addition to tracking the weights themselves under the standard `layer.variable`/[`module.variable`](https://www.tensorflow.org/probability/oryx/api_docs/python/oryx/core/state/variable)/etc. properties, if the method belongs to a `tf.keras.Layer` then any regularization losses specified via the `get_variable` or [`tf.compat.v1.layers`](../../layers) regularizer arguments will get tracked by the layer under the standard `layer.losses` property.
This tracking enables using large classes of TF1-style model-forward-pass code inside of Keras layers or `tf.Modules` in TF2 with TF2 behaviors enabled.
Example of capturing tf.compat.v1.layer-based modeling code as a Keras layer:
```
class WrappedDoubleDenseLayer(tf.keras.layers.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@tf.compat.v1.keras.utils.track_tf1_style_variables
def call(self, inputs):
with tf.compat.v1.variable_scope("double_dense_layer"):
out = tf.compat.v1.layers.dense(
inputs, self.units, name="dense_one",
kernel_initializer=tf.compat.v1.random_normal_initializer,
kernel_regularizer="l2")
out = tf.compat.v1.layers.dense(
out, self.units, name="dense_two",
kernel_initializer=tf.compat.v1.random_normal_initializer(),
kernel_regularizer="l2")
return out
# Create a layer that can be used as a standard keras layer
layer = WrappedDoubleDenseLayer(10)
# call the layer on inputs
layer(...)
# Variables created/used within the scope will be tracked by the layer
layer.weights
layer.trainable_variables
# Regularization losses will be captured in layer.losses after a call,
# just like any other Keras layer
reg_losses = layer.losses
```
Example of capturing tf.compat.v1.get\_variable-based modeling code as a Keras layer:
```
class WrappedDoubleDenseLayer(tf.keras.layers.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
@tf.compat.v1.keras.utils.track_tf1_style_variables
def call(self, inputs):
out = inputs
with tf.compat.v1.variable_scope("double_dense_layer"):
with tf.compat.v1.variable_scope("dense_one"):
# The weights are created with a `regularizer`,
# so the layer should track their regularization losses
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=init_ops.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=init_ops.zeros_initializer(),
name="bias")
out = tf.compat.v1.math.matmul(out, kernel)
out = tf.compat.v1.nn.bias_add(out, bias)
with tf.compat.v1.variable_scope("dense_two"):
kernel = tf.compat.v1.get_variable(
shape=[out.shape[-1], self.units],
regularizer=regularizers.L2(),
initializer=init_ops.ones_initializer(),
name="kernel")
bias = tf.compat.v1.get_variable(
shape=[self.units,],
initializer=init_ops.zeros_initializer(),
name="bias")
out = tf.compat.v1.math.matmul(out, kernel)
out = tf.compat.v1.nn.bias_add(out, bias)
return out
# Create a layer that can be used as a standard keras layer
layer = WrappedDoubleDenseLayer(10)
# call the layer on inputs
layer(...)
# Variables created/used within the scope will be tracked by the layer
layer.weights
layer.trainable_variables
# Regularization losses will be captured in layer.losses after a call,
# just like any other Keras layer
reg_losses = layer.losses
```
#### Regularization losses:
Any regularizers specified in the `get_variable` calls or `compat.v1.layer` creations will get captured if they occur in your decorated method and the method belongs to a `tf.keras.Layer`/`tf.keras.Module`. Regularization losses are accessible in `layer.losses` after a call just like in a standard Keras layer, and will be captured by any model that includes this layer. Regularization losses attached to Keras layers/models set as attributes of your layer will also get captured in the standard Keras regularization loss tracking.
(While Modules have no `losses` property, no-arg callables to compute the regularization losses may be tracked as dict values in a private `module._tf1_style_var_store._regularizers` property, but only for [`tf.compat.v1.layers`](../../layers) and `get_variable` weights and not for any other nested Keras layers/tf.Modules)
Variable scope / variable reuse: variable-scope based reuse in your decorated method will be respected, and work like variable-scope based reuse in TF1.
Variable Names/Pre-trained checkpoint loading: Variable naming from get\_variable and `compat.v1.layer` layers will match the TF1 names, so you should be able to re-use your old name-based checkpoints. Variable naming for Keras layers/models or for variables created by [`tf.Variable`](../../../../variable) may change when going to eager execution.
Training Arg if you decorate `layer.call`: Keras will pass a `training` arg to this layer if `call` contains a `training` arg or a `**kwargs` varargs in its call signature, similarly to how keras passes `training` to other layers in TF2 that have similar signatures in their `call` implementations. See more details in the docs on [`tf.keras.layers.Layer`](../../../../keras/layers/layer) to understand what will be passed and when. Note: tf.compat.v1.layers are usually not called with `training=None`, so the training arg to `forward_pass` might not feed through to them unless you pass it to their calls explicitly.
#### Caveats:
* TF2 will not prune unused variable updates (or unused outputs). You may need to adjust your forward pass code to avoid computations or variable updates that you don't intend to use.
* Avoid Nesting variable creation in tf.function inside of methods decorated with `track_tf1_style_variables` While the method may safely be used from inside a [`tf.function`](../../../../function), using a function inside of a decorated method may break the variable scoping.
* This decorator only adds implicit tracking for legacy tf1-style get\_variable / compat.v1.layers usage. If you would like to use nested Keras layers/models inside the decorated method, you need to assign them as attributes of your layer so that Keras/Module's standard object-oriented weights (and loss tracking for layers) will kick in. See the intro to modules, layers, and models [guide](https://www.tensorflow.org/guide/intro_to_modules) for more info. As a backup, the [`compat.v1.keras.utils.get_or_create_layer`](get_or_create_layer) method will ease tracking nested keras model weights and losses for existing TF1 code, but new code should use explicit tracking.
| Args |
| `method` | The method to decorate. This should belong to a custom tf.Module, tf.keras.layers.Layer, or tf.keras.Model. |
| Returns |
| The decorated method. |
tensorflow tf.compat.v1.keras.utils.get_or_create_layer tf.compat.v1.keras.utils.get\_or\_create\_layer
===============================================
Use this method to track nested keras models in a shim-decorated method.
```
tf.compat.v1.keras.utils.get_or_create_layer(
name, create_layer_method
)
```
This method can be used within a `tf.keras.Layer`'s methods decorated by the`track_tf1_style_variables` shim, to additionally track inner keras Model objects created within the same method. The inner model's variables and losses will be accessible via the outer model's `variables` and `losses` attributes.
This enables tracking of inner keras models using TF2 behaviors, with minimal changes to existing TF1-style code.
#### Example:
```
class NestedLayer(tf.keras.layers.Layer):
def __init__(self, units, *args, **kwargs):
super().__init__(*args, **kwargs)
self.units = units
def build_model(self):
inp = tf.keras.Input(shape=(5, 5))
dense_layer = tf.keras.layers.Dense(
10, name="dense", kernel_regularizer="l2",
kernel_initializer=tf.compat.v1.ones_initializer())
model = tf.keras.Model(inputs=inp, outputs=dense_layer(inp))
return model
@tf.compat.v1.keras.utils.track_tf1_style_variables
def call(self, inputs):
model = tf.compat.v1.keras.utils.get_or_create_layer(
"dense_model", self.build_model)
return model(inputs)
```
The inner model creation should be confined to its own zero-arg function, which should be passed into this method. In TF1, this method will immediately create and return the desired model, without any tracking.
| Args |
| `name` | A name to give the nested layer to track. |
| `create_layer_method` | a Callable that takes no args and returns the nested layer. |
| Returns |
| The created layer. |
tensorflow tf.compat.v1.keras.backend.name_scope tf.compat.v1.keras.backend.name\_scope
======================================
A context manager for use when defining a Python op.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.name_scope`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/backend/name_scope)
```
tf.compat.v1.keras.backend.name_scope(
name, default_name=None, values=None
)
```
This context manager validates that the given `values` are from the same graph, makes that graph the default graph, and pushes a name scope in that graph (see [`tf.Graph.name_scope`](../../../../graph#name_scope) for more details on that).
For example, to define a new Python op called `my_op`:
```
def my_op(a, b, c, name=None):
with tf.name_scope(name, "MyOp", [a, b, c]) as scope:
a = tf.convert_to_tensor(a, name="a")
b = tf.convert_to_tensor(b, name="b")
c = tf.convert_to_tensor(c, name="c")
# Define some computation that uses `a`, `b`, and `c`.
return foo_op(..., name=scope)
```
| Args |
| `name` | The name argument that is passed to the op function. |
| `default_name` | The default name to use if the `name` argument is `None`. |
| `values` | The list of `Tensor` arguments that are passed to the op function. |
| Raises |
| `TypeError` | if `default_name` is passed in but not a string. |
| Attributes |
| `name` | |
Methods
-------
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/ops.py#L6834-L6835)
```
__enter__()
```
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/framework/ops.py#L6837-L6838)
```
__exit__(
*exc_info
)
```
tensorflow tf.compat.v1.keras.backend.get_session tf.compat.v1.keras.backend.get\_session
=======================================
Returns the TF session to be used by the backend.
```
tf.compat.v1.keras.backend.get_session(
op_input_list=()
)
```
If a default TensorFlow session is available, we will return it.
Else, we will return the global Keras session assuming it matches the current graph.
If no global Keras session exists at this point: we will create a new global session.
Note that you can manually set the global session via `K.set_session(sess)`.
| Args |
| `op_input_list` | An option sequence of tensors or ops, which will be used to determine the current graph. Otherwise the default graph will be used. |
| Returns |
| A TensorFlow session. |
tensorflow tf.compat.v1.keras.backend.set_session tf.compat.v1.keras.backend.set\_session
=======================================
Sets the global TensorFlow session.
```
tf.compat.v1.keras.backend.set_session(
session
)
```
| Args |
| `session` | A TF Session. |
tensorflow Module: tf.compat.v1.keras.optimizers.legacy Module: tf.compat.v1.keras.optimizers.legacy
============================================
Public API for tf.keras.optimizers.legacy namespace.
Classes
-------
[`class Adadelta`](../../../../keras/optimizers/legacy/adadelta): Optimizer that implements the Adadelta algorithm.
[`class Adagrad`](../../../../keras/optimizers/legacy/adagrad): Optimizer that implements the Adagrad algorithm.
[`class Adam`](../../../../keras/optimizers/legacy/adam): Optimizer that implements the Adam algorithm.
[`class Adamax`](../../../../keras/optimizers/legacy/adamax): Optimizer that implements the Adamax algorithm.
[`class Ftrl`](../../../../keras/optimizers/legacy/ftrl): Optimizer that implements the FTRL algorithm.
[`class Nadam`](../../../../keras/optimizers/legacy/nadam): Optimizer that implements the NAdam algorithm.
[`class Optimizer`](../../../../keras/optimizers/legacy/optimizer): Base class for Keras optimizers.
[`class RMSprop`](../../../../keras/optimizers/legacy/rmsprop): Optimizer that implements the RMSprop algorithm.
[`class SGD`](../../../../keras/optimizers/legacy/sgd): Gradient descent (with momentum) optimizer.
tensorflow Module: tf.compat.v1.keras.optimizers.schedules Module: tf.compat.v1.keras.optimizers.schedules
===============================================
Public API for tf.keras.optimizers.schedules namespace.
Classes
-------
[`class CosineDecay`](../../../../keras/optimizers/schedules/cosinedecay): A LearningRateSchedule that uses a cosine decay schedule.
[`class CosineDecayRestarts`](../../../../keras/optimizers/schedules/cosinedecayrestarts): A LearningRateSchedule that uses a cosine decay schedule with restarts.
[`class ExponentialDecay`](../../../../keras/optimizers/schedules/exponentialdecay): A LearningRateSchedule that uses an exponential decay schedule.
[`class InverseTimeDecay`](../../../../keras/optimizers/schedules/inversetimedecay): A LearningRateSchedule that uses an inverse time decay schedule.
[`class LearningRateSchedule`](../../../../keras/optimizers/schedules/learningrateschedule): The learning rate schedule base class.
[`class PiecewiseConstantDecay`](../../../../keras/optimizers/schedules/piecewiseconstantdecay): A LearningRateSchedule that uses a piecewise constant decay schedule.
[`class PolynomialDecay`](../../../../keras/optimizers/schedules/polynomialdecay): A LearningRateSchedule that uses a polynomial decay schedule.
Functions
---------
[`deserialize(...)`](../../../../keras/optimizers/schedules/deserialize): Instantiates a `LearningRateSchedule` object from a serialized form.
[`serialize(...)`](../../../../keras/optimizers/schedules/serialize): Serializes a `LearningRateSchedule` into a JSON-compatible representation.
tensorflow Module: tf.compat.v1.keras.applications.xception Module: tf.compat.v1.keras.applications.xception
================================================
Xception V1 model for Keras.
On ImageNet, this model gets to a top-1 validation accuracy of 0.790 and a top-5 validation accuracy of 0.945.
#### Reference:
* [Xception: Deep Learning with Depthwise Separable Convolutions](https://arxiv.org/abs/1610.02357) (CVPR 2017)
Functions
---------
[`Xception(...)`](../../../../keras/applications/xception/xception): Instantiates the Xception architecture.
[`decode_predictions(...)`](../../../../keras/applications/xception/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/xception/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.densenet Module: tf.compat.v1.keras.applications.densenet
================================================
DenseNet models for Keras.
#### Reference:
* [Densely Connected Convolutional Networks](https://arxiv.org/abs/1608.06993) (CVPR 2017)
Functions
---------
[`DenseNet121(...)`](../../../../keras/applications/densenet/densenet121): Instantiates the Densenet121 architecture.
[`DenseNet169(...)`](../../../../keras/applications/densenet/densenet169): Instantiates the Densenet169 architecture.
[`DenseNet201(...)`](../../../../keras/applications/densenet/densenet201): Instantiates the Densenet201 architecture.
[`decode_predictions(...)`](../../../../keras/applications/densenet/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/densenet/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.vgg16 Module: tf.compat.v1.keras.applications.vgg16
=============================================
VGG16 model for Keras.
#### Reference:
* [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556) (ICLR 2015)
Functions
---------
[`VGG16(...)`](../../../../keras/applications/vgg16/vgg16): Instantiates the VGG16 model.
[`decode_predictions(...)`](../../../../keras/applications/vgg16/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/vgg16/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.inception_v3 Module: tf.compat.v1.keras.applications.inception\_v3
=====================================================
Inception V3 model for Keras.
#### Reference:
* [Rethinking the Inception Architecture for Computer Vision](http://arxiv.org/abs/1512.00567) (CVPR 2016)
Functions
---------
[`InceptionV3(...)`](../../../../keras/applications/inception_v3/inceptionv3): Instantiates the Inception v3 architecture.
[`decode_predictions(...)`](../../../../keras/applications/inception_v3/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/inception_v3/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.imagenet_utils Module: tf.compat.v1.keras.applications.imagenet\_utils
=======================================================
Utilities for ImageNet data preprocessing & prediction decoding.
Functions
---------
[`decode_predictions(...)`](../../../../keras/applications/imagenet_utils/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/imagenet_utils/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.inception_resnet_v2 Module: tf.compat.v1.keras.applications.inception\_resnet\_v2
=============================================================
Inception-ResNet V2 model for Keras.
#### Reference:
* [Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning](https://arxiv.org/abs/1602.07261) (AAAI 2017)
Functions
---------
[`InceptionResNetV2(...)`](../../../../keras/applications/inception_resnet_v2/inceptionresnetv2): Instantiates the Inception-ResNet v2 architecture.
[`decode_predictions(...)`](../../../../keras/applications/inception_resnet_v2/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/inception_resnet_v2/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
| programming_docs |
tensorflow Module: tf.compat.v1.keras.applications.mobilenet Module: tf.compat.v1.keras.applications.mobilenet
=================================================
MobileNet v1 models for Keras.
MobileNet is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance. The number of parameters and number of multiply-adds can be modified by using the `alpha` parameter, which increases/decreases the number of filters in each layer. By altering the image size and `alpha` parameter, all 16 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using `alpha` values of 1.0 (also called 100 % MobileNet), 0.75, 0.5 and 0.25. For each of these `alpha` values, weights for 4 different input image sizes are provided (224, 192, 160, 128).
The following table describes the size and accuracy of the 100% MobileNet
on size 224 x 224:
------------------
Width Multiplier (alpha) | ImageNet Acc | Multiply-Adds (M) | Params (M)
------------------------------------------------------------------------
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 0.75 MobileNet-224 | 68.4 % | 325 | 2.6 | | 0.50 MobileNet-224 | 63.7 % | 149 | 1.3 |
| 0.25 MobileNet-224 | 50.6 % | 41 | 0.5 |
------------------------------------------
The following table describes the performance of
the 100 % MobileNet on various input sizes:
-------------------------------------------
```
Resolution | ImageNet Acc | Multiply-Adds (M) | Params (M)
```
| 1.0 MobileNet-224 | 70.6 % | 569 | 4.2 | | 1.0 MobileNet-192 | 69.1 % | 418 | 4.2 | | 1.0 MobileNet-160 | 67.2 % | 290 | 4.2 |
| 1.0 MobileNet-128 | 64.4 % | 186 | 4.2 |
------------------------------------------
Reference:
* [MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications](https://arxiv.org/abs/1704.04861)
Functions
---------
[`MobileNet(...)`](../../../../keras/applications/mobilenet/mobilenet): Instantiates the MobileNet architecture.
[`decode_predictions(...)`](../../../../keras/applications/mobilenet/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/mobilenet/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.efficientnet_v2 Module: tf.compat.v1.keras.applications.efficientnet\_v2
========================================================
EfficientNet V2 models for Keras.
#### Reference:
* [EfficientNetV2: Smaller Models and Faster Training](https://arxiv.org/abs/2104.00298) (ICML 2021)
Functions
---------
[`EfficientNetV2B0(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2b0): Instantiates the EfficientNetV2B0 architecture.
[`EfficientNetV2B1(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2b1): Instantiates the EfficientNetV2B1 architecture.
[`EfficientNetV2B2(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2b2): Instantiates the EfficientNetV2B2 architecture.
[`EfficientNetV2B3(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2b3): Instantiates the EfficientNetV2B3 architecture.
[`EfficientNetV2L(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2l): Instantiates the EfficientNetV2L architecture.
[`EfficientNetV2M(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2m): Instantiates the EfficientNetV2M architecture.
[`EfficientNetV2S(...)`](../../../../keras/applications/efficientnet_v2/efficientnetv2s): Instantiates the EfficientNetV2S architecture.
[`decode_predictions(...)`](../../../../keras/applications/efficientnet_v2/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/efficientnet_v2/preprocess_input): A placeholder method for backward compatibility.
tensorflow Module: tf.compat.v1.keras.applications.resnet_rs Module: tf.compat.v1.keras.applications.resnet\_rs
==================================================
ResNet-RS models for Keras.
#### Reference:
* [Revisiting ResNets: Improved Training and Scaling Strategies](https://arxiv.org/pdf/2103.07579.pdf)
Functions
---------
[`ResNetRS101(...)`](../../../../keras/applications/resnet_rs/resnetrs101): Build ResNet-RS101 model.
[`ResNetRS152(...)`](../../../../keras/applications/resnet_rs/resnetrs152): Instantiates the ResNetRS152 architecture.
[`ResNetRS200(...)`](../../../../keras/applications/resnet_rs/resnetrs200): Instantiates the ResNetRS200 architecture.
[`ResNetRS270(...)`](../../../../keras/applications/resnet_rs/resnetrs270): Instantiates the ResNetRS270 architecture.
[`ResNetRS350(...)`](../../../../keras/applications/resnet_rs/resnetrs350): Instantiates the ResNetRS350 architecture.
[`ResNetRS420(...)`](../../../../keras/applications/resnet_rs/resnetrs420): Instantiates the ResNetRS420 architecture.
[`ResNetRS50(...)`](../../../../keras/applications/resnet_rs/resnetrs50): Instantiates the ResNetRS50 architecture.
[`decode_predictions(...)`](../../../../keras/applications/resnet_rs/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/resnet_rs/preprocess_input): A placeholder method for backward compatibility.
tensorflow Module: tf.compat.v1.keras.applications.nasnet Module: tf.compat.v1.keras.applications.nasnet
==============================================
NASNet-A models for Keras.
NASNet refers to Neural Architecture Search Network, a family of models that were designed automatically by learning the model architectures directly on the dataset of interest.
Here we consider NASNet-A, the highest performance model that was found for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset, obtaining state of the art performance on CIFAR-10 and ImageNet 2012. Only the NASNet-A models, and their respective weights, which are suited for ImageNet 2012 are provided.
The below table describes the performance on ImageNet 2012:
-----------------------------------------------------------
```
Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M)
```
| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 |
| NASNet-A (6 @ 4032) | 82.7 % | 96.2 % | 23.8 B | 88.9 |
---------------------------------------------------------
#### Reference:
* [Learning Transferable Architectures for Scalable Image Recognition](https://arxiv.org/abs/1707.07012) (CVPR 2018)
Functions
---------
[`NASNetLarge(...)`](../../../../keras/applications/nasnet/nasnetlarge): Instantiates a NASNet model in ImageNet mode.
[`NASNetMobile(...)`](../../../../keras/applications/nasnet/nasnetmobile): Instantiates a Mobile NASNet model in ImageNet mode.
[`decode_predictions(...)`](../../../../keras/applications/nasnet/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/nasnet/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.resnet_v2 Module: tf.compat.v1.keras.applications.resnet\_v2
==================================================
ResNet v2 models for Keras.
#### Reference:
* [Identity Mappings in Deep Residual Networks](https://arxiv.org/abs/1603.05027) (CVPR 2016)
Functions
---------
[`ResNet101V2(...)`](../../../../keras/applications/resnet_v2/resnet101v2): Instantiates the ResNet101V2 architecture.
[`ResNet152V2(...)`](../../../../keras/applications/resnet_v2/resnet152v2): Instantiates the ResNet152V2 architecture.
[`ResNet50V2(...)`](../../../../keras/applications/resnet_v2/resnet50v2): Instantiates the ResNet50V2 architecture.
[`decode_predictions(...)`](../../../../keras/applications/resnet_v2/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/resnet_v2/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.resnet50 Module: tf.compat.v1.keras.applications.resnet50
================================================
Public API for tf.keras.applications.resnet50 namespace.
Functions
---------
[`ResNet50(...)`](../../../../keras/applications/resnet50/resnet50): Instantiates the ResNet50 architecture.
[`decode_predictions(...)`](../../../../keras/applications/resnet50/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/resnet50/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.vgg19 Module: tf.compat.v1.keras.applications.vgg19
=============================================
VGG19 model for Keras.
#### Reference:
* [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556) (ICLR 2015)
Functions
---------
[`VGG19(...)`](../../../../keras/applications/vgg19/vgg19): Instantiates the VGG19 architecture.
[`decode_predictions(...)`](../../../../keras/applications/vgg19/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/vgg19/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.regnet Module: tf.compat.v1.keras.applications.regnet
==============================================
RegNet models for Keras.
#### References:
* [Designing Network Design Spaces](https://arxiv.org/abs/2003.13678) (CVPR 2020)
* [Fast and Accurate Model Scaling](https://arxiv.org/abs/2103.06877) (CVPR 2021)
Functions
---------
[`RegNetX002(...)`](../../../../keras/applications/regnet/regnetx002): Instantiates the RegNetX002 architecture.
[`RegNetX004(...)`](../../../../keras/applications/regnet/regnetx004): Instantiates the RegNetX004 architecture.
[`RegNetX006(...)`](../../../../keras/applications/regnet/regnetx006): Instantiates the RegNetX006 architecture.
[`RegNetX008(...)`](../../../../keras/applications/regnet/regnetx008): Instantiates the RegNetX008 architecture.
[`RegNetX016(...)`](../../../../keras/applications/regnet/regnetx016): Instantiates the RegNetX016 architecture.
[`RegNetX032(...)`](../../../../keras/applications/regnet/regnetx032): Instantiates the RegNetX032 architecture.
[`RegNetX040(...)`](../../../../keras/applications/regnet/regnetx040): Instantiates the RegNetX040 architecture.
[`RegNetX064(...)`](../../../../keras/applications/regnet/regnetx064): Instantiates the RegNetX064 architecture.
[`RegNetX080(...)`](../../../../keras/applications/regnet/regnetx080): Instantiates the RegNetX080 architecture.
[`RegNetX120(...)`](../../../../keras/applications/regnet/regnetx120): Instantiates the RegNetX120 architecture.
[`RegNetX160(...)`](../../../../keras/applications/regnet/regnetx160): Instantiates the RegNetX160 architecture.
[`RegNetX320(...)`](../../../../keras/applications/regnet/regnetx320): Instantiates the RegNetX320 architecture.
[`RegNetY002(...)`](../../../../keras/applications/regnet/regnety002): Instantiates the RegNetY002 architecture.
[`RegNetY004(...)`](../../../../keras/applications/regnet/regnety004): Instantiates the RegNetY004 architecture.
[`RegNetY006(...)`](../../../../keras/applications/regnet/regnety006): Instantiates the RegNetY006 architecture.
[`RegNetY008(...)`](../../../../keras/applications/regnet/regnety008): Instantiates the RegNetY008 architecture.
[`RegNetY016(...)`](../../../../keras/applications/regnet/regnety016): Instantiates the RegNetY016 architecture.
[`RegNetY032(...)`](../../../../keras/applications/regnet/regnety032): Instantiates the RegNetY032 architecture.
[`RegNetY040(...)`](../../../../keras/applications/regnet/regnety040): Instantiates the RegNetY040 architecture.
[`RegNetY064(...)`](../../../../keras/applications/regnet/regnety064): Instantiates the RegNetY064 architecture.
[`RegNetY080(...)`](../../../../keras/applications/regnet/regnety080): Instantiates the RegNetY080 architecture.
[`RegNetY120(...)`](../../../../keras/applications/regnet/regnety120): Instantiates the RegNetY120 architecture.
[`RegNetY160(...)`](../../../../keras/applications/regnet/regnety160): Instantiates the RegNetY160 architecture.
[`RegNetY320(...)`](../../../../keras/applications/regnet/regnety320): Instantiates the RegNetY320 architecture.
[`decode_predictions(...)`](../../../../keras/applications/regnet/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/regnet/preprocess_input): A placeholder method for backward compatibility.
tensorflow Module: tf.compat.v1.keras.applications.mobilenet_v3 Module: tf.compat.v1.keras.applications.mobilenet\_v3
=====================================================
MobileNet v3 models for Keras.
Functions
---------
[`decode_predictions(...)`](../../../../keras/applications/mobilenet_v3/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/mobilenet_v3/preprocess_input): A placeholder method for backward compatibility.
tensorflow Module: tf.compat.v1.keras.applications.mobilenet_v2 Module: tf.compat.v1.keras.applications.mobilenet\_v2
=====================================================
MobileNet v2 models for Keras.
MobileNetV2 is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices.
MobileNetV2 is very similar to the original MobileNet, except that it uses inverted residual blocks with bottlenecking features. It has a drastically lower parameter count than the original MobileNet. MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance.
The number of parameters and number of multiply-adds can be modified by using the `alpha` parameter, which increases/decreases the number of filters in each layer. By altering the image size and `alpha` parameter, all 22 models from the paper can be built, with ImageNet weights provided.
The paper demonstrates the performance of MobileNets using `alpha` values of 1.0 (also called 100 % MobileNet), 0.35, 0.5, 0.75, 1.0, 1.3, and 1.4 For each of these `alpha` values, weights for 5 different input image sizes are provided (224, 192, 160, 128, and 96).
The following table describes the performance of
MobileNet on various input sizes:
---------------------------------
MACs stands for Multiply Adds Classification Checkpoint|MACs (M)|Parameters (M)|Top 1 Accuracy|Top 5 Accuracy --------------------------|------------|---------------|---------|----|--------- | [mobilenet\_v2\_1.4\_224] | 582 | 6.06 | 75.0 | 92.5 | | [mobilenet\_v2\_1.3\_224] | 509 | 5.34 | 74.4 | 92.1 | | [mobilenet\_v2\_1.0\_224] | 300 | 3.47 | 71.8 | 91.0 | | [mobilenet\_v2\_1.0\_192] | 221 | 3.47 | 70.7 | 90.1 | | [mobilenet\_v2\_1.0\_160] | 154 | 3.47 | 68.8 | 89.0 | | [mobilenet\_v2\_1.0\_128] | 99 | 3.47 | 65.3 | 86.9 | | [mobilenet\_v2\_1.0\_96] | 56 | 3.47 | 60.3 | 83.2 | | [mobilenet\_v2\_0.75\_224] | 209 | 2.61 | 69.8 | 89.6 | | [mobilenet\_v2\_0.75\_192] | 153 | 2.61 | 68.7 | 88.9 | | [mobilenet\_v2\_0.75\_160] | 107 | 2.61 | 66.4 | 87.3 | | [mobilenet\_v2\_0.75\_128] | 69 | 2.61 | 63.2 | 85.3 | | [mobilenet\_v2\_0.75\_96] | 39 | 2.61 | 58.8 | 81.6 | | [mobilenet\_v2\_0.5\_224] | 97 | 1.95 | 65.4 | 86.4 | | [mobilenet\_v2\_0.5\_192] | 71 | 1.95 | 63.9 | 85.4 | | [mobilenet\_v2\_0.5\_160] | 50 | 1.95 | 61.0 | 83.2 | | [mobilenet\_v2\_0.5\_128] | 32 | 1.95 | 57.7 | 80.8 | | [mobilenet\_v2\_0.5\_96] | 18 | 1.95 | 51.2 | 75.8 | | [mobilenet\_v2\_0.35\_224] | 59 | 1.66 | 60.3 | 82.9 | | [mobilenet\_v2\_0.35\_192] | 43 | 1.66 | 58.2 | 81.2 | | [mobilenet\_v2\_0.35\_160] | 30 | 1.66 | 55.7 | 79.1 | | [mobilenet\_v2\_0.35\_128] | 20 | 1.66 | 50.8 | 75.0 | | [mobilenet\_v2\_0.35\_96] | 11 | 1.66 | 45.5 | 70.4 |
Reference:
* [MobileNetV2: Inverted Residuals and Linear Bottlenecks](https://arxiv.org/abs/1801.04381) (CVPR 2018)
Functions
---------
[`MobileNetV2(...)`](../../../../keras/applications/mobilenet_v2/mobilenetv2): Instantiates the MobileNetV2 architecture.
[`decode_predictions(...)`](../../../../keras/applications/mobilenet_v2/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/mobilenet_v2/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.resnet Module: tf.compat.v1.keras.applications.resnet
==============================================
ResNet models for Keras.
#### Reference:
* [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) (CVPR 2015)
Functions
---------
[`ResNet101(...)`](../../../../keras/applications/resnet/resnet101): Instantiates the ResNet101 architecture.
[`ResNet152(...)`](../../../../keras/applications/resnet/resnet152): Instantiates the ResNet152 architecture.
[`ResNet50(...)`](../../../../keras/applications/resnet50/resnet50): Instantiates the ResNet50 architecture.
[`decode_predictions(...)`](../../../../keras/applications/resnet50/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/resnet50/preprocess_input): Preprocesses a tensor or Numpy array encoding a batch of images.
tensorflow Module: tf.compat.v1.keras.applications.efficientnet Module: tf.compat.v1.keras.applications.efficientnet
====================================================
EfficientNet models for Keras.
#### Reference:
* [EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks](https://arxiv.org/abs/1905.11946) (ICML 2019)
Functions
---------
[`EfficientNetB0(...)`](../../../../keras/applications/efficientnet/efficientnetb0): Instantiates the EfficientNetB0 architecture.
[`EfficientNetB1(...)`](../../../../keras/applications/efficientnet/efficientnetb1): Instantiates the EfficientNetB1 architecture.
[`EfficientNetB2(...)`](../../../../keras/applications/efficientnet/efficientnetb2): Instantiates the EfficientNetB2 architecture.
[`EfficientNetB3(...)`](../../../../keras/applications/efficientnet/efficientnetb3): Instantiates the EfficientNetB3 architecture.
[`EfficientNetB4(...)`](../../../../keras/applications/efficientnet/efficientnetb4): Instantiates the EfficientNetB4 architecture.
[`EfficientNetB5(...)`](../../../../keras/applications/efficientnet/efficientnetb5): Instantiates the EfficientNetB5 architecture.
[`EfficientNetB6(...)`](../../../../keras/applications/efficientnet/efficientnetb6): Instantiates the EfficientNetB6 architecture.
[`EfficientNetB7(...)`](../../../../keras/applications/efficientnet/efficientnetb7): Instantiates the EfficientNetB7 architecture.
[`decode_predictions(...)`](../../../../keras/applications/efficientnet/decode_predictions): Decodes the prediction of an ImageNet model.
[`preprocess_input(...)`](../../../../keras/applications/efficientnet/preprocess_input): A placeholder method for backward compatibility.
tensorflow Module: tf.compat.v1.keras.preprocessing.text Module: tf.compat.v1.keras.preprocessing.text
=============================================
Utilities for text input preprocessing.
Classes
-------
[`class Tokenizer`](../../../../keras/preprocessing/text/tokenizer): Text tokenization utility class.
Functions
---------
[`hashing_trick(...)`](../../../../keras/preprocessing/text/hashing_trick): Converts a text to a sequence of indexes in a fixed-size hashing space.
[`one_hot(...)`](../../../../keras/preprocessing/text/one_hot): One-hot encodes a text into a list of word indexes of size `n`.
[`text_to_word_sequence(...)`](../../../../keras/preprocessing/text/text_to_word_sequence): Converts a text to a sequence of words (or tokens).
[`tokenizer_from_json(...)`](../../../../keras/preprocessing/text/tokenizer_from_json): Parses a JSON tokenizer configuration and returns a tokenizer instance.
| programming_docs |
tensorflow Module: tf.compat.v1.keras.preprocessing.sequence Module: tf.compat.v1.keras.preprocessing.sequence
=================================================
Utilities for preprocessing sequence data.
Classes
-------
[`class TimeseriesGenerator`](../../../../keras/preprocessing/sequence/timeseriesgenerator): Utility class for generating batches of temporal data.
Functions
---------
[`make_sampling_table(...)`](../../../../keras/preprocessing/sequence/make_sampling_table): Generates a word rank-based probabilistic sampling table.
[`pad_sequences(...)`](../../../../keras/utils/pad_sequences): Pads sequences to the same length.
[`skipgrams(...)`](../../../../keras/preprocessing/sequence/skipgrams): Generates skipgram word pairs.
tensorflow Module: tf.compat.v1.keras.preprocessing.image Module: tf.compat.v1.keras.preprocessing.image
==============================================
Utilies for image preprocessing and augmentation.
Classes
-------
[`class DirectoryIterator`](../../../../keras/preprocessing/image/directoryiterator): Iterator capable of reading images from a directory on disk.
[`class ImageDataGenerator`](../../../../keras/preprocessing/image/imagedatagenerator): Generate batches of tensor image data with real-time data augmentation.
[`class Iterator`](../../../../keras/preprocessing/image/iterator): Base class for image data iterators.
[`class NumpyArrayIterator`](../../../../keras/preprocessing/image/numpyarrayiterator): Iterator yielding data from a Numpy array.
Functions
---------
[`apply_affine_transform(...)`](../../../../keras/preprocessing/image/apply_affine_transform): Applies an affine transformation specified by the parameters given.
[`apply_brightness_shift(...)`](../../../../keras/preprocessing/image/apply_brightness_shift): Performs a brightness shift.
[`apply_channel_shift(...)`](../../../../keras/preprocessing/image/apply_channel_shift): Performs a channel shift.
[`array_to_img(...)`](../../../../keras/utils/array_to_img): Converts a 3D Numpy array to a PIL Image instance.
[`img_to_array(...)`](../../../../keras/utils/img_to_array): Converts a PIL Image instance to a Numpy array.
[`load_img(...)`](../../../../keras/utils/load_img): Loads an image into PIL format.
[`random_brightness(...)`](../../../../keras/preprocessing/image/random_brightness): Performs a random brightness shift.
[`random_channel_shift(...)`](../../../../keras/preprocessing/image/random_channel_shift): Performs a random channel shift.
[`random_rotation(...)`](../../../../keras/preprocessing/image/random_rotation): Performs a random rotation of a Numpy image tensor.
[`random_shear(...)`](../../../../keras/preprocessing/image/random_shear): Performs a random spatial shear of a Numpy image tensor.
[`random_shift(...)`](../../../../keras/preprocessing/image/random_shift): Performs a random spatial shift of a Numpy image tensor.
[`random_zoom(...)`](../../../../keras/preprocessing/image/random_zoom): Performs a random spatial zoom of a Numpy image tensor.
[`save_img(...)`](../../../../keras/utils/save_img): Saves an image stored as a Numpy array to a path or file object.
tensorflow tf.compat.v1.keras.initializers.lecun_normal tf.compat.v1.keras.initializers.lecun\_normal
=============================================
Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: [`VarianceScaling`](variancescaling)
```
tf.compat.v1.keras.initializers.lecun_normal(
seed=None
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../../../function).
To switch to TF2 APIs, move to using either [`tf.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/VarianceScaling) or [`tf.keras.initializers.VarianceScaling`](../../../../keras/initializers/variancescaling) (neither from [`compat.v1`](../../../v1)) and pass the dtype when calling the initializer.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.variance_scaling_initializer(
scale=scale,
mode=mode,
distribution=distribution
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.VarianceScaling(
scale=scale,
mode=mode,
distribution=distribution
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `scale` | `scale` | No change to defaults |
| `mode` | `mode` | No change to defaults |
| `distribution` | `distribution` | No change to defaults. 'normal' maps to 'truncated\_normal' |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is:
* number of input units in the weight tensor, if mode = "fan\_in"
* number of output units, if mode = "fan\_out"
* average of the numbers of input and output units, if mode = "fan\_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
| Args |
| `scale` | Scaling factor (positive float). |
| `mode` | One of "fan\_in", "fan\_out", "fan\_avg". |
| `distribution` | Random distribution to use. One of "normal", "uniform". |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
| Raises |
| `ValueError` | In case of an invalid value for the "scale", mode" or "distribution" arguments. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/initializers/initializers_v1.py#L419-L420)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.he_uniform tf.compat.v1.keras.initializers.he\_uniform
===========================================
Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: [`VarianceScaling`](variancescaling)
```
tf.compat.v1.keras.initializers.he_uniform(
seed=None
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../../../function).
To switch to TF2 APIs, move to using either [`tf.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/VarianceScaling) or [`tf.keras.initializers.VarianceScaling`](../../../../keras/initializers/variancescaling) (neither from [`compat.v1`](../../../v1)) and pass the dtype when calling the initializer.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.variance_scaling_initializer(
scale=scale,
mode=mode,
distribution=distribution
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.VarianceScaling(
scale=scale,
mode=mode,
distribution=distribution
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `scale` | `scale` | No change to defaults |
| `mode` | `mode` | No change to defaults |
| `distribution` | `distribution` | No change to defaults. 'normal' maps to 'truncated\_normal' |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is:
* number of input units in the weight tensor, if mode = "fan\_in"
* number of output units, if mode = "fan\_out"
* average of the numbers of input and output units, if mode = "fan\_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
| Args |
| `scale` | Scaling factor (positive float). |
| `mode` | One of "fan\_in", "fan\_out", "fan\_avg". |
| `distribution` | Random distribution to use. One of "normal", "uniform". |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
| Raises |
| `ValueError` | In case of an invalid value for the "scale", mode" or "distribution" arguments. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/initializers/initializers_v1.py#L452-L453)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.Ones tf.compat.v1.keras.initializers.Ones
====================================
Initializer that generates tensors initialized to 1.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.ones`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Ones), [`tf.compat.v1.keras.initializers.ones`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Ones), [`tf.compat.v1.ones_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Ones)
```
tf.compat.v1.keras.initializers.Ones(
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
This API is compatible with TF2 behavior and [`tf.function`](../../../../function), and can be migrated immediately with [`tf.keras.initializers.ones`](../../../../keras/initializers/ones).
Before:
```
>>> initializer = tf.compat.v1.keras.initializers.ones()
>>> initializer((1, 1))
<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[1.]], dtype=float32)>
```
After:
```
>>> initializer = tf.keras.initializers.ones()
>>> initializer((1, 1))
<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[1.]], dtype=float32)>
```
Description
-----------
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L214-L215)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L209-L212)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.RandomNormal tf.compat.v1.keras.initializers.RandomNormal
============================================
Initializer that generates a normal distribution.
Inherits From: [`random_normal_initializer`](../../random_normal_initializer)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.keras.initializers.normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/RandomNormal), [`tf.compat.v1.keras.initializers.random_normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/RandomNormal)
```
tf.compat.v1.keras.initializers.RandomNormal(
mean=0.0,
stddev=0.05,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy compat.v1 api, [`tf.compat.v1.keras.initializers.RandomNormal`](randomnormal) is compatible with eager execution and [`tf.function`](../../../../function).
To switch to native TF2, switch to using [`tf.keras.initializers.RandomNormal`](../../../../keras/initializers/randomnormal) (not from [`compat.v1`](../../../v1)) and if you need to change the default dtype use [`tf.keras.backend.set_floatx(float_dtype)`](../../../../keras/backend/set_floatx) or pass the dtype when calling the initializer, rather than passing it when constructing the initializer.
Random seed behavior: Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```
initializer = tf.compat.v1.keras.initializers.RandomNormal(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.RandomNormal(
mean=mean,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | No change to defaults |
| `seed` | `seed` | Different random number generation semantics (to change in a future version). If set, the TF2 version will use stateless random number generation which will produce the exact same initialization even across multiple calls of the initializer instance. the [`compat.v1`](../../../v1) version will generate new initializations each time. Do not set a seed if you need different initializations each time. Instead either set a global tf seed with [`tf.random.set_seed`](../../../../random/set_seed) if you need determinism, or initialize each weight with a separate initializer instance and a different seed. |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
[`compat.v1`](../../../v1) Fixed seed behavior:
```
initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
After:
```
initializer = tf.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
Description
-----------
| Args |
| `mean` | a python scalar or a scalar tensor. Mean of the random values to generate. |
| `stddev` | a python scalar or a scalar tensor. Standard deviation of the random values to generate. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L567-L573)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L561-L565)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
| programming_docs |
tensorflow tf.compat.v1.keras.initializers.Constant tf.compat.v1.keras.initializers.Constant
========================================
Initializer that generates tensors with constant values.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.constant_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Constant), [`tf.compat.v1.initializers.constant`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Constant), [`tf.compat.v1.keras.initializers.constant`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Constant)
```
tf.compat.v1.keras.initializers.Constant(
value=0,
dtype=tf.dtypes.float32,
verify_shape=False
)
```
Migrate to TF2
--------------
Although it is a legacy API endpoint, [`tf.compat.v1.constant_initializer`](constant) is compatible with eager execution and [`tf.function`](../../../../function).
To migrate to a non-legacy TF2 API, please use [`tf.constant*initializer*`](../../../../constant_initializer) instead. The `dtype` argument in <a href="../../../../../tf/compat/v1/keras/initializers/Constant#*init*\_">`tf.compat.v1.constant*initializer.**init*_()` does not exist in [`tf.constant*initializer.**init*_()`](../../../../constant_initializer#__init__). However, you can specify the `dtype` in `__call__()` in both cases.
In the [`compat.v1`](../../../v1) symbol, if `verify_shape` is set to `True`, an exception is raised when initializing a variable with a different shape from `value`. If set to `False`, `value` is reshaped to initialize the variable if necessary. An exception would only be raised when the number of elements are different.
The `verify_shape` argument is not supported in TF2. Using [`tf.constant_initializer`](../../../../constant_initializer) is equivalent to setting `verify_shape` to `False`.
#### Structural Mapping to TF2
Before:
```
value = [0, 1, 2, 3, 4, 5, 6, 7]
initializer = tf.compat.v1.constant_initializer(
value=value,
dtype=tf.float32,
verify_shape=False)
variable = tf.Variable(initializer(shape=[2, 4]))
```
After:
```
value = [0, 1, 2, 3, 4, 5, 6, 7]
initializer = tf.constant_initializer(value=value)
tf.Variable(initializer(shape=[2, 4], dtype=tf.float32))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `value` | `value` | In constructor |
| `dtype` | `dtype` | In `__call__()` method |
| `verify_shape` | Not Supported | Equivalent to set to `False` |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Before & After Usage Example
Before:
```
value = [1., 2., 3., 4.]
initializer = tf.compat.v1.constant_initializer(
value=value, dtype=tf.float32, verify_shape=True)
tf.Variable(initializer(shape=[2, 2])).numpy()
Traceback (most recent call last):
TypeError: Expected Tensor's shape: (2, 2), got (4,).
initializer = tf.compat.v1.constant_initializer(
value=value, dtype=tf.float32, verify_shape=False)
tf.Variable(initializer(shape=[2, 2])).numpy()
array([[1., 2.],
[3., 4.]], dtype=float32)
```
After:
```
value = [1., 2., 3., 4.]
initializer = tf.constant_initializer(value=value)
tf.Variable(initializer(shape=[2, 2], dtype=tf.float32)).numpy()
array([[1., 2.],
[3., 4.]], dtype=float32)
```
Description
-----------
The resulting tensor is populated with values of type `dtype`, as specified by arguments `value` following the desired `shape` of the new tensor (see examples below).
The argument `value` can be a constant value, or a list of values of type `dtype`. If `value` is a list, then the length of the list must be less than or equal to the number of elements implied by the desired shape of the tensor. In the case where the total number of elements in `value` is less than the number of elements required by the tensor shape, the last element in `value` will be used to fill the remaining entries. If the total number of elements in `value` is greater than the number of elements required by the tensor shape, the initializer will raise a `ValueError`.
| Args |
| `value` | A Python scalar, list or tuple of values, or a N-dimensional numpy array. All elements of the initialized variable will be set to the corresponding value in the `value` argument. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. |
| `verify_shape` | Boolean that enables verification of the shape of `value`. If `True`, the initializer will throw an error if the shape of `value` is not compatible with the shape of the initialized tensor. |
| Raises |
| `TypeError` | If the input `value` is not one of the expected types. |
#### Examples:
The following example can be rewritten using a numpy.ndarray instead of the `value` list, even reshaped, as shown in the two commented lines below the `value` list initialization.
```
value = [0, 1, 2, 3, 4, 5, 6, 7]
init = tf.compat.v1.constant_initializer(value)
# fitting shape
with tf.compat.v1.Session():
x = tf.compat.v1.get_variable('x', shape=[2, 4], initializer=init)
x.initializer.run()
print(x.eval())
[[0. 1. 2. 3.]
[4. 5. 6. 7.]]
# Larger shape
with tf.compat.v1.Session():
y = tf.compat.v1.get_variable('y', shape=[3, 4], initializer=init)
y.initializer.run()
print(y.eval())
[[0. 1. 2. 3.]
[4. 5. 6. 7.]
[7. 7. 7. 7.]]
# Smaller shape
with tf.compat.v1.Session():
z = tf.compat.v1.get_variable('z', shape=[2, 3], initializer=init)
Traceback (most recent call last):
ValueError: Too many elements provided. Needed at most 6, but received 8
# Shape verification
init_verify = tf.compat.v1.constant_initializer(value, verify_shape=True)
with tf.compat.v1.Session():
u = tf.compat.v1.get_variable('u', shape=[3, 4],
initializer=init_verify)
Traceback (most recent call last):
TypeError: Expected Tensor's shape: (3, 4), got (8,).
```
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L388-L393)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L380-L386)
```
__call__(
shape, dtype=None, partition_info=None, verify_shape=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.Identity tf.compat.v1.keras.initializers.Identity
========================================
Initializer that generates the identity matrix.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.identity`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Identity), [`tf.compat.v1.keras.initializers.identity`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Identity)
```
tf.compat.v1.keras.initializers.Identity(
gain=1.0,
dtype=tf.dtypes.float32
)
```
Only use for 2D matrices.
| Args |
| `gain` | Multiplicative factor to apply to the identity matrix. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L1590-L1591)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L1574-L1588)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.lecun_uniform tf.compat.v1.keras.initializers.lecun\_uniform
==============================================
Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: [`VarianceScaling`](variancescaling)
```
tf.compat.v1.keras.initializers.lecun_uniform(
seed=None
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../../../function).
To switch to TF2 APIs, move to using either [`tf.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/VarianceScaling) or [`tf.keras.initializers.VarianceScaling`](../../../../keras/initializers/variancescaling) (neither from [`compat.v1`](../../../v1)) and pass the dtype when calling the initializer.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.variance_scaling_initializer(
scale=scale,
mode=mode,
distribution=distribution
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.VarianceScaling(
scale=scale,
mode=mode,
distribution=distribution
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `scale` | `scale` | No change to defaults |
| `mode` | `mode` | No change to defaults |
| `distribution` | `distribution` | No change to defaults. 'normal' maps to 'truncated\_normal' |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is:
* number of input units in the weight tensor, if mode = "fan\_in"
* number of output units, if mode = "fan\_out"
* average of the numbers of input and output units, if mode = "fan\_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
| Args |
| `scale` | Scaling factor (positive float). |
| `mode` | One of "fan\_in", "fan\_out", "fan\_avg". |
| `distribution` | Random distribution to use. One of "normal", "uniform". |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
| Raises |
| `ValueError` | In case of an invalid value for the "scale", mode" or "distribution" arguments. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/initializers/initializers_v1.py#L430-L431)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.he_normal tf.compat.v1.keras.initializers.he\_normal
==========================================
Initializer capable of adapting its scale to the shape of weights tensors.
Inherits From: [`VarianceScaling`](variancescaling)
```
tf.compat.v1.keras.initializers.he_normal(
seed=None
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../../../function).
To switch to TF2 APIs, move to using either [`tf.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/VarianceScaling) or [`tf.keras.initializers.VarianceScaling`](../../../../keras/initializers/variancescaling) (neither from [`compat.v1`](../../../v1)) and pass the dtype when calling the initializer.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.variance_scaling_initializer(
scale=scale,
mode=mode,
distribution=distribution
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.VarianceScaling(
scale=scale,
mode=mode,
distribution=distribution
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `scale` | `scale` | No change to defaults |
| `mode` | `mode` | No change to defaults |
| `distribution` | `distribution` | No change to defaults. 'normal' maps to 'truncated\_normal' |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is:
* number of input units in the weight tensor, if mode = "fan\_in"
* number of output units, if mode = "fan\_out"
* average of the numbers of input and output units, if mode = "fan\_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
| Args |
| `scale` | Scaling factor (positive float). |
| `mode` | One of "fan\_in", "fan\_out", "fan\_avg". |
| `distribution` | Random distribution to use. One of "normal", "uniform". |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
| Raises |
| `ValueError` | In case of an invalid value for the "scale", mode" or "distribution" arguments. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/initializers/initializers_v1.py#L441-L442)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.Zeros tf.compat.v1.keras.initializers.Zeros
=====================================
Initializer that generates tensors initialized to 0.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.zeros`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Zeros), [`tf.compat.v1.keras.initializers.zeros`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Zeros), [`tf.compat.v1.zeros_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Zeros)
```
tf.compat.v1.keras.initializers.Zeros(
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
[`tf.compat.v1.zeros_initializer`](zeros) is compatible with eager execution and [`tf.function`](../../../../function).
To migrate to TF2, please use [`tf.zeros*initializer*`](../../../../zeros_initializer) instead. The `dtype` argument in <a href="../../../../../tf/compat/v1/keras/initializers/Zeros#*init*\_">`tf.compat.v1.zeros*initializer.**init*_()` does not exist in [`tf.zeros*initializer.**init*_()`](../../../../zeros_initializer#__init__). However, you can specify the `dtype` in `__call__()` in both cases.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32)
variable = tf.Variable(initializer(shape=[3, 3]))
```
After:
```
initializer = tf.zeros_initializer()
variable = tf.Variable(initializer(shape=[3, 3], dtype=tf.float32))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `dtype` | `dtype` | In `__call__()` method |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Before & After Usage Example
Before:
```
initializer = tf.compat.v1.zeros_initializer(dtype=tf.float32)
tf.Variable(initializer(shape=[3])).numpy()
array([0., 0., 0.], dtype=float32)
tf.Variable(initializer(shape=[3, 3])).numpy()
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=float32)
initializer = tf.compat.v1.zeros_initializer()
tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy()
array([0., 0., 0.], dtype=float32)
tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy()
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=float32)
```
After:
```
initializer = tf.zeros_initializer()
tf.Variable(initializer(shape=[3], dtype=tf.float32)).numpy()
array([0., 0., 0.], dtype=float32)
tf.Variable(initializer(shape=[3, 3], dtype=tf.float32)).numpy()
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=float32)
```
Description
-----------
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L177-L178)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L172-L175)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
| programming_docs |
tensorflow tf.compat.v1.keras.initializers.TruncatedNormal tf.compat.v1.keras.initializers.TruncatedNormal
===============================================
Initializer that generates a truncated normal distribution.
Inherits From: [`truncated_normal_initializer`](../../truncated_normal_initializer)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.keras.initializers.truncated_normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/TruncatedNormal)
```
tf.compat.v1.keras.initializers.TruncatedNormal(
mean=0.0,
stddev=0.05,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy compat.v1 api, [`tf.compat.v1.keras.initializers.TruncatedNormal`](truncatednormal) is compatible with eager execution and [`tf.function`](../../../../function).
To switch to native TF2, switch to using [`tf.keras.initializers.TruncatedNormal`](../../../../keras/initializers/truncatednormal) (not from [`compat.v1`](../../../v1)) and if you need to change the default dtype use [`tf.keras.backend.set_floatx(float_dtype)`](../../../../keras/backend/set_floatx) or pass the dtype when calling the initializer, rather than passing it when constructing the initializer.
Random seed behavior: Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```
initializer = tf.compat.v1.keras.initializers.TruncatedNormal(
mean=mean,
stddev=stddev,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.TruncatedNormal(
mean=mean,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
stddev=stddev)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `mean` | `mean` | No change to defaults |
| `stddev` | `stddev` | No change to defaults |
| `seed` | `seed` | Different random number generation semantics (to change in a future version). If set, the TF2 version will use stateless random number generation which will produce the exact same initialization even across multiple calls of the initializer instance. the [`compat.v1`](../../../v1) version will generate new initializations each time. Do not set a seed if you need different initializations each time. Instead either set a global tf seed with [`tf.random.set_seed`](../../../../random/set_seed) if you need determinism, or initialize each weight with a separate initializer instance and a different seed. |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
[`compat.v1`](../../../v1) Fixed seed behavior:
```
initializer = tf.compat.v1.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
After:
```
initializer = tf.keras.initializers.TruncatedNormal(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
Description
-----------
These values are similar to values from a `random_normal_initializer` except that values more than two standard deviations from the mean are discarded and re-drawn. This is the recommended initializer for neural network weights and filters.
| Args |
| `mean` | a python scalar or a scalar tensor. Mean of the random values to generate. |
| `stddev` | a python scalar or a scalar tensor. Standard deviation of the random values to generate. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L663-L669)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L657-L661)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.glorot_normal tf.compat.v1.keras.initializers.glorot\_normal
==============================================
The Glorot normal initializer, also called Xavier normal initializer.
Inherits From: [`VarianceScaling`](variancescaling)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.glorot_normal_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/glorot_normal), [`tf.compat.v1.initializers.glorot_normal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/glorot_normal)
```
tf.compat.v1.keras.initializers.glorot_normal(
seed=None,
dtype=tf.dtypes.float32
)
```
It draws samples from a truncated normal distribution centered on 0 with standard deviation (after truncation) given by `stddev = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units in the weight tensor.
| Args |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
#### References:
[Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L1655-L1656)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.VarianceScaling tf.compat.v1.keras.initializers.VarianceScaling
===============================================
Initializer capable of adapting its scale to the shape of weights tensors.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/VarianceScaling), [`tf.compat.v1.variance_scaling_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/VarianceScaling)
```
tf.compat.v1.keras.initializers.VarianceScaling(
scale=1.0,
mode='fan_in',
distribution='truncated_normal',
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) API, this symbol is compatible with eager execution and [`tf.function`](../../../../function).
To switch to TF2 APIs, move to using either [`tf.initializers.variance_scaling`](https://www.tensorflow.org/api_docs/python/tf/keras/initializers/VarianceScaling) or [`tf.keras.initializers.VarianceScaling`](../../../../keras/initializers/variancescaling) (neither from [`compat.v1`](../../../v1)) and pass the dtype when calling the initializer.
#### Structural Mapping to TF2
Before:
```
initializer = tf.compat.v1.variance_scaling_initializer(
scale=scale,
mode=mode,
distribution=distribution
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.VarianceScaling(
scale=scale,
mode=mode,
distribution=distribution
seed=seed)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `scale` | `scale` | No change to defaults |
| `mode` | `mode` | No change to defaults |
| `distribution` | `distribution` | No change to defaults. 'normal' maps to 'truncated\_normal' |
| `seed` | `seed` | |
| `dtype` | `dtype` | The TF2 api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
Description
-----------
With `distribution="truncated_normal" or "untruncated_normal"`, samples are drawn from a truncated/untruncated normal distribution with a mean of zero and a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)` where n is:
* number of input units in the weight tensor, if mode = "fan\_in"
* number of output units, if mode = "fan\_out"
* average of the numbers of input and output units, if mode = "fan\_avg"
With `distribution="uniform"`, samples are drawn from a uniform distribution within [-limit, limit], with `limit = sqrt(3 * scale / n)`.
| Args |
| `scale` | Scaling factor (positive float). |
| `mode` | One of "fan\_in", "fan\_out", "fan\_avg". |
| `distribution` | Random distribution to use. One of "normal", "uniform". |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
| Raises |
| `ValueError` | In case of an invalid value for the "scale", mode" or "distribution" arguments. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L884-L891)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.Orthogonal tf.compat.v1.keras.initializers.Orthogonal
==========================================
Initializer that generates an orthogonal matrix.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.initializers.orthogonal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Orthogonal), [`tf.compat.v1.keras.initializers.orthogonal`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Orthogonal), [`tf.compat.v1.orthogonal_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/Orthogonal)
```
tf.compat.v1.keras.initializers.Orthogonal(
gain=1.0,
seed=None,
dtype=tf.dtypes.float32
)
```
If the shape of the tensor to initialize is two-dimensional, it is initialized with an orthogonal matrix obtained from the QR decomposition of a matrix of random numbers drawn from a normal distribution. If the matrix has fewer rows than columns then the output will have orthogonal rows. Otherwise, the output will have orthogonal columns.
If the shape of the tensor to initialize is more than two-dimensional, a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])` is initialized, where `n` is the length of the shape vector. The matrix is subsequently reshaped to give a tensor of the desired shape.
| Args |
| `gain` | multiplicative factor to apply to the orthogonal matrix |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
#### References:
[Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C) ([pdf](https://arxiv.org/pdf/1312.6120.pdf))
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L961-L962)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L930-L959)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.keras.initializers.RandomUniform tf.compat.v1.keras.initializers.RandomUniform
=============================================
Initializer that generates tensors with a uniform distribution.
Inherits From: [`random_uniform_initializer`](../../random_uniform_initializer)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.keras.initializers.random_uniform`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/RandomUniform), [`tf.compat.v1.keras.initializers.uniform`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/RandomUniform)
```
tf.compat.v1.keras.initializers.RandomUniform(
minval=-0.05,
maxval=0.05,
seed=None,
dtype=tf.dtypes.float32
)
```
Migrate to TF2
--------------
Although it is a legacy [`compat.v1`](../../../v1) api, [`tf.compat.v1.keras.initializers.RandomUniform`](randomuniform) is compatible with eager execution and [`tf.function`](../../../../function).
To switch to native TF2, switch to using [`tf.keras.initializers.RandomUniform`](../../../../keras/initializers/randomuniform) (not from [`compat.v1`](../../../v1)) and if you need to change the default dtype use [`tf.keras.backend.set_floatx(float_dtype)`](../../../../keras/backend/set_floatx) or pass the dtype when calling the initializer, rather than passing it when constructing the initializer.
Random seed behavior:
Also be aware that if you pass a seed to the TF2 initializer API it will reuse that same seed for every single initialization (unlike the TF1 initializer)
#### Structural Mapping to Native TF2
Before:
```
initializer = tf.compat.v1.keras.initializers.RandomUniform(
minval=minval,
maxval=maxval,
seed=seed,
dtype=dtype)
weight_one = tf.Variable(initializer(shape_one))
weight_two = tf.Variable(initializer(shape_two))
```
After:
```
initializer = tf.keras.initializers.RandomUniform(
minval=minval,
maxval=maxval,
# seed=seed, # Setting a seed in the native TF2 API
# causes it to produce the same initializations
# across multiple calls of the same initializer.
)
weight_one = tf.Variable(initializer(shape_one, dtype=dtype))
weight_two = tf.Variable(initializer(shape_two, dtype=dtype))
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `minval` | `minval` | No change to defaults |
| `maxval` | `maxval` | No change to defaults |
| `seed` | `seed` | Different random number generation semantics (to change in a future version). If set, the TF2 version will use stateless random number generation which will produce the exact same initialization even across multiple calls of the initializer instance. the [`compat.v1`](../../../v1) version will generate new initializations each time. Do not set a seed if you need different initializations each time. Instead either set a global tf seed with [`tf.random.set_seed`](../../../../random/set_seed) if you need determinism, or initialize each weight with a separate initializer instance and a different seed. |
| `dtype` | `dtype` | The TF2 native api only takes it as a `__call__` arg, not a constructor arg. |
| `partition_info` | - | (`__call__` arg in TF1) Not supported |
#### Example of fixed-seed behavior differences
[`compat.v1`](../../../v1) Fixed seed behavior:
```
initializer = tf.compat.v1.keras.initializers.RandomUniform(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
After:
```
initializer = tf.keras.initializers.RandomUniform(seed=10)
a = initializer(shape=(2, 2))
b = initializer(shape=(2, 2))
tf.reduce_sum(a - b) == 0
<tf.Tensor: shape=(), dtype=bool, numpy=False>
```
Description
-----------
| Args |
| `minval` | A python scalar or a scalar tensor. Lower bound of the range of random values to generate. |
| `maxval` | A python scalar or a scalar tensor. Upper bound of the range of random values to generate. Defaults to 1 for float types. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L477-L483)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L471-L475)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
| programming_docs |
tensorflow tf.compat.v1.keras.initializers.glorot_uniform tf.compat.v1.keras.initializers.glorot\_uniform
===============================================
The Glorot uniform initializer, also called Xavier uniform initializer.
Inherits From: [`VarianceScaling`](variancescaling)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.glorot_uniform_initializer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/glorot_uniform), [`tf.compat.v1.initializers.glorot_uniform`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/keras/initializers/glorot_uniform)
```
tf.compat.v1.keras.initializers.glorot_uniform(
seed=None,
dtype=tf.dtypes.float32
)
```
It draws samples from a uniform distribution within [-limit, limit] where `limit` is `sqrt(6 / (fan_in + fan_out))` where `fan_in` is the number of input units in the weight tensor and `fan_out` is the number of output units in the weight tensor.
| Args |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../../set_random_seed) for behavior. |
| `dtype` | Default data type, used if no `dtype` argument is provided when calling the initializer. Only floating point types are supported. |
#### References:
[Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html) ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L74-L93)
```
@classmethod
from_config(
config
)
```
Instantiates an initializer from a configuration dictionary.
#### Example:
```
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```
| Args |
| `config` | A Python dictionary. It will typically be the output of `get_config`. |
| Returns |
| An Initializer instance. |
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L1622-L1623)
```
get_config()
```
Returns the configuration of the initializer as a JSON-serializable dict.
| Returns |
| A JSON-serializable Python dict. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/init_ops.py#L857-L882)
```
__call__(
shape, dtype=None, partition_info=None
)
```
Returns a tensor object initialized as specified by the initializer.
| Args |
| `shape` | Shape of the tensor. |
| `dtype` | Optional dtype of the tensor. If not provided use the initializer dtype. |
| `partition_info` | Optional information about the possible partitioning of a tensor. |
tensorflow tf.compat.v1.metrics.precision tf.compat.v1.metrics.precision
==============================
Computes the precision of the predictions with respect to the labels.
```
tf.compat.v1.metrics.precision(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `precision` function creates two local variables, `true_positives` and `false_positives`, that are used to compute the precision. This value is ultimately returned as `precision`, an idempotent operation that simply divides `true_positives` by the sum of `true_positives` and `false_positives`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision`. `update_op` weights each prediction by the corresponding value in `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `precision` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `precision` | Scalar float `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_positives` variables appropriately and whose value matches `precision`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.recall tf.compat.v1.metrics.recall
===========================
Computes the recall of the predictions with respect to the labels.
```
tf.compat.v1.metrics.recall(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `recall` function creates two local variables, `true_positives` and `false_negatives`, that are used to compute the recall. This value is ultimately returned as `recall`, an idempotent operation that simply divides `true_positives` by the sum of `true_positives` and `false_negatives`.
For estimation of the metric over a stream of data, the function creates an `update_op` that updates these variables and returns the `recall`. `update_op` weights each prediction by the corresponding value in `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `recall` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `recall` | Scalar float `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_negatives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_negatives` variables appropriately and whose value matches `recall`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean tf.compat.v1.metrics.mean
=========================
Computes the (weighted) mean of the given values.
```
tf.compat.v1.metrics.mean(
values,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.metrics.mean`](mean) is not compatible with eager execution or [`tf.function`](../../../function). Please use [`tf.keras.metrics.Mean`](../../../keras/metrics/mean) instead for TF2 migration. After instantiating a [`tf.keras.metrics.Mean`](../../../keras/metrics/mean) object, you can first call the `update_state()` method to record the new values, and then call the `result()` method to get the mean eagerly. You can also attach it to a Keras model with the `add_metric` method. Please refer to the [migration guide](https://www.tensorflow.org/guide/migrate#new-style_metrics_and_losses) for more details.
#### Structural Mapping to TF2
Before:
```
mean, update_op = tf.compat.v1.metrics.mean(
values=values,
weights=weights,
metrics_collections=metrics_collections,
update_collections=update_collections,
name=name)
```
After:
```
m = tf.keras.metrics.Mean(
name=name)
m.update_state(
values=values,
sample_weight=weights)
mean = m.result()
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `values` | `values` | In `update_state()` method |
| `weights` | `sample_weight` | In `update_state()` method |
| `metrics_collections` | Not supported | Metrics should be tracked explicitly or with Keras APIs, for example, [add\_metric](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_metric), instead of via collections |
| `updates_collections` | Not supported | - |
| `name` | `name` | In constructor |
#### Before & After Usage Example
Before:
```
g = tf.Graph()
with g.as_default():
values = [1, 2, 3]
mean, update_op = tf.compat.v1.metrics.mean(values)
global_init = tf.compat.v1.global_variables_initializer()
local_init = tf.compat.v1.local_variables_initializer()
sess = tf.compat.v1.Session(graph=g)
sess.run([global_init, local_init])
sess.run(update_op)
sess.run(mean)
2.0
```
After:
```
m = tf.keras.metrics.Mean()
m.update_state([1, 2, 3])
m.result().numpy()
2.0
```
```
# Used within Keras model
model.add_metric(tf.keras.metrics.Mean()(values))
```
Description
-----------
The `mean` function creates two local variables, `total` and `count` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean`. `update_op` increments `total` with the reduced sum of the product of `values` and `weights`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `values` | A `Tensor` of arbitrary dimensions. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `values`, and must be broadcastable to `values` (i.e., all dimensions must be either `1`, or the same as the corresponding `values` dimension). |
| `metrics_collections` | An optional list of collections that `mean` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean_relative_error tf.compat.v1.metrics.mean\_relative\_error
==========================================
Computes the mean relative error by normalizing with the given values.
```
tf.compat.v1.metrics.mean_relative_error(
labels,
predictions,
normalizer,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `mean_relative_error` function creates two local variables, `total` and `count` that are used to compute the mean relative absolute error. This average is weighted by `weights`, and it is ultimately returned as `mean_relative_error`: an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_reative_error`. Internally, a `relative_errors` operation divides the absolute value of the differences between `predictions` and `labels` by the `normalizer`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `relative_errors`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of the same shape as `predictions`. |
| `predictions` | A `Tensor` of arbitrary shape. |
| `normalizer` | A `Tensor` of the same shape as `predictions`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `mean_relative_error` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean_relative_error` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_relative_error`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean_tensor tf.compat.v1.metrics.mean\_tensor
=================================
Computes the element-wise (weighted) mean of the given tensors.
```
tf.compat.v1.metrics.mean_tensor(
values,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
In contrast to the `mean` function which returns a scalar with the mean, this function returns an average tensor with the same shape as the input tensors.
The `mean_tensor` function creates two local variables, `total_tensor` and `count_tensor` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean`. `update_op` increments `total` with the reduced sum of the product of `values` and `weights`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `values` | A `Tensor` of arbitrary dimensions. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `values`, and must be broadcastable to `values` (i.e., all dimensions must be either `1`, or the same as the corresponding `values` dimension). |
| `metrics_collections` | An optional list of collections that `mean` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean` | A float `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.recall_at_top_k tf.compat.v1.metrics.recall\_at\_top\_k
=======================================
Computes recall@k of top-k predictions with respect to sparse labels.
```
tf.compat.v1.metrics.recall_at_top_k(
labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Differs from `recall_at_k` in that predictions must be in the form of top `k` class indices, whereas `recall_at_k` expects logits. Refer to `recall_at_k` for more details.
| Args |
| `labels` | `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num\_labels] or [D1, ... DN], where the latter implies num\_labels=1. N >= 1 and num\_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch\_size, num\_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. Values outside this range always count towards `false_negative_at_<k>`. |
| `predictions_idx` | Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and predictions has shape [batch size, k]. The final dimension contains the top `k` predicted class indices. [D1, ... DN] must match `labels`. |
| `k` | Integer, k for @k metric. Only used for the default op name. |
| `class_id` | Integer class ID for which we want binary metrics. This should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. If class\_id is outside this range, the method returns NAN. |
| `weights` | `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that values should be added to. |
| `updates_collections` | An optional list of collections that updates should be added to. |
| `name` | Name of new update operation, and namespace for other dependent ops. |
| Returns |
| `recall` | Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_negatives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_negatives` variables appropriately, and whose value matches `recall`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
tensorflow tf.compat.v1.metrics.recall_at_k tf.compat.v1.metrics.recall\_at\_k
==================================
Computes recall@k of the predictions with respect to sparse labels.
```
tf.compat.v1.metrics.recall_at_k(
labels,
predictions,
k,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `class_id` is specified, we calculate recall by considering only the entries in the batch for which `class_id` is in the label, and computing the fraction of them for which `class_id` is in the top-k `predictions`. If `class_id` is not specified, we'll calculate recall as how often on average a class among the labels of a batch entry is in the top-k `predictions`.
`sparse_recall_at_k` creates two local variables, `true_positive_at_<k>` and `false_negative_at_<k>`, that are used to compute the recall\_at\_k frequency. This frequency is ultimately returned as `recall_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_negative_at_<k>`).
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false negatives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_negative_at_<k>` using these values.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num\_labels] or [D1, ... DN], where the latter implies num\_labels=1. N >= 1 and num\_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch\_size, num\_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. Values outside this range always count towards `false_negative_at_<k>`. |
| `predictions` | Float `Tensor` with shape [D1, ... DN, num\_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num\_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. |
| `k` | Integer, k for @k metric. |
| `class_id` | Integer class ID for which we want binary metrics. This should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. If class\_id is outside this range, the method returns NAN. |
| `weights` | `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that values should be added to. |
| `updates_collections` | An optional list of collections that updates should be added to. |
| `name` | Name of new update operation, and namespace for other dependent ops. |
| Returns |
| `recall` | Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_negatives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_negatives` variables appropriately, and whose value matches `recall`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.metrics.false_positives tf.compat.v1.metrics.false\_positives
=====================================
Sum the weights of false positives.
```
tf.compat.v1.metrics.false_positives(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `value_tensor` | A `Tensor` representing the current value of the metric. |
| `update_op` | An operation that accumulates the error from a batch of data. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.recall_at_thresholds tf.compat.v1.metrics.recall\_at\_thresholds
===========================================
Computes various recall values for different `thresholds` on `predictions`.
```
tf.compat.v1.metrics.recall_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `recall_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `recall[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of `True` values in `labels` (`true_positives[i] / (true_positives[i] + false_negatives[i])`).
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `recall`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `recall` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `recall` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `recall`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.true_positives_at_thresholds tf.compat.v1.metrics.true\_positives\_at\_thresholds
====================================================
Computes true positives at provided threshold values.
```
tf.compat.v1.metrics.true_positives_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `true_positives` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `true_positives` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that updates the `true_positives` variable and returns its current value. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.accuracy tf.compat.v1.metrics.accuracy
=============================
Calculates how often `predictions` matches `labels`.
```
tf.compat.v1.metrics.accuracy(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.metrics.accuracy`](accuracy) is not compatible with eager execution or [`tf.function`](../../../function). Please use [`tf.keras.metrics.Accuracy`](../../../keras/metrics/accuracy) instead for TF2 migration. After instantiating a [`tf.keras.metrics.Accuracy`](../../../keras/metrics/accuracy) object, you can first call the `update_state()` method to record the prediction/labels, and then call the `result()` method to get the accuracy eagerly. You can also attach it to a Keras model when calling the `compile` method. Please refer to [this guide](https://www.tensorflow.org/guide/migrate#new-style_metrics_and_losses) for more details.
#### Structural Mapping to Native TF2
Before:
```
accuracy, update_op = tf.compat.v1.metrics.accuracy(
labels=labels,
predictions=predictions,
weights=weights,
metrics_collections=metrics_collections,
update_collections=update_collections,
name=name)
```
After:
```
m = tf.keras.metrics.Accuracy(
name=name,
dtype=None)
m.update_state(
y_true=labels,
y_pred=predictions,
sample_weight=weights)
accuracy = m.result()
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `label` | `y_true` | In `update_state()` method |
| `predictions` | `y_true` | In `update_state()` method |
| `weights` | `sample_weight` | In `update_state()` method |
| `metrics_collections` | Not supported | Metrics should be tracked explicitly or with Keras APIs, for example, [add\_metric](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_metric), instead of via collections |
| `updates_collections` | Not supported | - |
| `name` | `name` | In constructor |
#### Before & After Usage Example
Before:
```
g = tf.Graph()
with g.as_default():
logits = [1, 2, 3]
labels = [0, 2, 3]
acc, acc_op = tf.compat.v1.metrics.accuracy(logits, labels)
global_init = tf.compat.v1.global_variables_initializer()
local_init = tf.compat.v1.local_variables_initializer()
sess = tf.compat.v1.Session(graph=g)
sess.run([global_init, local_init])
print(sess.run([acc, acc_op]))
[0.0, 0.66667]
```
After:
```
m = tf.keras.metrics.Accuracy()
m.update_state([1, 2, 3], [0, 2, 3])
m.result().numpy()
0.66667
```
```
# Used within Keras model
model.compile(optimizer='sgd',
loss='mse',
metrics=[tf.keras.metrics.Accuracy()])
```
Description
-----------
The `accuracy` function creates two local variables, `total` and `count` that are used to compute the frequency with which `predictions` matches `labels`. This frequency is ultimately returned as `accuracy`: an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `accuracy`. Internally, an `is_correct` operation computes a `Tensor` with elements 1.0 where the corresponding elements of `predictions` and `labels` match and 0.0 otherwise. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `is_correct`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose shape matches `predictions`. |
| `predictions` | The predicted values, a `Tensor` of any shape. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `accuracy` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `accuracy` | A `Tensor` representing the accuracy, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `accuracy`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.false_negatives_at_thresholds tf.compat.v1.metrics.false\_negatives\_at\_thresholds
=====================================================
Computes false negatives at provided threshold values.
```
tf.compat.v1.metrics.false_negatives_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `false_negatives` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `false_negatives` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that updates the `false_negatives` variable and returns its current value. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.true_positives tf.compat.v1.metrics.true\_positives
====================================
Sum the weights of true\_positives.
```
tf.compat.v1.metrics.true_positives(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `value_tensor` | A `Tensor` representing the current value of the metric. |
| `update_op` | An operation that accumulates the error from a batch of data. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.sensitivity_at_specificity tf.compat.v1.metrics.sensitivity\_at\_specificity
=================================================
Computes the specificity at a given sensitivity.
```
tf.compat.v1.metrics.sensitivity_at_specificity(
labels,
predictions,
specificity,
weights=None,
num_thresholds=200,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `sensitivity_at_specificity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the sensitivity at the given specificity value. The threshold for the given specificity value is computed and used to evaluate the corresponding sensitivity.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `sensitivity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
For additional information about specificity and sensitivity, see the following: <https://en.wikipedia.org/wiki/Sensitivity_and_specificity>
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `specificity` | A scalar value in range `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `num_thresholds` | The number of thresholds to use for matching the given specificity. |
| `metrics_collections` | An optional list of collections that `sensitivity` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `sensitivity` | A scalar `Tensor` representing the sensitivity at the given `specificity` value. |
| `update_op` | An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `sensitivity`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `specificity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.average_precision_at_k tf.compat.v1.metrics.average\_precision\_at\_k
==============================================
Computes average precision@k of predictions with respect to sparse labels.
```
tf.compat.v1.metrics.average_precision_at_k(
labels,
predictions,
k,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
`average_precision_at_k` creates two local variables, `average_precision_at_<k>/total` and `average_precision_at_<k>/max`, that are used to compute the frequency. This frequency is ultimately returned as `average_precision_at_<k>`: an idempotent operation that simply divides `average_precision_at_<k>/total` by `average_precision_at_<k>/max`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num\_labels] or [D1, ... DN], where the latter implies num\_labels=1. N >= 1 and num\_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch\_size, num\_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. Values outside this range are ignored. |
| `predictions` | Float `Tensor` with shape [D1, ... DN, num\_classes] where N >= 1. Commonly, N=1 and `predictions` has shape [batch size, num\_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. |
| `k` | Integer, k for @k metric. This will calculate an average precision for range `[1,k]`, as documented above. |
| `weights` | `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that values should be added to. |
| `updates_collections` | An optional list of collections that updates should be added to. |
| `name` | Name of new update operation, and namespace for other dependent ops. |
| Returns |
| `mean_average_precision` | Scalar `float64` `Tensor` with the mean average precision values. |
| `update` | `Operation` that increments variables appropriately, and whose value matches `metric`. |
| Raises |
| `ValueError` | if k is invalid. |
| `RuntimeError` | If eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.metrics.mean_iou tf.compat.v1.metrics.mean\_iou
==============================
Calculate per-step mean Intersection-Over-Union (mIOU).
```
tf.compat.v1.metrics.mean_iou(
labels,
predictions,
num_classes,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Mean Intersection-Over-Union is a common evaluation metric for semantic image segmentation, which first computes the IOU for each semantic class and then computes the average over classes. IOU is defined as follows: IOU = true\_positive / (true\_positive + false\_positive + false\_negative). The predictions are accumulated in a confusion matrix, weighted by `weights`, and mIOU is then calculated from it.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_iou`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of ground truth labels with shape [batch size] and of type `int32` or `int64`. The tensor will be flattened if its rank > 1. |
| `predictions` | A `Tensor` of prediction results for semantic labels, whose shape is [batch size] and type `int32` or `int64`. The tensor will be flattened if its rank > 1. |
| `num_classes` | The possible number of labels the prediction task can have. This value must be provided, since a confusion matrix of dimension = [num\_classes, num\_classes] will be allocated. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `mean_iou` should be added to. |
| `updates_collections` | An optional list of collections `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean_iou` | A `Tensor` representing the mean intersection-over-union. |
| `update_op` | An operation that increments the confusion matrix. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean_squared_error tf.compat.v1.metrics.mean\_squared\_error
=========================================
Computes the mean squared error between the labels and predictions.
```
tf.compat.v1.metrics.mean_squared_error(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the mean squared error. This average is weighted by `weights`, and it is ultimately returned as `mean_squared_error`: an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of the same shape as `predictions`. |
| `predictions` | A `Tensor` of arbitrary shape. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `mean_squared_error` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean_squared_error` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_squared_error`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.false_positives_at_thresholds tf.compat.v1.metrics.false\_positives\_at\_thresholds
=====================================================
Computes false positives at provided threshold values.
```
tf.compat.v1.metrics.false_positives_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `false_positives` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `false_positives` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that updates the `false_positives` variable and returns its current value. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.true_negatives_at_thresholds tf.compat.v1.metrics.true\_negatives\_at\_thresholds
====================================================
Computes true negatives at provided threshold values.
```
tf.compat.v1.metrics.true_negatives_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `true_negatives` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `true_negatives` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that updates the `true_negatives` variable and returns its current value. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.true_negatives tf.compat.v1.metrics.true\_negatives
====================================
Sum the weights of true\_negatives.
```
tf.compat.v1.metrics.true_negatives(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `value_tensor` | A `Tensor` representing the current value of the metric. |
| `update_op` | An operation that accumulates the error from a batch of data. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.precision_at_top_k tf.compat.v1.metrics.precision\_at\_top\_k
==========================================
Computes precision@k of the predictions with respect to sparse labels.
```
tf.compat.v1.metrics.precision_at_top_k(
labels,
predictions_idx,
k=None,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Differs from `sparse_precision_at_k` in that predictions must be in the form of top `k` class indices, whereas `sparse_precision_at_k` expects logits. Refer to `sparse_precision_at_k` for more details.
| Args |
| `labels` | `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num\_labels] or [D1, ... DN], where the latter implies num\_labels=1. N >= 1 and num\_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch\_size, num\_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. Values outside this range are ignored. |
| `predictions_idx` | Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and predictions has shape [batch size, k]. The final dimension contains the top `k` predicted class indices. [D1, ... DN] must match `labels`. |
| `k` | Integer, k for @k metric. Only used for the default op name. |
| `class_id` | Integer class ID for which we want binary metrics. This should be in range [0, num\_classes], where num\_classes is the last dimension of `predictions`. If `class_id` is outside this range, the method returns NAN. |
| `weights` | `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that values should be added to. |
| `updates_collections` | An optional list of collections that updates should be added to. |
| `name` | Name of new update operation, and namespace for other dependent ops. |
| Returns |
| `precision` | Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean_absolute_error tf.compat.v1.metrics.mean\_absolute\_error
==========================================
Computes the mean absolute error between the labels and predictions.
```
tf.compat.v1.metrics.mean_absolute_error(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `mean_absolute_error` function creates two local variables, `total` and `count` that are used to compute the mean absolute error. This average is weighted by `weights`, and it is ultimately returned as `mean_absolute_error`: an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_absolute_error`. Internally, an `absolute_errors` operation computes the absolute value of the differences between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `absolute_errors`, and it increments `count` with the reduced sum of `weights`
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of the same shape as `predictions`. |
| `predictions` | A `Tensor` of arbitrary shape. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `mean_absolute_error` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean_absolute_error` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_absolute_error`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.sparse_average_precision_at_k tf.compat.v1.metrics.sparse\_average\_precision\_at\_k
======================================================
Renamed to `average_precision_at_k`, please use that method instead. (deprecated)
```
tf.compat.v1.metrics.sparse_average_precision_at_k(
labels,
predictions,
k,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
tensorflow tf.compat.v1.metrics.percentage_below tf.compat.v1.metrics.percentage\_below
======================================
Computes the percentage of values less than the given threshold.
```
tf.compat.v1.metrics.percentage_below(
values,
threshold,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `percentage_below` function creates two local variables, `total` and `count` that are used to compute the percentage of `values` that fall below `threshold`. This rate is weighted by `weights`, and it is ultimately returned as `percentage` which is an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `percentage`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `values` | A numeric `Tensor` of arbitrary size. |
| `threshold` | A scalar threshold. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `values`, and must be broadcastable to `values` (i.e., all dimensions must be either `1`, or the same as the corresponding `values` dimension). |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `percentage` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.sparse_precision_at_k tf.compat.v1.metrics.sparse\_precision\_at\_k
=============================================
Renamed to `precision_at_k`, please use that method instead. (deprecated)
```
tf.compat.v1.metrics.sparse_precision_at_k(
labels,
predictions,
k,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
tensorflow tf.compat.v1.metrics.precision_at_thresholds tf.compat.v1.metrics.precision\_at\_thresholds
==============================================
Computes precision values for different `thresholds` on `predictions`.
```
tf.compat.v1.metrics.precision_at_thresholds(
labels,
predictions,
thresholds,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `precision_at_thresholds` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` for various values of thresholds. `precision[i]` is defined as the total weight of values in `predictions` above `thresholds[i]` whose corresponding entry in `labels` is `True`, divided by the total weight of values in `predictions` above `thresholds[i]` (`true_positives[i] / (true_positives[i] + false_positives[i])`).
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `thresholds` | A python list or tuple of float thresholds in `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `auc` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `precision` | A float `Tensor` of shape `[len(thresholds)]`. |
| `update_op` | An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables that are used in the computation of `precision`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.metrics.mean_per_class_accuracy tf.compat.v1.metrics.mean\_per\_class\_accuracy
===============================================
Calculates the mean of the per-class accuracies.
```
tf.compat.v1.metrics.mean_per_class_accuracy(
labels,
predictions,
num_classes,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
Calculates the accuracy for each class, then takes the mean of that.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates the accuracy of each class and returns them.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of ground truth labels with shape [batch size] and of type `int32` or `int64`. The tensor will be flattened if its rank > 1. |
| `predictions` | A `Tensor` of prediction results for semantic labels, whose shape is [batch size] and type `int32` or `int64`. The tensor will be flattened if its rank > 1. |
| `num_classes` | The possible number of labels the prediction task can have. This value must be provided, since two variables with shape = [num\_classes] will be allocated. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `mean_per_class_accuracy' should be added to. </td> </tr><tr> <td>`updates\_collections`</td> <td> An optional list of collections`update\_op`should be added to. </td> </tr><tr> <td>`name` | An optional variable\_scope name. |
| Returns |
| `mean_accuracy` | A `Tensor` representing the mean per class accuracy. |
| `update_op` | An operation that updates the accuracy tensor. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.precision_at_k tf.compat.v1.metrics.precision\_at\_k
=====================================
Computes precision@k of the predictions with respect to sparse labels.
```
tf.compat.v1.metrics.precision_at_k(
labels,
predictions,
k,
class_id=None,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `class_id` is specified, we calculate precision by considering only the entries in the batch for which `class_id` is in the top-k highest `predictions`, and computing the fraction of them for which `class_id` is indeed a correct label. If `class_id` is not specified, we'll calculate precision as how often on average a class among the top-k classes with the highest predicted values of a batch entry is correct and can be found in the label for that entry.
`precision_at_k` creates two local variables, `true_positive_at_<k>` and `false_positive_at_<k>`, that are used to compute the precision@k frequency. This frequency is ultimately returned as `precision_at_<k>`: an idempotent operation that simply divides `true_positive_at_<k>` by total (`true_positive_at_<k>` + `false_positive_at_<k>`).
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Internally, a `top_k` operation computes a `Tensor` indicating the top `k` `predictions`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num\_labels] or [D1, ... DN], where the latter implies num\_labels=1. N >= 1 and num\_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch\_size, num\_labels]. [D1, ... DN] must match `predictions`. Values should be in range [0, num\_classes), where num\_classes is the last dimension of `predictions`. Values outside this range are ignored. |
| `predictions` | Float `Tensor` with shape [D1, ... DN, num\_classes] where N >= 1. Commonly, N=1 and predictions has shape [batch size, num\_classes]. The final dimension contains the logit values for each class. [D1, ... DN] must match `labels`. |
| `k` | Integer, k for @k metric. |
| `class_id` | Integer class ID for which we want binary metrics. This should be in range [0, num\_classes], where num\_classes is the last dimension of `predictions`. If `class_id` is outside this range, the method returns NAN. |
| `weights` | `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that values should be added to. |
| `updates_collections` | An optional list of collections that updates should be added to. |
| `name` | Name of new update operation, and namespace for other dependent ops. |
| Returns |
| `precision` | Scalar `float64` `Tensor` with the value of `true_positives` divided by the sum of `true_positives` and `false_positives`. |
| `update_op` | `Operation` that increments `true_positives` and `false_positives` variables appropriately, and whose value matches `precision`. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.false_negatives tf.compat.v1.metrics.false\_negatives
=====================================
Computes the total number of false negatives.
```
tf.compat.v1.metrics.false_negatives(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | The predicted values, a `Tensor` of arbitrary dimensions. Will be cast to `bool`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `value_tensor` | A `Tensor` representing the current value of the metric. |
| `update_op` | An operation that accumulates the error from a batch of data. |
| Raises |
| `ValueError` | If `weights` is not `None` and its shape doesn't match `values`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.mean_cosine_distance tf.compat.v1.metrics.mean\_cosine\_distance
===========================================
Computes the cosine distance between the labels and predictions.
```
tf.compat.v1.metrics.mean_cosine_distance(
labels,
predictions,
dim,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `mean_cosine_distance` function creates two local variables, `total` and `count` that are used to compute the average cosine distance between `predictions` and `labels`. This average is weighted by `weights`, and it is ultimately returned as `mean_distance`, which is an idempotent operation that simply divides `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `mean_distance`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of arbitrary shape. |
| `predictions` | A `Tensor` of the same shape as `labels`. |
| `dim` | The dimension along which the cosine distance is computed. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). Also, dimension `dim` must be `1`. |
| `metrics_collections` | An optional list of collections that the metric value variable should be added to. |
| `updates_collections` | An optional list of collections that the metric update ops should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `mean_distance` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.root_mean_squared_error tf.compat.v1.metrics.root\_mean\_squared\_error
===============================================
Computes the root mean squared error between the labels and predictions.
```
tf.compat.v1.metrics.root_mean_squared_error(
labels,
predictions,
weights=None,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `root_mean_squared_error` function creates two local variables, `total` and `count` that are used to compute the root mean squared error. This average is weighted by `weights`, and it is ultimately returned as `root_mean_squared_error`: an idempotent operation that takes the square root of the division of `total` by `count`.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `root_mean_squared_error`. Internally, a `squared_error` operation computes the element-wise square of the difference between `predictions` and `labels`. Then `update_op` increments `total` with the reduced sum of the product of `weights` and `squared_error`, and it increments `count` with the reduced sum of `weights`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` of the same shape as `predictions`. |
| `predictions` | A `Tensor` of arbitrary shape. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `metrics_collections` | An optional list of collections that `root_mean_squared_error` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `root_mean_squared_error` | A `Tensor` representing the current mean, the value of `total` divided by `count`. |
| `update_op` | An operation that increments the `total` and `count` variables appropriately and whose value matches `root_mean_squared_error`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.auc tf.compat.v1.metrics.auc
========================
Computes the approximate AUC via a Riemann sum. (deprecated)
```
tf.compat.v1.metrics.auc(
labels,
predictions,
weights=None,
num_thresholds=200,
metrics_collections=None,
updates_collections=None,
curve='ROC',
name=None,
summation_method='trapezoidal',
thresholds=None
)
```
The `auc` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the AUC. To discretize the AUC curve, a linearly spaced set of thresholds is used to compute pairs of recall and precision values. The area under the ROC-curve is therefore computed using the height of the recall values by the false positive rate, while the area under the PR-curve is the computed using the height of the precision values by the recall.
This value is ultimately returned as `auc`, an idempotent operation that computes the area under a discretized curve of precision versus recall values (computed using the aforementioned variables). The `num_thresholds` variable controls the degree of discretization with larger numbers of thresholds more closely approximating the true AUC. The quality of the approximation may vary dramatically depending on `num_thresholds`.
For best results, `predictions` should be distributed approximately uniformly in the range [0, 1] and not peaked around 0 or 1. The quality of the AUC approximation may be poor if this is not the case. Setting `summation_method` to 'minoring' or 'majoring' can help quantify the error in the approximation by providing lower or upper bound estimate of the AUC. The `thresholds` parameter can be used to manually specify thresholds which split the predictions more evenly.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `auc`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
| Args |
| `labels` | A `Tensor` whose shape matches `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `num_thresholds` | The number of thresholds to use when discretizing the roc curve. |
| `metrics_collections` | An optional list of collections that `auc` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `curve` | Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve. |
| `name` | An optional variable\_scope name. |
| `summation_method` | Specifies the Riemann summation method used (<https://en.wikipedia.org/wiki/Riemann_sum>): 'trapezoidal' [default] that applies the trapezoidal rule; 'careful\_interpolation', a variant of it differing only by a more correct interpolation scheme for PR-AUC - interpolating (true/false) positives but not the ratio that is precision; 'minoring' that applies left summation for increasing intervals and right summation for decreasing intervals; 'majoring' that does the opposite. Note that 'careful\_interpolation' is strictly preferred to 'trapezoidal' (to be deprecated soon) as it applies the same method for ROC, and a better one (see Davis & Goadrich 2006 for details) for the PR curve. |
| `thresholds` | An optional list of floating point values to use as the thresholds for discretizing the curve. If set, the `num_thresholds` parameter is ignored. Values should be in [0, 1]. Endpoint thresholds equal to {-epsilon, 1+epsilon} for a small positive epsilon value will be automatically included with these to correctly handle predictions equal to exactly 0 or 1. |
| Returns |
| `auc` | A scalar `Tensor` representing the current area-under-curve. |
| `update_op` | An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `auc`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, or if `weights` is not `None` and its shape doesn't match `predictions`, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.metrics.specificity_at_sensitivity tf.compat.v1.metrics.specificity\_at\_sensitivity
=================================================
Computes the specificity at a given sensitivity.
```
tf.compat.v1.metrics.specificity_at_sensitivity(
labels,
predictions,
sensitivity,
weights=None,
num_thresholds=200,
metrics_collections=None,
updates_collections=None,
name=None
)
```
The `specificity_at_sensitivity` function creates four local variables, `true_positives`, `true_negatives`, `false_positives` and `false_negatives` that are used to compute the specificity at the given sensitivity value. The threshold for the given sensitivity value is computed and used to evaluate the corresponding specificity.
For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `specificity`. `update_op` increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` counts with the weight of each case found in the `predictions` and `labels`.
If `weights` is `None`, weights default to 1. Use weights of 0 to mask values.
For additional information about specificity and sensitivity, see the following: <https://en.wikipedia.org/wiki/Sensitivity_and_specificity>
| Args |
| `labels` | The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. |
| `predictions` | A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. |
| `sensitivity` | A scalar value in range `[0, 1]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). |
| `num_thresholds` | The number of thresholds to use for matching the given sensitivity. |
| `metrics_collections` | An optional list of collections that `specificity` should be added to. |
| `updates_collections` | An optional list of collections that `update_op` should be added to. |
| `name` | An optional variable\_scope name. |
| Returns |
| `specificity` | A scalar `Tensor` representing the specificity at the given `sensitivity` value. |
| `update_op` | An operation that increments the `true_positives`, `true_negatives`, `false_positives` and `false_negatives` variables appropriately and whose value matches `specificity`. |
| Raises |
| `ValueError` | If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `sensitivity` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.GPUOptions.Experimental tf.compat.v1.GPUOptions.Experimental
====================================
A ProtocolMessage
| Attributes |
| `collective_ring_order` | `string collective_ring_order` |
| `disallow_retry_on_allocation_failure` | `bool disallow_retry_on_allocation_failure` |
| `internal_fragmentation_fraction` | `double internal_fragmentation_fraction` |
| `kernel_tracker_max_bytes` | `int32 kernel_tracker_max_bytes` |
| `kernel_tracker_max_interval` | `int32 kernel_tracker_max_interval` |
| `kernel_tracker_max_pending` | `int32 kernel_tracker_max_pending` |
| `num_dev_to_dev_copy_streams` | `int32 num_dev_to_dev_copy_streams` |
| `timestamped_allocator` | `bool timestamped_allocator` |
| `use_cuda_malloc_async` | `bool use_cuda_malloc_async` |
| `use_unified_memory` | `bool use_unified_memory` |
| `virtual_devices` | `repeated VirtualDevices virtual_devices` |
Child Classes
-------------
[`class VirtualDevices`](experimental/virtualdevices)
| programming_docs |
tensorflow tf.compat.v1.GPUOptions.Experimental.VirtualDevices tf.compat.v1.GPUOptions.Experimental.VirtualDevices
===================================================
A ProtocolMessage
| Attributes |
| `memory_limit_mb` | `repeated float memory_limit_mb` |
| `priority` | `repeated int32 priority` |
tensorflow tf.compat.v1.losses.huber_loss tf.compat.v1.losses.huber\_loss
===============================
Adds a [Huber Loss](https://en.wikipedia.org/wiki/Huber_loss) term to the training procedure.
```
tf.compat.v1.losses.huber_loss(
labels,
predictions,
weights=1.0,
delta=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
For each value x in `error=labels-predictions`, the following is calculated:
```
0.5 * x^2 if |x| <= d
0.5 * d^2 + d * (|x| - d) if |x| > d
```
where d is `delta`.
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`.
| Args |
| `labels` | The ground truth output tensor, same dimensions as 'predictions'. |
| `predictions` | The predicted outputs. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `delta` | `float`, the point where the huber loss function changes from a quadratic to linear. |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid. Also if `labels` or `predictions` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.log_loss tf.compat.v1.losses.log\_loss
=============================
Adds a Log Loss term to the training procedure.
```
tf.compat.v1.losses.log_loss(
labels,
predictions,
weights=1.0,
epsilon=1e-07,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`.
| Args |
| `labels` | The ground truth output tensor, same dimensions as 'predictions'. |
| `predictions` | The predicted outputs. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `epsilon` | A small increment to add to avoid taking a log of zero. |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid. Also if `labels` or `predictions` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.softmax_cross_entropy tf.compat.v1.losses.softmax\_cross\_entropy
===========================================
Creates a cross-entropy loss using tf.nn.softmax\_cross\_entropy\_with\_logits\_v2.
```
tf.compat.v1.losses.softmax_cross_entropy(
onehot_labels,
logits,
weights=1.0,
label_smoothing=0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
Migrate to TF2
--------------
[`tf.compat.v1.losses.softmax_cross_entropy`](softmax_cross_entropy) is mostly compatible with eager execution and [`tf.function`](../../../function). But, the `loss_collection` argument is ignored when executing eagerly and no loss will be written to the loss collections. You will need to either hold on to the return value manually or rely on [`tf.keras.Model`](../../../keras/model) loss tracking.
To switch to native TF2 style, instantiate the [`tf.keras.losses.CategoricalCrossentropy`](../../../keras/losses/categoricalcrossentropy) class with `from_logits` set as `True` and call the object instead.
#### Structural Mapping to Native TF2
Before:
```
loss = tf.compat.v1.losses.softmax_cross_entropy(
onehot_labels=onehot_labels,
logits=logits,
weights=weights,
label_smoothing=smoothing)
```
After:
```
loss_fn = tf.keras.losses.CategoricalCrossentropy(
from_logits=True,
label_smoothing=smoothing)
loss = loss_fn(
y_true=onehot_labels,
y_pred=logits,
sample_weight=weights)
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| - | `from_logits` | Set `from_logits` as True to have identical behavior |
| `onehot_labels` | `y_true` | In `__call__()` method |
| `logits` | `y_pred` | In `__call__()` method |
| `weights` | `sample_weight` | In `__call__()` method |
| `label_smoothing` | `label_smoothing` | In constructor |
| `scope` | Not supported | - |
| `loss_collection` | Not supported | Losses should be tracked explicitly or with Keras APIs, for example, [add\_loss](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss), instead of via collections |
| `reduction` | `reduction` | In constructor. Value of [`tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE`](reduction#SUM_OVER_BATCH_SIZE), [`tf.compat.v1.losses.Reduction.SUM`](reduction#SUM), [`tf.compat.v1.losses.Reduction.NONE`](reduction#NONE) in [`tf.compat.v1.losses.softmax_cross_entropy`](softmax_cross_entropy) correspond to [`tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE`](../../../keras/losses/reduction#SUM_OVER_BATCH_SIZE), [`tf.keras.losses.Reduction.SUM`](../../../keras/losses/reduction#SUM), [`tf.keras.losses.Reduction.NONE`](../../../keras/losses/reduction#NONE), respectively. If you used other value for `reduction`, including the default value [`tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS`](reduction#SUM_BY_NONZERO_WEIGHTS), there is no directly corresponding value. Please modify the loss implementation manually. |
#### Before & After Usage Example
Before:
```
y_true = [[0, 1, 0], [0, 0, 1]]
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]
weights = [0.3, 0.7]
smoothing = 0.2
tf.compat.v1.losses.softmax_cross_entropy(y_true, y_pred, weights=weights,
label_smoothing=smoothing).numpy()
0.57618
```
After:
```
cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True,
label_smoothing=smoothing)
cce(y_true, y_pred, sample_weight=weights).numpy()
0.57618
```
Description
-----------
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of shape `[batch_size]`, then the loss weights apply to each corresponding sample.
If `label_smoothing` is nonzero, smooth the labels towards 1/num\_classes: new\_onehot\_labels = onehot\_labels \* (1 - label\_smoothing)
```
+ label_smoothing / num_classes
```
Note that `onehot_labels` and `logits` must have the same shape, e.g. `[batch_size, num_classes]`. The shape of `weights` must be broadcastable to loss, whose shape is decided by the shape of `logits`. In case the shape of `logits` is `[batch_size, num_classes]`, loss is a `Tensor` of shape `[batch_size]`.
| Args |
| `onehot_labels` | One-hot-encoded labels. |
| `logits` | Logits outputs of the network. |
| `weights` | Optional `Tensor` that is broadcastable to loss. |
| `label_smoothing` | If greater than 0 then smooth the labels. |
| `scope` | the scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss `Tensor` of the same type as `logits`. If `reduction` is `NONE`, this has shape `[batch_size]`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `logits` doesn't match that of `onehot_labels` or if the shape of `weights` is invalid or if `weights` is None. Also if `onehot_labels` or `logits` is None. |
tensorflow tf.compat.v1.losses.get_regularization_losses tf.compat.v1.losses.get\_regularization\_losses
===============================================
Gets the list of regularization losses.
```
tf.compat.v1.losses.get_regularization_losses(
scope=None
)
```
| Args |
| `scope` | An optional scope name for filtering the losses to return. |
| Returns |
| A list of regularization losses as Tensors. |
tensorflow tf.compat.v1.losses.sigmoid_cross_entropy tf.compat.v1.losses.sigmoid\_cross\_entropy
===========================================
Creates a cross-entropy loss using tf.nn.sigmoid\_cross\_entropy\_with\_logits.
```
tf.compat.v1.losses.sigmoid_cross_entropy(
multi_class_labels,
logits,
weights=1.0,
label_smoothing=0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of shape `[batch_size]`, then the loss weights apply to each corresponding sample.
If `label_smoothing` is nonzero, smooth the labels towards 1/2:
```
new_multiclass_labels = multiclass_labels * (1 - label_smoothing)
+ 0.5 * label_smoothing
```
| Args |
| `multi_class_labels` | `[batch_size, num_classes]` target integer labels in `{0, 1}`. |
| `logits` | Float `[batch_size, num_classes]` logits outputs of the network. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `multi_class_labels`, and must be broadcastable to `multi_class_labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `label_smoothing` | If greater than `0` then smooth the labels. |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss `Tensor` of the same type as `logits`. If `reduction` is `NONE`, this has the same shape as `logits`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `logits` doesn't match that of `multi_class_labels` or if the shape of `weights` is invalid, or if `weights` is None. Also if `multi_class_labels` or `logits` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.hinge_loss tf.compat.v1.losses.hinge\_loss
===============================
Adds a hinge loss to the training procedure.
```
tf.compat.v1.losses.hinge_loss(
labels,
logits,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
| Args |
| `labels` | The ground truth output tensor. Its shape should match the shape of logits. The values of the tensor are expected to be 0.0 or 1.0. Internally the {0,1} labels are converted to {-1,1} when calculating the hinge loss. |
| `logits` | The logits, a float tensor. Note that logits are assumed to be unbounded and 0-centered. A value > 0 (resp. < 0) is considered a positive (resp. negative) binary prediction. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shapes of `logits` and `labels` don't match or if `labels` or `logits` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.absolute_difference tf.compat.v1.losses.absolute\_difference
========================================
Adds an Absolute Difference loss to the training procedure.
```
tf.compat.v1.losses.absolute_difference(
labels,
predictions,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a `Tensor` of shape `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`.
| Args |
| `labels` | The ground truth output tensor, same dimensions as 'predictions'. |
| `predictions` | The predicted outputs. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which this loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid or if `labels` or `predictions` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.sparse_softmax_cross_entropy tf.compat.v1.losses.sparse\_softmax\_cross\_entropy
===================================================
Cross-entropy loss using [`tf.nn.sparse_softmax_cross_entropy_with_logits`](../../../nn/sparse_softmax_cross_entropy_with_logits).
```
tf.compat.v1.losses.sparse_softmax_cross_entropy(
labels,
logits,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of shape `[batch_size]`, then the loss weights apply to each corresponding sample.
| Args |
| `labels` | `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of `labels` and result) and dtype `int32` or `int64`. Each entry in `labels` must be an index in `[0, num_classes)`. Other values will raise an exception when this op is run on CPU, and return `NaN` for corresponding loss and gradient rows on GPU. |
| `logits` | Unscaled log probabilities of shape `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32` or `float64`. |
| `weights` | Coefficients for the loss. This must be scalar or broadcastable to `labels` (i.e. same rank and each dimension is either 1 or the same). |
| `scope` | the scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss `Tensor` of the same type as `logits`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shapes of `logits`, `labels`, and `weights` are incompatible, or if any of them are None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.mean_pairwise_squared_error tf.compat.v1.losses.mean\_pairwise\_squared\_error
==================================================
Adds a pairwise-errors-squared loss to the training procedure.
```
tf.compat.v1.losses.mean_pairwise_squared_error(
labels,
predictions,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES
)
```
Unlike `mean_squared_error`, which is a measure of the differences between corresponding elements of `predictions` and `labels`, `mean_pairwise_squared_error` is a measure of the differences between pairs of corresponding elements of `predictions` and `labels`.
For example, if `labels`=[a, b, c] and `predictions`=[x, y, z], there are three pairs of differences are summed to compute the loss: loss = [ ((a-b) - (x-y)).^2 + ((a-c) - (x-z)).^2 + ((b-c) - (y-z)).^2 ] / 3
Note that since the inputs are of shape `[batch_size, d0, ... dN]`, the corresponding pairs are computed within each batch sample but not across samples within a batch. For example, if `predictions` represents a batch of 16 grayscale images of dimension [batch\_size, 100, 200], then the set of pairs is drawn from each image, but not across images.
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector.
| Args |
| `labels` | The ground truth output tensor, whose shape must match the shape of `predictions`. |
| `predictions` | The predicted outputs, a tensor of size `[batch_size, d0, .. dN]` where N+1 is the total number of dimensions in `predictions`. |
| `weights` | Coefficients for the loss a scalar, a tensor of shape `[batch_size]` or a tensor whose shape matches `predictions`. |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| Returns |
| A scalar `Tensor` that returns the weighted loss. |
| Raises |
| `ValueError` | If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid. Also if `labels` or `predictions` is None. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
| programming_docs |
tensorflow tf.compat.v1.losses.mean_squared_error tf.compat.v1.losses.mean\_squared\_error
========================================
Adds a Sum-of-Squares loss to the training procedure.
```
tf.compat.v1.losses.mean_squared_error(
labels,
predictions,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
Migrate to TF2
--------------
[`tf.compat.v1.losses.mean_squared_error`](mean_squared_error) is mostly compatible with eager execution and [`tf.function`](../../../function). But, the `loss_collection` argument is ignored when executing eagerly and no loss will be written to the loss collections. You will need to either hold on to the return value manually or rely on [`tf.keras.Model`](../../../keras/model) loss tracking.
To switch to native TF2 style, instantiate the [`tf.keras.losses.MeanSquaredError`](../../../keras/losses/meansquarederror) class and call the object instead.
#### Structural Mapping to Native TF2
Before:
```
loss = tf.compat.v1.losses.mean_squared_error(
labels=labels,
predictions=predictions,
weights=weights,
reduction=reduction)
```
After:
```
loss_fn = tf.keras.losses.MeanSquaredError(
reduction=reduction)
loss = loss_fn(
y_true=labels,
y_pred=predictions,
sample_weight=weights)
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `labels` | `y_true` | In `__call__()` method |
| `predictions` | `y_pred` | In `__call__()` method |
| `weights` | `sample_weight` | In `__call__()` method. The shape requirements for `sample_weight` is different from `weights`. Please check the [argument definition](https://www.tensorflow.org/api_docs/python/tf/keras/losses/MeanSquaredError#__call__) for details. |
| `scope` | Not supported | - |
| `loss_collection` | Not supported | Losses should be tracked explicitly or with Keras APIs, for example, [add\_loss](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer#add_loss), instead of via collections |
| `reduction` | `reduction` | In constructor. Value of [`tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE`](reduction#SUM_OVER_BATCH_SIZE), [`tf.compat.v1.losses.Reduction.SUM`](reduction#SUM), [`tf.compat.v1.losses.Reduction.NONE`](reduction#NONE) in [`tf.compat.v1.losses.softmax_cross_entropy`](softmax_cross_entropy) correspond to [`tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE`](../../../keras/losses/reduction#SUM_OVER_BATCH_SIZE), [`tf.keras.losses.Reduction.SUM`](../../../keras/losses/reduction#SUM), [`tf.keras.losses.Reduction.NONE`](../../../keras/losses/reduction#NONE), respectively. If you used other value for `reduction`, including the default value [`tf.compat.v1.losses.Reduction.SUM_BY_NONZERO_WEIGHTS`](reduction#SUM_BY_NONZERO_WEIGHTS), there is no directly corresponding value. Please modify the loss implementation manually. |
#### Before & After Usage Example
Before:
```
y_true = [1, 2, 3]
y_pred = [1, 3, 5]
weights = [0, 1, 0.25]
# samples with zero-weight are excluded from calculation when `reduction`
# argument is set to default value `Reduction.SUM_BY_NONZERO_WEIGHTS`
tf.compat.v1.losses.mean_squared_error(
labels=y_true,
predictions=y_pred,
weights=weights).numpy()
1.0
```
```
tf.compat.v1.losses.mean_squared_error(
labels=y_true,
predictions=y_pred,
weights=weights,
reduction=tf.compat.v1.losses.Reduction.SUM_OVER_BATCH_SIZE).numpy()
0.66667
```
After:
```
y_true = [[1.0], [2.0], [3.0]]
y_pred = [[1.0], [3.0], [5.0]]
weights = [1, 1, 0.25]
mse = tf.keras.losses.MeanSquaredError(
reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE)
mse(y_true=y_true, y_pred=y_pred, sample_weight=weights).numpy()
0.66667
```
Description
-----------
`weights` acts as a coefficient for the loss. If a scalar is provided, then the loss is simply scaled by the given value. If `weights` is a tensor of size `[batch_size]`, then the total loss for each sample of the batch is rescaled by the corresponding element in the `weights` vector. If the shape of `weights` matches the shape of `predictions`, then the loss of each measurable element of `predictions` is scaled by the corresponding value of `weights`.
| Args |
| `labels` | The ground truth output tensor, same dimensions as 'predictions'. |
| `predictions` | The predicted outputs. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which the loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If the shape of `predictions` doesn't match that of `labels` or if the shape of `weights` is invalid. Also if `labels` or `predictions` is None. |
tensorflow tf.compat.v1.losses.add_loss tf.compat.v1.losses.add\_loss
=============================
Adds a externally defined loss to the collection of losses.
```
tf.compat.v1.losses.add_loss(
loss, loss_collection=ops.GraphKeys.LOSSES
)
```
| Args |
| `loss` | A loss `Tensor`. |
| `loss_collection` | Optional collection to add the loss to. |
tensorflow tf.compat.v1.losses.compute_weighted_loss tf.compat.v1.losses.compute\_weighted\_loss
===========================================
Computes the weighted loss.
```
tf.compat.v1.losses.compute_weighted_loss(
losses,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS
)
```
| Args |
| `losses` | `Tensor` of shape `[batch_size, d1, ... dN]`. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `losses`, and must be broadcastable to `losses` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `scope` | the scope for the operations performed in computing the loss. |
| `loss_collection` | the loss will be added to these collections. |
| `reduction` | Type of reduction to apply to loss. |
| Returns |
| Weighted loss `Tensor` of the same type as `losses`. If `reduction` is `NONE`, this has the same shape as `losses`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If `weights` is `None` or the shape is not compatible with `losses`, or if the number of dimensions (rank) of either `losses` or `weights` is missing. |
#### Note:
When calculating the gradient of a weighted loss contributions from both `losses` and `weights` are considered. If your `weights` depend on some model parameters but you do not want this to affect the loss gradient, you need to apply [`tf.stop_gradient`](../../../stop_gradient) to `weights` before passing them to `compute_weighted_loss`.
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.Reduction tf.compat.v1.losses.Reduction
=============================
Types of loss reduction.
Contains the following values:
* `NONE`: Un-reduced weighted losses with the same shape as input.
* `SUM`: Scalar sum of weighted losses.
* `MEAN`: Scalar `SUM` divided by sum of weights. DEPRECATED.
* `SUM_OVER_BATCH_SIZE`: Scalar `SUM` divided by number of elements in losses.
* `SUM_OVER_NONZERO_WEIGHTS`: Scalar `SUM` divided by number of non-zero weights. DEPRECATED.
* `SUM_BY_NONZERO_WEIGHTS`: Same as `SUM_OVER_NONZERO_WEIGHTS`. DEPRECATED.
Methods
-------
### `all`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/losses/losses_impl.py#L56-L64)
```
@classmethod
all()
```
### `validate`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/losses/losses_impl.py#L66-L70)
```
@classmethod
validate(
key
)
```
| Class Variables |
| MEAN | `'weighted_mean'` |
| NONE | `'none'` |
| SUM | `'weighted_sum'` |
| SUM\_BY\_NONZERO\_WEIGHTS | `'weighted_sum_by_nonzero_weights'` |
| SUM\_OVER\_BATCH\_SIZE | `'weighted_sum_over_batch_size'` |
| SUM\_OVER\_NONZERO\_WEIGHTS | `'weighted_sum_by_nonzero_weights'` |
tensorflow tf.compat.v1.losses.get_total_loss tf.compat.v1.losses.get\_total\_loss
====================================
Returns a tensor whose value represents the total loss.
```
tf.compat.v1.losses.get_total_loss(
add_regularization_losses=True, name='total_loss', scope=None
)
```
In particular, this adds any losses you have added with `tf.add_loss()` to any regularization losses that have been added by regularization parameters on layers constructors e.g. `tf.layers`. Be very sure to use this if you are constructing a loss\_op manually. Otherwise regularization arguments on `tf.layers` methods will not function.
| Args |
| `add_regularization_losses` | A boolean indicating whether or not to use the regularization losses in the sum. |
| `name` | The name of the returned tensor. |
| `scope` | An optional scope name for filtering the losses to return. Note that this filters the losses added with `tf.add_loss()` as well as the regularization losses to that scope. |
| Returns |
| A `Tensor` whose value represents the total loss. |
| Raises |
| `ValueError` | if `losses` is not iterable. |
tensorflow tf.compat.v1.losses.get_losses tf.compat.v1.losses.get\_losses
===============================
Gets the list of losses from the loss\_collection.
```
tf.compat.v1.losses.get_losses(
scope=None, loss_collection=ops.GraphKeys.LOSSES
)
```
| Args |
| `scope` | An optional scope name for filtering the losses to return. |
| `loss_collection` | Optional losses collection. |
| Returns |
| a list of loss tensors. |
tensorflow tf.compat.v1.losses.cosine_distance tf.compat.v1.losses.cosine\_distance
====================================
Adds a cosine-distance loss to the training procedure. (deprecated arguments)
```
tf.compat.v1.losses.cosine_distance(
labels,
predictions,
axis=None,
weights=1.0,
scope=None,
loss_collection=ops.GraphKeys.LOSSES,
reduction=Reduction.SUM_BY_NONZERO_WEIGHTS,
dim=None
)
```
Note that the function assumes that `predictions` and `labels` are already unit-normalized.
| Args |
| `labels` | `Tensor` whose shape matches 'predictions' |
| `predictions` | An arbitrary matrix. |
| `axis` | The dimension along which the cosine distance is computed. |
| `weights` | Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `losses` dimension). |
| `scope` | The scope for the operations performed in computing the loss. |
| `loss_collection` | collection to which this loss will be added. |
| `reduction` | Type of reduction to apply to loss. |
| `dim` | The old (deprecated) name for `axis`. |
| Returns |
| Weighted loss float `Tensor`. If `reduction` is `NONE`, this has the same shape as `labels`; otherwise, it is scalar. |
| Raises |
| `ValueError` | If `predictions` shape doesn't match `labels` shape, or `axis`, `labels`, `predictions` or `weights` is `None`. |
eager compatibility
-------------------
The `loss_collection` argument is ignored when executing eagerly. Consider holding on to the return value or collecting losses via a [`tf.keras.Model`](../../../keras/model).
tensorflow tf.compat.v1.losses.get_regularization_loss tf.compat.v1.losses.get\_regularization\_loss
=============================================
Gets the total regularization loss.
```
tf.compat.v1.losses.get_regularization_loss(
scope=None, name='total_regularization_loss'
)
```
| Args |
| `scope` | An optional scope name for filtering the losses to return. |
| `name` | The name of the returned tensor. |
| Returns |
| A scalar regularization loss. |
tensorflow tf.compat.v1.experimental.output_all_intermediates tf.compat.v1.experimental.output\_all\_intermediates
====================================================
Whether to output all intermediates from functional control flow ops.
```
tf.compat.v1.experimental.output_all_intermediates(
state
)
```
The "default" behavior to is to output all intermediates when using v2 control flow inside Keras models in graph mode (possibly inside Estimators). This is needed to support taking gradients of v2 control flow. In graph mode, Keras can sometimes freeze the forward graph before the gradient computation which does not work for v2 control flow since it requires updating the forward ops to output the needed intermediates. We work around this by proactively outputting the needed intermediates when building the forward pass itself. Ideally any such extra tensors should be pruned out at runtime. However, if for any reason this doesn't work for you or if you have an inference-only model you can turn this behavior off using [`tf.compat.v1.experimental.output_all_intermediates(False)`](output_all_intermediates).
If with the default behavior you are still seeing errors of the form "Connecting to invalid output X of source node Y which has Z outputs" try setting [`tf.compat.v1.experimental.output_all_intermediates(True)`](output_all_intermediates) and please file an issue at https://github.com/tensorflow/tensorflow/issues.
| Args |
| `state` | True, False or None. None restores the default behavior. |
tensorflow tf.compat.v1.AttrValue.ListValue tf.compat.v1.AttrValue.ListValue
================================
A ProtocolMessage
| Attributes |
| `b` | `repeated bool b` |
| `f` | `repeated float f` |
| `func` | `repeated NameAttrList func` |
| `i` | `repeated int64 i` |
| `s` | `repeated bytes s` |
| `shape` | `repeated TensorShapeProto shape` |
| `tensor` | `repeated TensorProto tensor` |
| `type` | `repeated DataType type` |
tensorflow tf.compat.v1.strings.split tf.compat.v1.strings.split
==========================
Split elements of `input` based on `sep`.
```
tf.compat.v1.strings.split(
input=None,
sep=None,
maxsplit=-1,
result_type='SparseTensor',
source=None,
name=None
)
```
Let N be the size of `input` (typically N will be the batch size). Split each element of `input` based on `sep` and return a `SparseTensor` or `RaggedTensor` containing the split tokens. Empty tokens are ignored.
#### Examples:
```
print(tf.compat.v1.strings.split(['hello world', 'a b c']))
SparseTensor(indices=tf.Tensor( [[0 0] [0 1] [1 0] [1 1] [1 2]], ...),
values=tf.Tensor([b'hello' b'world' b'a' b'b' b'c'], ...),
dense_shape=tf.Tensor([2 3], shape=(2,), dtype=int64))
```
```
print(tf.compat.v1.strings.split(['hello world', 'a b c'],
result_type="RaggedTensor"))
<tf.RaggedTensor [[b'hello', b'world'], [b'a', b'b', b'c']]>
```
If `sep` is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings. For example, `input` of `"1<>2<><>3"` and `sep` of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty string, consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
Note that the above mentioned behavior matches python's str.split.
| Args |
| `input` | A string `Tensor` of rank `N`, the strings to split. If `rank(input)` is not known statically, then it is assumed to be `1`. |
| `sep` | `0-D` string `Tensor`, the delimiter character. |
| `maxsplit` | An `int`. If `maxsplit > 0`, limit of the split of the result. |
| `result_type` | The tensor type for the result: one of `"RaggedTensor"` or `"SparseTensor"`. |
| `source` | alias for "input" argument. |
| `name` | A name for the operation (optional). |
| Raises |
| `ValueError` | If sep is not a string. |
| Returns |
| A `SparseTensor` or `RaggedTensor` of rank `N+1`, the strings split according to the delimiter. |
tensorflow tf.compat.v1.strings.length tf.compat.v1.strings.length
===========================
Computes the length of each string given in the input tensor.
```
tf.compat.v1.strings.length(
input, name=None, unit='BYTE'
)
```
```
strings = tf.constant(['Hello','TensorFlow', '🙂'])
tf.strings.length(strings).numpy() # default counts bytes
array([ 5, 10, 4], dtype=int32)
tf.strings.length(strings, unit="UTF8_CHAR").numpy()
array([ 5, 10, 1], dtype=int32)
```
| Args |
| `input` | A `Tensor` of type `string`. The strings for which to compute the length for each element. |
| `name` | A name for the operation (optional). |
| `unit` | An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to `"BYTE"`. The unit that is counted to compute string length. One of: `"BYTE"` (for the number of bytes in each string) or `"UTF8_CHAR"` (for the number of UTF-8 encoded Unicode code points in each string). Results are undefined if `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid UTF-8. |
| Returns |
| A `Tensor` of type `int32`, containing the length of the input string in the same element of the input tensor. |
tensorflow tf.compat.v1.strings.substr tf.compat.v1.strings.substr
===========================
Return substrings from `Tensor` of strings.
```
tf.compat.v1.strings.substr(
input, pos, len, name=None, unit='BYTE'
)
```
For each string in the input `Tensor`, creates a substring starting at index `pos` with a total length of `len`.
If `len` defines a substring that would extend beyond the length of the input string, or if `len` is negative, then as many characters as possible are used.
A negative `pos` indicates distance within the string backwards from the end.
If `pos` specifies an index which is out of range for any of the input strings, then an `InvalidArgumentError` is thrown.
`pos` and `len` must have the same shape, otherwise a `ValueError` is thrown on Op creation.
>
> **Note:** `Substr` supports broadcasting up to two dimensions. More about broadcasting [here](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html)
>
Examples
Using scalar `pos` and `len`:
```
input = [b'Hello', b'World']
position = 1
length = 3
output = [b'ell', b'orl']
```
Using `pos` and `len` with same shape as `input`:
```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen']]
position = [[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
length = [[2, 3, 4],
[4, 3, 2],
[5, 5, 5]]
output = [[b'en', b'eve', b'lve'],
[b'hirt', b'urt', b'te'],
[b'ixtee', b'vente', b'hteen']]
```
Broadcasting `pos` and `len` onto `input`:
```
input = [[b'ten', b'eleven', b'twelve'],
[b'thirteen', b'fourteen', b'fifteen'],
[b'sixteen', b'seventeen', b'eighteen'],
[b'nineteen', b'twenty', b'twentyone']]
position = [1, 2, 3]
length = [1, 2, 3]
output = [[b'e', b'ev', b'lve'],
[b'h', b'ur', b'tee'],
[b'i', b've', b'hte'],
[b'i', b'en', b'nty']]
```
Broadcasting `input` onto `pos` and `len`:
```
input = b'thirteen'
position = [1, 5, 7]
length = [3, 2, 1]
output = [b'hir', b'ee', b'n']
```
| Raises |
| * `ValueError`: If the first argument cannot be converted to a Tensor of `dtype string`.
* `InvalidArgumentError`: If indices are out of range.
* `ValueError`: If `pos` and `len` are not the same shape.
|
| Args |
| `input` | A `Tensor` of type `string`. Tensor of strings |
| `pos` | A `Tensor`. Must be one of the following types: `int32`, `int64`. Scalar defining the position of first character in each substring |
| `len` | A `Tensor`. Must have the same type as `pos`. Scalar defining the number of characters to include in each substring |
| `unit` | An optional `string` from: `"BYTE", "UTF8_CHAR"`. Defaults to `"BYTE"`. The unit that is used to create the substring. One of: `"BYTE"` (for defining position and length by bytes) or `"UTF8_CHAR"` (for the UTF-8 encoded Unicode code points). The default is `"BYTE"`. Results are undefined if `unit=UTF8_CHAR` and the `input` strings do not contain structurally valid UTF-8. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `string`. |
| programming_docs |
tensorflow Module: tf.compat.v1.types.experimental Module: tf.compat.v1.types.experimental
=======================================
Public API for tf.types.experimental namespace.
Type Aliases
------------
[`TensorLike`](../../../types/experimental/tensorlike)
tensorflow tf.compat.v1.flags.ArgumentParser tf.compat.v1.flags.ArgumentParser
=================================
Base class used to parse and convert arguments.
The parse() method checks to make sure that the string argument is a legal value and convert it to a native type. If the value cannot be converted, it should throw a 'ValueError' exception with a human readable explanation of why the value is illegal.
Subclasses should also define a syntactic\_help string which may be presented to the user to describe the form of the legal values.
Argument parser classes must be stateless, since instances are cached and shared between flags. Initializer arguments are allowed, but all member variables must be derived from initializer arguments only.
Methods
-------
### `flag_type`
```
flag_type()
```
Returns a string representing the type of the flag.
### `parse`
```
parse(
argument
)
```
Parses the string argument and returns the native value.
By default it returns its argument unmodified.
| Args |
| `argument` | string argument passed in the commandline. |
| Raises |
| `ValueError` | Raised when it fails to parse the argument. |
| `TypeError` | Raised when the argument has the wrong type. |
| Returns |
| The parsed value in native type. |
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.ListSerializer tf.compat.v1.flags.ListSerializer
=================================
Base class for generating string representations of a flag value.
Inherits From: [`ArgumentSerializer`](argumentserializer)
```
tf.compat.v1.flags.ListSerializer(
list_sep
)
```
Methods
-------
### `serialize`
```
serialize(
value
)
```
See base class.
tensorflow tf.compat.v1.flags.FlagHolder tf.compat.v1.flags.FlagHolder
=============================
Holds a defined flag.
```
tf.compat.v1.flags.FlagHolder(
flag_values, flag, ensure_non_none_value=False
)
```
This facilitates a cleaner api around global state. Instead of
```
flags.DEFINE_integer('foo', ...)
flags.DEFINE_integer('bar', ...)
...
def method():
# prints parsed value of 'bar' flag
print(flags.FLAGS.foo)
# runtime error due to typo or possibly bad coding style.
print(flags.FLAGS.baz)
```
it encourages code like
```
FOO_FLAG = flags.DEFINE_integer('foo', ...)
BAR_FLAG = flags.DEFINE_integer('bar', ...)
...
def method():
print(FOO_FLAG.value)
print(BAR_FLAG.value)
```
since the name of the flag appears only once in the source code.
| Args |
| `flag_values` | The container the flag is registered to. |
| `flag` | The flag object for this flag. |
| `ensure_non_none_value` | Is the value of the flag allowed to be None. |
| Attributes |
| `default` | Returns the default value of the flag. |
| `name` | |
| `present` | Returns True if the flag was parsed from command-line flags. |
| `value` | Returns the value of the flag. If \_ensure\_non\_none\_value is True, then return value is not None. |
Methods
-------
### `__bool__`
```
__bool__()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__nonzero__`
```
__nonzero__()
```
tensorflow tf.compat.v1.flags.EnumClassSerializer tf.compat.v1.flags.EnumClassSerializer
======================================
Class for generating string representations of an enum class flag value.
Inherits From: [`ArgumentSerializer`](argumentserializer)
```
tf.compat.v1.flags.EnumClassSerializer(
lowercase
)
```
| Args |
| `lowercase` | If True, enum member names are lowercased during serialization. |
Methods
-------
### `serialize`
```
serialize(
value
)
```
Returns a serialized string of the Enum class value.
tensorflow tf.compat.v1.flags.doc_to_help tf.compat.v1.flags.doc\_to\_help
================================
Takes a **doc** string and reformats it as help.
```
tf.compat.v1.flags.doc_to_help(
doc
)
```
tensorflow tf.compat.v1.flags.BooleanParser tf.compat.v1.flags.BooleanParser
================================
Parser of boolean values.
Inherits From: [`ArgumentParser`](argumentparser)
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
See base class.
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.FLAGS tf.compat.v1.flags.FLAGS
========================
Registry of 'Flag' objects.
```
tf.compat.v1.flags.FLAGS(
*args, **kwargs
)
```
A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: flags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via **setitem**: FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through **getattr**. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag' objects through the **call** method. Unparsed arguments, including argv[0](e.g.%20the%20program%20name) are returned. argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use of the dictionary-like operator, **getitem**: x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects.
tensorflow tf.compat.v1.flags.CsvListSerializer tf.compat.v1.flags.CsvListSerializer
====================================
Base class for generating string representations of a flag value.
Inherits From: [`ArgumentSerializer`](argumentserializer)
```
tf.compat.v1.flags.CsvListSerializer(
list_sep
)
```
Methods
-------
### `serialize`
```
serialize(
value
)
```
Serializes a list as a CSV string or unicode.
tensorflow tf.compat.v1.flags.mark_flags_as_mutual_exclusive tf.compat.v1.flags.mark\_flags\_as\_mutual\_exclusive
=====================================================
Ensures that only one flag among flag\_names is not None.
```
tf.compat.v1.flags.mark_flags_as_mutual_exclusive(
flag_names, required=False, flag_values=_flagvalues.FLAGS
)
```
Important note: This validator checks if flag values are None, and it does not distinguish between default and explicit values. Therefore, this validator does not make sense when applied to flags with default values other than None, including other false values (e.g. False, 0, '', []). That includes multi flags with a default value of [] instead of None.
| Args |
| `flag_names` | [str], names of the flags. |
| `required` | bool. If true, exactly one of the flags must have a value other than None. Otherwise, at most one of the flags can have a value other than None, and it is valid for all of the flags to be None. |
| `flag_values` | flags.FlagValues, optional FlagValues instance where the flags are defined. |
tensorflow tf.compat.v1.flags.ListParser tf.compat.v1.flags.ListParser
=============================
Parser for a comma-separated list of strings.
Inherits From: [`BaseListParser`](baselistparser), [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.ListParser()
```
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
Parses argument as comma-separated list of strings.
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.ArgumentSerializer tf.compat.v1.flags.ArgumentSerializer
=====================================
Base class for generating string representations of a flag value.
Methods
-------
### `serialize`
```
serialize(
value
)
```
Returns a serialized string of the value.
tensorflow tf.compat.v1.flags.DEFINE_string tf.compat.v1.flags.DEFINE\_string
=================================
Registers a flag whose value can be any string.
```
tf.compat.v1.flags.DEFINE_string(
name, default, help, flag_values=_flagvalues.FLAGS, required=False, **args
)
```
tensorflow tf.compat.v1.flags.EnumClassFlag tf.compat.v1.flags.EnumClassFlag
================================
Basic enum flag; its value is an enum class's member.
Inherits From: [`Flag`](flag)
```
tf.compat.v1.flags.EnumClassFlag(
name,
default,
help,
enum_class,
short_name=None,
case_sensitive=False,
**args
)
```
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
Returns a str that describes the type of the flag.
>
> **Note:** we use strings, and not the types.\*Type constants because our flags can have more exotic types, e.g., 'comma separated list of strings', 'whitespace separated list of strings', etc.
>
### `parse`
```
parse(
argument
)
```
Parses string and sets flag value.
| Args |
| `argument` | str or the correct flag value type, argument to be parsed. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
tensorflow tf.compat.v1.flags.text_wrap tf.compat.v1.flags.text\_wrap
=============================
Wraps a given text to a maximum line length and returns it.
```
tf.compat.v1.flags.text_wrap(
text, length=None, indent='', firstline_indent=None
)
```
It turns lines that only contain whitespace into empty lines, keeps new lines, and expands tabs using 4 spaces.
| Args |
| [`text`](https://www.tensorflow.org/text/api_docs/python/text) | str, text to wrap. |
| `length` | int, maximum length of a line, includes indentation. If this is None then use get\_help\_width() |
| `indent` | str, indent for all but first line. |
| `firstline_indent` | str, indent for first line; if None, fall back to indent. |
| Returns |
| str, the wrapped text. |
| Raises |
| `ValueError` | Raised if indent or firstline\_indent not shorter than length. |
tensorflow tf.compat.v1.flags.mark_flags_as_required tf.compat.v1.flags.mark\_flags\_as\_required
============================================
Ensures that flags are not None during program execution.
```
tf.compat.v1.flags.mark_flags_as_required(
flag_names, flag_values=_flagvalues.FLAGS
)
```
If your module might be imported by others, and you only wish to make the flag required when the module is directly executed, call this method like this:
if **name** == '**main**': flags.mark\_flags\_as\_required(['flag1', 'flag2', 'flag3']) app.run()
| Args |
| `flag_names` | Sequence[str], names of the flags. |
| `flag_values` | flags.FlagValues, optional FlagValues instance where the flags are defined. |
| Raises |
| `AttributeError` | If any of flag name has not already been defined as a flag. |
tensorflow tf.compat.v1.flags.DEFINE_bool tf.compat.v1.flags.DEFINE\_bool
===============================
Registers a boolean flag.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.flags.DEFINE_boolean`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/flags/DEFINE_bool)
```
tf.compat.v1.flags.DEFINE_bool(
name,
default,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
required=False,
**args
)
```
Such a boolean flag does not take an argument. If a user wants to specify a false value explicitly, the long option beginning with 'no' must be used: i.e. --noflag
This flag will have a value of None, True or False. None is possible if default=None and the user does not specify the flag on the command line.
| Args |
| `name` | str, the flag name. |
| `default` | bool|str|None, the default value of the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.FlagValues tf.compat.v1.flags.FlagValues
=============================
Registry of 'Flag' objects.
```
tf.compat.v1.flags.FlagValues()
```
A 'FlagValues' can then scan command line arguments, passing flag arguments through to the 'Flag' objects that it owns. It also provides easy access to the flag values. Typically only one 'FlagValues' object is needed by an application: flags.FLAGS
This class is heavily overloaded:
'Flag' objects are registered via **setitem**: FLAGS['longname'] = x # register a new flag
The .value attribute of the registered 'Flag' objects can be accessed as attributes of this 'FlagValues' object, through **getattr**. Both the long and short name of the original 'Flag' objects can be used to access its value: FLAGS.longname # parsed flag value FLAGS.x # parsed flag value (short name)
Command line arguments are scanned and passed to the registered 'Flag' objects through the **call** method. Unparsed arguments, including argv[0](e.g.%20the%20program%20name) are returned. argv = FLAGS(sys.argv) # scan command line arguments
The original registered Flag objects can be retrieved through the use of the dictionary-like operator, **getitem**: x = FLAGS['longname'] # access the registered Flag object
The str() operator of a 'FlagValues' object provides help for all of the registered 'Flag' objects.
Methods
-------
### `append_flag_values`
```
append_flag_values(
flag_values
)
```
Appends flags registered in another FlagValues instance.
| Args |
| `flag_values` | FlagValues, the FlagValues instance from which to copy flags. |
### `append_flags_into_file`
```
append_flags_into_file(
filename
)
```
Appends all flags assignments from this FlagInfo object to a file.
Output will be in the format of a flagfile.
>
> **Note:** MUST mirror the behavior of the C++ AppendFlagsIntoFile from <https://github.com/gflags/gflags>
>
| Args |
| `filename` | str, name of the file. |
### `find_module_defining_flag`
```
find_module_defining_flag(
flagname, default=None
)
```
Return the name of the module defining this flag, or default.
| Args |
| `flagname` | str, name of the flag to lookup. |
| `default` | Value to return if flagname is not defined. Defaults to None. |
| Returns |
| The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. |
### `find_module_id_defining_flag`
```
find_module_id_defining_flag(
flagname, default=None
)
```
Return the ID of the module defining this flag, or default.
| Args |
| `flagname` | str, name of the flag to lookup. |
| `default` | Value to return if flagname is not defined. Defaults to None. |
| Returns |
| The ID of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. |
### `flag_values_dict`
```
flag_values_dict()
```
Returns a dictionary that maps flag names to flag values.
### `flags_by_module_dict`
```
flags_by_module_dict()
```
Returns the dictionary of module\_name -> list of defined flags.
| Returns |
| A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. |
### `flags_by_module_id_dict`
```
flags_by_module_id_dict()
```
Returns the dictionary of module\_id -> list of defined flags.
| Returns |
| A dictionary. Its keys are module IDs (ints). Its values are lists of Flag objects. |
### `flags_into_string`
```
flags_into_string()
```
Returns a string with the flags assignments from this FlagValues object.
This function ignores flags whose value is None. Each flag assignment is separated by a newline.
>
> **Note:** MUST mirror the behavior of the C++ CommandlineFlagsIntoString from <https://github.com/gflags/gflags>
>
| Returns |
| str, the string with the flags assignments from this FlagValues object. The flags are ordered by (module\_name, flag\_name). |
### `get_flag_value`
```
get_flag_value(
name, default
)
```
Returns the value of a flag (if not None) or a default value.
| Args |
| `name` | str, the name of a flag. |
| `default` | Default value to use if the flag value is None. |
| Returns |
| Requested flag value or default. |
### `get_flags_for_module`
```
get_flags_for_module(
module
)
```
Returns the list of flags defined by a module.
| Args |
| `module` | module|str, the module to get flags from. |
| Returns |
| [Flag], a new list of Flag instances. Caller may update this list as |
| `desired` | none of those changes will affect the internals of this FlagValue instance. |
### `get_help`
```
get_help(
prefix='', include_special_flags=True
)
```
Returns a help string for all known flags.
| Args |
| `prefix` | str, per-line output prefix. |
| `include_special_flags` | bool, whether to include description of SPECIAL\_FLAGS, i.e. --flagfile and --undefok. |
| Returns |
| str, formatted help message. |
### `get_key_flags_for_module`
```
get_key_flags_for_module(
module
)
```
Returns the list of key flags for a module.
| Args |
| `module` | module|str, the module to get key flags from. |
| Returns |
| [Flag], a new list of Flag instances. Caller may update this list as |
| `desired` | none of those changes will affect the internals of this FlagValue instance. |
### `is_gnu_getopt`
```
is_gnu_getopt()
```
### `is_parsed`
```
is_parsed()
```
Returns whether flags were parsed.
### `key_flags_by_module_dict`
```
key_flags_by_module_dict()
```
Returns the dictionary of module\_name -> list of key flags.
| Returns |
| A dictionary. Its keys are module names (strings). Its values are lists of Flag objects. |
### `main_module_help`
```
main_module_help()
```
Describes the key flags of the main module.
| Returns |
| str, describing the key flags of the main module. |
### `mark_as_parsed`
```
mark_as_parsed()
```
Explicitly marks flags as parsed.
Use this when the caller knows that this FlagValues has been parsed as if a **call**() invocation has happened. This is only a public method for use by things like appcommands which do additional command like parsing.
### `module_help`
```
module_help(
module
)
```
Describes the key flags of a module.
| Args |
| `module` | module|str, the module to describe the key flags for. |
| Returns |
| str, describing the key flags of a module. |
### `read_flags_from_files`
```
read_flags_from_files(
argv, force_gnu=True
)
```
Processes command line args, but also allow args to be read from file.
| Args |
| `argv` | [str], a list of strings, usually sys.argv[1:], which may contain one or more flagfile directives of the form --flagfile="./filename". Note that the name of the program (sys.argv[0]) should be omitted. |
| `force_gnu` | bool, if False, --flagfile parsing obeys the FLAGS.is\_gnu\_getopt() value. If True, ignore the value and always follow gnu\_getopt semantics. |
| Returns |
| A new list which has the original list combined with what we read from any flagfile(s). |
| Raises |
| `IllegalFlagValueError` | Raised when --flagfile is provided with no argument. |
This function is called by FLAGS(argv). It scans the input list for a flag that looks like: --flagfile=. Then it opens , reads all valid key and value pairs and inserts them into the input list in exactly the place where the --flagfile arg is found.
Note that your application's flags are still defined the usual way using absl.flags DEFINE\_flag() type functions.
Notes (assuming we're getting a commandline of some sort as our input): --> For duplicate flags, the last one we hit should "win". --> Since flags that appear later win, a flagfile's settings can be "weak" if the --flagfile comes at the beginning of the argument sequence, and it can be "strong" if the --flagfile comes at the end. --> A further "--flagfile=" CAN be nested in a flagfile. It will be expanded in exactly the spot where it is found. --> In a flagfile, a line beginning with # or // is a comment. --> Entirely blank lines *should* be ignored.
### `register_flag_by_module`
```
register_flag_by_module(
module_name, flag
)
```
Records the module that defines a specific flag.
We keep track of which flag is defined by which module so that we can later sort the flags by module.
| Args |
| `module_name` | str, the name of a Python module. |
| `flag` | Flag, the Flag instance that is key to the module. |
### `register_flag_by_module_id`
```
register_flag_by_module_id(
module_id, flag
)
```
Records the module that defines a specific flag.
| Args |
| `module_id` | int, the ID of the Python module. |
| `flag` | Flag, the Flag instance that is key to the module. |
### `register_key_flag_for_module`
```
register_key_flag_for_module(
module_name, flag
)
```
Specifies that a flag is a key flag for a module.
| Args |
| `module_name` | str, the name of a Python module. |
| `flag` | Flag, the Flag instance that is key to the module. |
### `remove_flag_values`
```
remove_flag_values(
flag_values
)
```
Remove flags that were previously appended from another FlagValues.
| Args |
| `flag_values` | FlagValues, the FlagValues instance containing flags to remove. |
### `set_default`
```
set_default(
name, value
)
```
Changes the default value of the named flag object.
The flag's current value is also updated if the flag is currently using the default value, i.e. not specified in the command line, and not set by FLAGS.name = value.
| Args |
| `name` | str, the name of the flag to modify. |
| `value` | The new default value. |
| Raises |
| `UnrecognizedFlagError` | Raised when there is no registered flag named name. |
| `IllegalFlagValueError` | Raised when value is not valid. |
### `set_gnu_getopt`
```
set_gnu_getopt(
gnu_getopt=True
)
```
Sets whether or not to use GNU style scanning.
GNU style allows mixing of flag and non-flag arguments. See <http://docs.python.org/library/getopt.html#getopt.gnu_getopt>
| Args |
| `gnu_getopt` | bool, whether or not to use GNU style scanning. |
### `unparse_flags`
```
unparse_flags()
```
Unparses all flags to the point before any FLAGS(argv) was called.
### `validate_all_flags`
```
validate_all_flags()
```
Verifies whether all flags pass validation.
| Raises |
| `AttributeError` | Raised if validators work with a non-existing flag. |
| `IllegalFlagValueError` | Raised if validation fails for at least one validator. |
### `write_help_in_xml_format`
```
write_help_in_xml_format(
outfile=None
)
```
Outputs flag documentation in XML format.
>
> **Note:** We use element names that are consistent with those used by the C++ command-line flag library, from <https://github.com/gflags/gflags> We also use a few new elements (e.g., ), but we do not interfere / overlap with existing XML elements used by the C++ library. Please maintain this consistency.
>
| Args |
| `outfile` | File object we write to. Default None means sys.stdout. |
### `__call__`
```
__call__(
argv, known_only=False
)
```
Parses flags from argv; stores parsed flags into this FlagValues object.
All unparsed arguments are returned.
| Args |
| `argv` | a tuple/list of strings. |
| `known_only` | bool, if True, parse and remove known flags; return the rest untouched. Unknown flags specified by --undefok are not returned. |
| Returns |
| The list of arguments not parsed as options, including argv[0]. |
| Raises |
| `Error` | Raised on any parsing error. |
| `TypeError` | Raised on passing wrong type of arguments. |
| `ValueError` | Raised on flag value parsing error. |
### `__contains__`
```
__contains__(
name
)
```
Returns True if name is a value (flag) in the dict.
### `__getitem__`
```
__getitem__(
name
)
```
Returns the Flag object for the flag --name.
### `__iter__`
```
__iter__()
```
### `__len__`
```
__len__()
```
| programming_docs |
tensorflow tf.compat.v1.flags.Flag tf.compat.v1.flags.Flag
=======================
Information about a command-line flag.
```
tf.compat.v1.flags.Flag(
parser,
serializer,
name,
default,
help_string,
short_name=None,
boolean=False,
allow_override=False,
allow_override_cpp=False,
allow_hide_cpp=False,
allow_overwrite=True,
allow_using_method_names=False
)
```
'Flag' objects define the following fields: .name - the name for this flag; .default - the default value for this flag; .default\_unparsed - the unparsed default value for this flag. .default\_as\_str - default value as repr'd string, e.g., "'true'" (or None); .value - the most recent parsed value of this flag; set by parse(); .help - a help string or None if no help is available; .short\_name - the single letter alias for this flag (or None); .boolean - if 'true', this flag does not accept arguments; .present - true if this flag was parsed from command line flags; .parser - an ArgumentParser object; .serializer - an ArgumentSerializer object; .allow\_override - the flag may be redefined without raising an error, and newly defined flag overrides the old one. .allow\_override\_cpp - use the flag from C++ if available; the flag definition is replaced by the C++ flag after init; .allow\_hide\_cpp - use the Python flag despite having a C++ flag with the same name (ignore the C++ flag); .using\_default\_value - the flag value has not been set by user; .allow\_overwrite - the flag may be parsed more than once without raising an error, the last set value will be used; .allow\_using\_method\_names - whether this flag can be defined even if it has a name that conflicts with a FlagValues method.
The only public method of a 'Flag' object is parse(), but it is typically only called by a 'FlagValues' object. The parse() method is a thin wrapper around the 'ArgumentParser' parse() method. The parsed value is saved in .value, and the .present attribute is updated. If this flag was already present, an Error is raised.
parse() is also called during **init** to parse the default value and initialize the .value attribute. This enables other python modules to safely use flags even if the **main** module neglects to parse the command line arguments. The .present attribute is cleared after **init** parsing. If the default value is set to None, then the **init** parsing step is skipped and the .value attribute is initialized to None.
>
> **Note:** The default value is also presented to the user in the help string, so it is important that it be a legal value for this flag.
>
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
Returns a str that describes the type of the flag.
>
> **Note:** we use strings, and not the types.\*Type constants because our flags can have more exotic types, e.g., 'comma separated list of strings', 'whitespace separated list of strings', etc.
>
### `parse`
```
parse(
argument
)
```
Parses string and sets flag value.
| Args |
| `argument` | str or the correct flag value type, argument to be parsed. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
tensorflow tf.compat.v1.flags.DuplicateFlagError tf.compat.v1.flags.DuplicateFlagError
=====================================
Raised if there is a flag naming conflict.
Inherits From: [`Error`](error)
Methods
-------
### `from_flag`
```
@classmethod
from_flag(
flagname, flag_values, other_flag_values=None
)
```
Creates a DuplicateFlagError by providing flag name and values.
| Args |
| `flagname` | str, the name of the flag being redefined. |
| `flag_values` | FlagValues, the FlagValues instance containing the first definition of flagname. |
| `other_flag_values` | FlagValues, if it is not None, it should be the FlagValues object where the second definition of flagname occurs. If it is None, we assume that we're being called when attempting to create the flag a second time, and we use the module calling this one as the source of the second definition. |
| Returns |
| An instance of DuplicateFlagError. |
tensorflow tf.compat.v1.flags.BaseListParser tf.compat.v1.flags.BaseListParser
=================================
Base class for a parser of lists of strings.
Inherits From: [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.BaseListParser(
token=None, name=None
)
```
To extend, inherit from this class; from the subclass **init**, call
```
BaseListParser.__init__(self, token, name)
```
where token is a character used to tokenize, and name is a description of the separator.
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
See base class.
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.DEFINE_alias tf.compat.v1.flags.DEFINE\_alias
================================
Defines an alias flag for an existing one.
```
tf.compat.v1.flags.DEFINE_alias(
name, original_name, flag_values=_flagvalues.FLAGS, module_name=None
)
```
| Args |
| `name` | str, the flag name. |
| `original_name` | str, the original flag name. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | A string, the name of the module that defines this flag. |
| Returns |
| a handle to defined flag. |
| Raises |
| `flags.FlagError` | UnrecognizedFlagError: if the referenced flag doesn't exist. DuplicateFlagError: if the alias name has been used by some existing flag. |
tensorflow tf.compat.v1.flags.mark_flag_as_required tf.compat.v1.flags.mark\_flag\_as\_required
===========================================
Ensures that flag is not None during program execution.
```
tf.compat.v1.flags.mark_flag_as_required(
flag_name, flag_values=_flagvalues.FLAGS
)
```
Registers a flag validator, which will follow usual validator rules. Important note: validator will pass for any non-None value, such as False, 0 (zero), '' (empty string) and so on.
If your module might be imported by others, and you only wish to make the flag required when the module is directly executed, call this method like this:
if **name** == '**main**': flags.mark\_flag\_as\_required('your\_flag\_name') app.run()
| Args |
| `flag_name` | str, name of the flag |
| `flag_values` | flags.FlagValues, optional FlagValues instance where the flag is defined. |
| Raises |
| `AttributeError` | Raised when flag\_name is not registered as a valid flag name. |
tensorflow tf.compat.v1.flags.register_multi_flags_validator tf.compat.v1.flags.register\_multi\_flags\_validator
====================================================
Adds a constraint to multiple flags.
```
tf.compat.v1.flags.register_multi_flags_validator(
flag_names,
multi_flags_checker,
message='Flags validation failed',
flag_values=_flagvalues.FLAGS
)
```
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value.
| Args |
| `flag_names` | [str], a list of the flag names to be checked. |
| `multi_flags_checker` | callable, a function to validate the flag. input - dict, with keys() being flag\_names, and value for each key being the value of the corresponding flag (string, boolean, etc). output - bool, True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise flags.ValidationError. |
| `message` | str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. |
| `flag_values` | flags.FlagValues, optional FlagValues instance to validate against. |
| Raises |
| `AttributeError` | Raised when a flag is not registered as a valid flag name. |
tensorflow tf.compat.v1.flags.DEFINE_enum tf.compat.v1.flags.DEFINE\_enum
===============================
Registers a flag whose value can be any string from enum\_values.
```
tf.compat.v1.flags.DEFINE_enum(
name,
default,
enum_values,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
required=False,
**args
)
```
Instead of a string enum, prefer `DEFINE_enum_class`, which allows defining enums from an `enum.Enum` class.
| Args |
| `name` | str, the flag name. |
| `default` | str|None, the default value of the flag. |
| `enum_values` | [str], a non-empty list of strings with the possible values for the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.validator tf.compat.v1.flags.validator
============================
A function decorator for defining a flag validator.
```
tf.compat.v1.flags.validator(
flag_name,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS
)
```
Registers the decorated function as a validator for flag\_name, e.g.
@flags.validator('foo') def \_CheckFoo(foo): ...
See register\_validator() for the specification of checker function.
| Args |
| `flag_name` | str, name of the flag to be checked. |
| `message` | str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. |
| `flag_values` | flags.FlagValues, optional FlagValues instance to validate against. |
| Returns |
| A function decorator that registers its function argument as a validator. |
| Raises |
| `AttributeError` | Raised when flag\_name is not registered as a valid flag name. |
tensorflow tf.compat.v1.flags.DEFINE_multi tf.compat.v1.flags.DEFINE\_multi
================================
Registers a generic MultiFlag that parses its args with a given parser.
```
tf.compat.v1.flags.DEFINE_multi(
parser,
serializer,
name,
default,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
required=False,
**args
)
```
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes for options which can appear multiple times can call this module function to register their flags.
| Args |
| `parser` | ArgumentParser, used to parse the flag arguments. |
| `serializer` | ArgumentSerializer, the flag serializer instance. |
| `name` | str, the flag name. |
| `default` | Union[Iterable[T], Text, None], the default value of the flag. If the value is text, it will be parsed as if it was provided from the command line. If the value is a non-string iterable, it will be iterated over to create a shallow copy of the values. If it is None, it is left as-is. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.EnumClassParser tf.compat.v1.flags.EnumClassParser
==================================
Parser of an Enum class member.
Inherits From: [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.EnumClassParser(
enum_class, case_sensitive=True
)
```
| Args |
| `enum_class` | class, the Enum class with all possible flag values. |
| `case_sensitive` | bool, whether or not the enum is to be case-sensitive. If False, all member names must be unique when case is ignored. |
| Raises |
| `TypeError` | When enum\_class is not a subclass of Enum. |
| `ValueError` | When enum\_class is empty. |
| Attributes |
| `member_names` | The accepted enum names, in lowercase if not case sensitive. |
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
Determines validity of argument and returns the correct element of enum.
| Args |
| `argument` | str or Enum class member, the supplied flag value. |
| Returns |
| The first matching Enum class member in Enum class. |
| Raises |
| `ValueError` | Raised when argument didn't match anything in enum. |
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.DEFINE_float tf.compat.v1.flags.DEFINE\_float
================================
Registers a flag whose value must be a float.
```
tf.compat.v1.flags.DEFINE_float(
name,
default,
help,
lower_bound=None,
upper_bound=None,
flag_values=_flagvalues.FLAGS,
required=False,
**args
)
```
If lower\_bound or upper\_bound are set, then this flag must be within the given range.
| Args |
| `name` | str, the flag name. |
| `default` | float|str|None, the default value of the flag. |
| `help` | str, the help message. |
| `lower_bound` | float, min value of the flag. |
| `upper_bound` | float, max value of the flag. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to DEFINE. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.EnumParser tf.compat.v1.flags.EnumParser
=============================
Parser of a string enum value (a string value from a given set).
Inherits From: [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.EnumParser(
enum_values, case_sensitive=True
)
```
| Args |
| `enum_values` | [str], a non-empty list of string values in the enum. |
| `case_sensitive` | bool, whether or not the enum is to be case-sensitive. |
| Raises |
| `ValueError` | When enum\_values is empty. |
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
Determines validity of argument and returns the correct element of enum.
| Args |
| `argument` | str, the supplied flag value. |
| Returns |
| The first matching element from enum\_values. |
| Raises |
| `ValueError` | Raised when argument didn't match anything in enum. |
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.DEFINE_multi_string tf.compat.v1.flags.DEFINE\_multi\_string
========================================
Registers a flag whose value can be a list of any strings.
```
tf.compat.v1.flags.DEFINE_multi_string(
name, default, help, flag_values=_flagvalues.FLAGS, required=False, **args
)
```
Use the flag on the command line multiple times to place multiple string values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings.
| Args |
| `name` | str, the flag name. |
| `default` | Union[Iterable[Text], Text, None], the default value of the flag; see `DEFINE_multi`. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.multi_flags_validator tf.compat.v1.flags.multi\_flags\_validator
==========================================
A function decorator for defining a multi-flag validator.
```
tf.compat.v1.flags.multi_flags_validator(
flag_names,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS
)
```
Registers the decorated function as a validator for flag\_names, e.g.
@flags.multi\_flags\_validator(['foo', 'bar']) def \_CheckFooBar(flags\_dict): ...
See register\_multi\_flags\_validator() for the specification of checker function.
| Args |
| `flag_names` | [str], a list of the flag names to be checked. |
| `message` | str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. |
| `flag_values` | flags.FlagValues, optional FlagValues instance to validate against. |
| Returns |
| A function decorator that registers its function argument as a validator. |
| Raises |
| `AttributeError` | Raised when a flag is not registered as a valid flag name. |
tensorflow tf.compat.v1.flags.DEFINE_multi_float tf.compat.v1.flags.DEFINE\_multi\_float
=======================================
Registers a flag whose value can be a list of arbitrary floats.
```
tf.compat.v1.flags.DEFINE_multi_float(
name,
default,
help,
lower_bound=None,
upper_bound=None,
flag_values=_flagvalues.FLAGS,
required=False,
**args
)
```
Use the flag on the command line multiple times to place multiple float values into the list. The 'default' may be a single float (which will be converted into a single-element list) or a list of floats.
| Args |
| `name` | str, the flag name. |
| `default` | Union[Iterable[float], Text, None], the default value of the flag; see `DEFINE_multi`. |
| `help` | str, the help message. |
| `lower_bound` | float, min values of the flag. |
| `upper_bound` | float, max values of the flag. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.MultiEnumClassFlag tf.compat.v1.flags.MultiEnumClassFlag
=====================================
A multi\_enum\_class flag.
Inherits From: [`MultiFlag`](multiflag), [`Flag`](flag)
```
tf.compat.v1.flags.MultiEnumClassFlag(
name, default, help_string, enum_class, case_sensitive=False, **args
)
```
See the **doc** for MultiFlag for most behaviors of this class. In addition, this class knows how to handle enum.Enum instances as values for this flag type.
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
arguments
)
```
Parses one or more arguments with the installed parser.
| Args |
| `arguments` | a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
| programming_docs |
tensorflow tf.compat.v1.flags.EnumFlag tf.compat.v1.flags.EnumFlag
===========================
Basic enum flag; its value can be any string from list of enum\_values.
Inherits From: [`Flag`](flag)
```
tf.compat.v1.flags.EnumFlag(
name,
default,
help,
enum_values,
short_name=None,
case_sensitive=True,
**args
)
```
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
Returns a str that describes the type of the flag.
>
> **Note:** we use strings, and not the types.\*Type constants because our flags can have more exotic types, e.g., 'comma separated list of strings', 'whitespace separated list of strings', etc.
>
### `parse`
```
parse(
argument
)
```
Parses string and sets flag value.
| Args |
| `argument` | str or the correct flag value type, argument to be parsed. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
tensorflow tf.compat.v1.flags.DEFINE_spaceseplist tf.compat.v1.flags.DEFINE\_spaceseplist
=======================================
Registers a flag whose value is a whitespace-separated list of strings.
```
tf.compat.v1.flags.DEFINE_spaceseplist(
name,
default,
help,
comma_compat=False,
flag_values=_flagvalues.FLAGS,
required=False,
**args
)
```
Any whitespace can be used as a separator.
| Args |
| `name` | str, the flag name. |
| `default` | list|str|None, the default value of the flag. |
| `help` | str, the help message. |
| `comma_compat` | bool - Whether to support comma as an additional separator. If false then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.UnparsedFlagAccessError tf.compat.v1.flags.UnparsedFlagAccessError
==========================================
Raised when accessing the flag value from unparsed FlagValues.
Inherits From: [`Error`](error)
tensorflow tf.compat.v1.flags.flag_dict_to_args tf.compat.v1.flags.flag\_dict\_to\_args
=======================================
Convert a dict of values into process call parameters.
```
tf.compat.v1.flags.flag_dict_to_args(
flag_map, multi_flags=None
)
```
This method is used to convert a dictionary into a sequence of parameters for a binary that parses arguments using this module.
| Args |
| `flag_map` | dict, a mapping where the keys are flag names (strings). values are treated according to their type: * If value is None, then only the name is emitted.
* If value is True, then only the name is emitted.
* If value is False, then only the name prepended with 'no' is emitted.
* If value is a string then --name=value is emitted.
* If value is a collection, this will emit --name=value1,value2,value3, unless the flag name is in multi\_flags, in which case this will emit --name=value1 --name=value2 --name=value3.
* Everything else is converted to string an passed as such.
|
| `multi_flags` | set, names (strings) of flags that should be treated as multi-flags. |
| Yields |
| sequence of string suitable for a subprocess execution. |
tensorflow tf.compat.v1.flags.get_help_width tf.compat.v1.flags.get\_help\_width
===================================
Returns the integer width of help lines that is used in TextWrap.
```
tf.compat.v1.flags.get_help_width()
```
tensorflow tf.compat.v1.flags.DEFINE_multi_enum_class tf.compat.v1.flags.DEFINE\_multi\_enum\_class
=============================================
Registers a flag whose value can be a list of enum members.
```
tf.compat.v1.flags.DEFINE_multi_enum_class(
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
case_sensitive=False,
required=False,
**args
)
```
Use the flag on the command line multiple times to place multiple enum values into the list.
| Args |
| `name` | str, the flag name. |
| `default` | Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the default value of the flag; see `DEFINE_multi`; only differences are documented here. If the value is a single Enum, it is treated as a single-item list of that Enum value. If it is an iterable, text values within the iterable will be converted to the equivalent Enum objects. |
| `enum_class` | class, the Enum class with all the possible values for the flag. help: str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | A string, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `case_sensitive` | bool, whether to map strings to members of the enum\_class without considering case. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.UnrecognizedFlagError tf.compat.v1.flags.UnrecognizedFlagError
========================================
Raised when a flag is unrecognized.
Inherits From: [`Error`](error)
```
tf.compat.v1.flags.UnrecognizedFlagError(
flagname, flagvalue='', suggestions=None
)
```
| Attributes |
| `flagname` | str, the name of the unrecognized flag. |
| `flagvalue` | The value of the flag, empty if the flag is not defined. |
tensorflow tf.compat.v1.flags.DEFINE_list tf.compat.v1.flags.DEFINE\_list
===============================
Registers a flag whose value is a comma-separated list of strings.
```
tf.compat.v1.flags.DEFINE_list(
name, default, help, flag_values=_flagvalues.FLAGS, required=False, **args
)
```
The flag value is parsed with a CSV parser.
| Args |
| `name` | str, the flag name. |
| `default` | list|str|None, the default value of the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.disclaim_key_flags tf.compat.v1.flags.disclaim\_key\_flags
=======================================
Declares that the current module will not define any more key flags.
```
tf.compat.v1.flags.disclaim_key_flags()
```
Normally, the module that calls the DEFINE\_xxx functions claims the flag to be its key flag. This is undesirable for modules that define additional DEFINE\_yyy functions with its own flag parsers and serializers, since that module will accidentally claim flags defined by DEFINE\_yyy as its key flags. After calling this function, the module disclaims flag definitions thereafter, so the key flags will be correctly attributed to the caller of DEFINE\_yyy.
After calling this function, the module will not be able to define any more flags. This function will affect all FlagValues objects.
tensorflow tf.compat.v1.flags.MultiFlag tf.compat.v1.flags.MultiFlag
============================
A flag that can appear multiple time on the command-line.
Inherits From: [`Flag`](flag)
```
tf.compat.v1.flags.MultiFlag(
*args, **kwargs
)
```
The value of such a flag is a list that contains the individual values from all the appearances of that flag on the command-line.
See the **doc** for Flag for most behavior of this class. Only differences in behavior are described here:
* The default value may be either a single value or an iterable of values. A single value is transformed into a single-item list of that value.
* The value of the flag is always a list, even if the option was only supplied once, and even if the default value is a single value
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
arguments
)
```
Parses one or more arguments with the installed parser.
| Args |
| `arguments` | a single argument or a list of arguments (typically a list of default values); a single argument is converted internally into a list containing one item. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
tensorflow tf.compat.v1.flags.DEFINE_multi_integer tf.compat.v1.flags.DEFINE\_multi\_integer
=========================================
Registers a flag whose value can be a list of arbitrary integers.
```
tf.compat.v1.flags.DEFINE_multi_integer(
name,
default,
help,
lower_bound=None,
upper_bound=None,
flag_values=_flagvalues.FLAGS,
required=False,
**args
)
```
Use the flag on the command line multiple times to place multiple integer values into the list. The 'default' may be a single integer (which will be converted into a single-element list) or a list of integers.
| Args |
| `name` | str, the flag name. |
| `default` | Union[Iterable[int], Text, None], the default value of the flag; see `DEFINE_multi`. |
| `help` | str, the help message. |
| `lower_bound` | int, min values of the flag. |
| `upper_bound` | int, max values of the flag. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.DEFINE_enum_class tf.compat.v1.flags.DEFINE\_enum\_class
======================================
Registers a flag whose value can be the name of enum members.
```
tf.compat.v1.flags.DEFINE_enum_class(
name,
default,
enum_class,
help,
flag_values=_flagvalues.FLAGS,
module_name=None,
case_sensitive=False,
required=False,
**args
)
```
| Args |
| `name` | str, the flag name. |
| `default` | Enum|str|None, the default value of the flag. |
| `enum_class` | class, the Enum class with all the possible values for the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `case_sensitive` | bool, whether to map strings to members of the enum\_class without considering case. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.CantOpenFlagFileError tf.compat.v1.flags.CantOpenFlagFileError
========================================
Raised when flagfile fails to open.
Inherits From: [`Error`](error)
E.g. the file doesn't exist, or has wrong permissions.
tensorflow tf.compat.v1.flags.DEFINE_integer tf.compat.v1.flags.DEFINE\_integer
==================================
Registers a flag whose value must be an integer.
```
tf.compat.v1.flags.DEFINE_integer(
name,
default,
help,
lower_bound=None,
upper_bound=None,
flag_values=_flagvalues.FLAGS,
required=False,
**args
)
```
If lower\_bound, or upper\_bound are set, then this flag must be within the given range.
| Args |
| `name` | str, the flag name. |
| `default` | int|str|None, the default value of the flag. |
| `help` | str, the help message. |
| `lower_bound` | int, min value of the flag. |
| `upper_bound` | int, max value of the flag. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to DEFINE. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.ValidationError tf.compat.v1.flags.ValidationError
==================================
Raised when flag validator constraint is not satisfied.
Inherits From: [`Error`](error)
tensorflow tf.compat.v1.flags.mark_bool_flags_as_mutual_exclusive tf.compat.v1.flags.mark\_bool\_flags\_as\_mutual\_exclusive
===========================================================
Ensures that only one flag among flag\_names is True.
```
tf.compat.v1.flags.mark_bool_flags_as_mutual_exclusive(
flag_names, required=False, flag_values=_flagvalues.FLAGS
)
```
| Args |
| `flag_names` | [str], names of the flags. |
| `required` | bool. If true, exactly one flag must be True. Otherwise, at most one flag can be True, and it is valid for all flags to be False. |
| `flag_values` | flags.FlagValues, optional FlagValues instance where the flags are defined. |
tensorflow tf.compat.v1.flags.IllegalFlagValueError tf.compat.v1.flags.IllegalFlagValueError
========================================
Raised when the flag command line argument is illegal.
Inherits From: [`Error`](error)
tensorflow tf.compat.v1.flags.DEFINE_multi_enum tf.compat.v1.flags.DEFINE\_multi\_enum
======================================
Registers a flag whose value can be a list strings from enum\_values.
```
tf.compat.v1.flags.DEFINE_multi_enum(
name,
default,
enum_values,
help,
flag_values=_flagvalues.FLAGS,
case_sensitive=True,
required=False,
**args
)
```
Use the flag on the command line multiple times to place multiple enum values into the list. The 'default' may be a single string (which will be converted into a single-element list) or a list of strings.
| Args |
| `name` | str, the flag name. |
| `default` | Union[Iterable[Text], Text, None], the default value of the flag; see `DEFINE_multi`. |
| `enum_values` | [str], a non-empty list of strings with the possible values for the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `case_sensitive` | Whether or not the enum is to be case-sensitive. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | Dictionary with extra keyword args that are passed to the Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.FloatParser tf.compat.v1.flags.FloatParser
==============================
Parser of floating point values.
Inherits From: [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.FloatParser(
lower_bound=None, upper_bound=None
)
```
Parsed value may be bounded to a given upper and lower bound.
Methods
-------
### `convert`
```
convert(
argument
)
```
Returns the float value of argument.
### `flag_type`
```
flag_type()
```
See base class.
### `is_outside_bounds`
```
is_outside_bounds(
val
)
```
Returns whether the value is outside the bounds or not.
### `parse`
```
parse(
argument
)
```
See base class.
| Class Variables |
| number\_article | `'a'` |
| number\_name | `'number'` |
| syntactic\_help | `'a number'` |
tensorflow tf.compat.v1.flags.BooleanFlag tf.compat.v1.flags.BooleanFlag
==============================
Basic boolean flag.
Inherits From: [`Flag`](flag)
```
tf.compat.v1.flags.BooleanFlag(
name, default, help, short_name=None, **args
)
```
Boolean flags do not take any arguments, and their value is either True (1) or False (0). The false value is specified on the command line by prepending the word 'no' to either the long or the short flag name.
For example, if a Boolean flag was created whose long name was 'update' and whose short name was 'x', then this flag could be explicitly unset through either --noupdate or --nox.
| Attributes |
| `value` | |
Methods
-------
### `flag_type`
```
flag_type()
```
Returns a str that describes the type of the flag.
>
> **Note:** we use strings, and not the types.\*Type constants because our flags can have more exotic types, e.g., 'comma separated list of strings', 'whitespace separated list of strings', etc.
>
### `parse`
```
parse(
argument
)
```
Parses string and sets flag value.
| Args |
| `argument` | str or the correct flag value type, argument to be parsed. |
### `serialize`
```
serialize()
```
Serializes the flag.
### `unparse`
```
unparse()
```
### `__eq__`
```
__eq__(
other
)
```
Return self==value.
### `__ge__`
```
__ge__(
other, NotImplemented=NotImplemented
)
```
Return a >= b. Computed by @total\_ordering from (not a < b).
### `__gt__`
```
__gt__(
other, NotImplemented=NotImplemented
)
```
Return a > b. Computed by @total\_ordering from (not a < b) and (a != b).
### `__le__`
```
__le__(
other, NotImplemented=NotImplemented
)
```
Return a <= b. Computed by @total\_ordering from (a < b) or (a == b).
### `__lt__`
```
__lt__(
other
)
```
Return self<value.
tensorflow tf.compat.v1.flags.register_validator tf.compat.v1.flags.register\_validator
======================================
Adds a constraint, which will be enforced during program execution.
```
tf.compat.v1.flags.register_validator(
flag_name,
checker,
message='Flag validation failed',
flag_values=_flagvalues.FLAGS
)
```
The constraint is validated when flags are initially parsed, and after each change of the corresponding flag's value. Args: flag\_name: str, name of the flag to be checked. checker: callable, a function to validate the flag. input - A single positional argument: The value of the corresponding flag (string, boolean, etc. This value will be passed to checker by the library). output - bool, True if validator constraint is satisfied. If constraint is not satisfied, it should either return False or raise flags.ValidationError(desired\_error\_message). message: str, error text to be shown to the user if checker returns False. If checker raises flags.ValidationError, message from the raised error will be shown. flag\_values: flags.FlagValues, optional FlagValues instance to validate against. Raises: AttributeError: Raised when flag\_name is not registered as a valid flag name.
| programming_docs |
tensorflow tf.compat.v1.flags.declare_key_flag tf.compat.v1.flags.declare\_key\_flag
=====================================
Declares one flag as key to the current module.
```
tf.compat.v1.flags.declare_key_flag(
flag_name, flag_values=_flagvalues.FLAGS
)
```
Key flags are flags that are deemed really important for a module. They are important when listing help messages; e.g., if the --helpshort command-line flag is used, then only the key flags of the main module are listed (instead of all flags, as in the case of --helpfull).
#### Sample usage:
flags.declare\_key\_flag('flag\_1')
| Args |
| `flag_name` | str, the name of an already declared flag. (Redeclaring flags as key, including flags implicitly key because they were declared in this module, is a no-op.) |
| `flag_values` | FlagValues, the FlagValues instance in which the flag will be declared as a key flag. This should almost never need to be overridden. |
| Raises |
| `ValueError` | Raised if flag\_name not defined as a Python flag. |
tensorflow tf.compat.v1.flags.WhitespaceSeparatedListParser tf.compat.v1.flags.WhitespaceSeparatedListParser
================================================
Parser for a whitespace-separated list of strings.
Inherits From: [`BaseListParser`](baselistparser), [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.WhitespaceSeparatedListParser(
comma_compat=False
)
```
| Args |
| `comma_compat` | bool, whether to support comma as an additional separator. If False then only whitespace is supported. This is intended only for backwards compatibility with flags that used to be comma-separated. |
Methods
-------
### `flag_type`
```
flag_type()
```
See base class.
### `parse`
```
parse(
argument
)
```
Parses argument as whitespace-separated list of strings.
It also parses argument as comma-separated list of strings if requested.
| Args |
| `argument` | string argument passed in the commandline. |
| Returns |
| [str], the parsed flag value. |
| Class Variables |
| syntactic\_help | `''` |
tensorflow tf.compat.v1.flags.DEFINE_flag tf.compat.v1.flags.DEFINE\_flag
===============================
Registers a 'Flag' object with a 'FlagValues' object.
```
tf.compat.v1.flags.DEFINE_flag(
flag, flag_values=_flagvalues.FLAGS, module_name=None, required=False
)
```
By default, the global FLAGS 'FlagValue' object is used.
Typical users will use one of the more specialized DEFINE\_xxx functions, such as DEFINE\_string or DEFINE\_integer. But developers who need to create Flag objects themselves should use this function to register their flags.
| Args |
| `flag` | Flag, a flag that is key to the module. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `module_name` | str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.flags.adopt_module_key_flags tf.compat.v1.flags.adopt\_module\_key\_flags
============================================
Declares that all flags key to a module are key to the current module.
```
tf.compat.v1.flags.adopt_module_key_flags(
module, flag_values=_flagvalues.FLAGS
)
```
| Args |
| `module` | module, the module object from which all key flags will be declared as key flags to the current module. |
| `flag_values` | FlagValues, the FlagValues instance in which the flags will be declared as key flags. This should almost never need to be overridden. |
| Raises |
| `Error` | Raised when given an argument that is a module name (a string), instead of a module object. |
tensorflow tf.compat.v1.flags.EnumClassListSerializer tf.compat.v1.flags.EnumClassListSerializer
==========================================
A serializer for MultiEnumClass flags.
Inherits From: [`ListSerializer`](listserializer), [`ArgumentSerializer`](argumentserializer)
```
tf.compat.v1.flags.EnumClassListSerializer(
list_sep, **kwargs
)
```
This serializer simply joins the output of `EnumClassSerializer` using a provided seperator.
| Args |
| `list_sep` | String to be used as a separator when serializing |
| `**kwargs` | Keyword arguments to the `EnumClassSerializer` used to serialize individual values. |
Methods
-------
### `serialize`
```
serialize(
value
)
```
See base class.
tensorflow tf.compat.v1.flags.FlagNameConflictsWithMethodError tf.compat.v1.flags.FlagNameConflictsWithMethodError
===================================================
Raised when a flag name conflicts with FlagValues methods.
Inherits From: [`Error`](error)
tensorflow tf.compat.v1.flags.IntegerParser tf.compat.v1.flags.IntegerParser
================================
Parser of an integer value.
Inherits From: [`ArgumentParser`](argumentparser)
```
tf.compat.v1.flags.IntegerParser(
lower_bound=None, upper_bound=None
)
```
Parsed value may be bounded to a given upper and lower bound.
Methods
-------
### `convert`
```
convert(
argument
)
```
Returns the int value of argument.
### `flag_type`
```
flag_type()
```
See base class.
### `is_outside_bounds`
```
is_outside_bounds(
val
)
```
Returns whether the value is outside the bounds or not.
### `parse`
```
parse(
argument
)
```
See base class.
| Class Variables |
| number\_article | `'an'` |
| number\_name | `'integer'` |
| syntactic\_help | `'an integer'` |
tensorflow tf.compat.v1.flags.DEFINE tf.compat.v1.flags.DEFINE
=========================
Registers a generic Flag object.
```
tf.compat.v1.flags.DEFINE(
parser,
name,
default,
help,
flag_values=_flagvalues.FLAGS,
serializer=None,
module_name=None,
required=False,
**args
)
```
>
> **Note:** in the docstrings of all DEFINE\* functions, "registers" is short for "creates a new flag and registers it".
>
Auxiliary function: clients should use the specialized DEFINE\_ function instead.
| Args |
| `parser` | ArgumentParser, used to parse the flag arguments. |
| `name` | str, the flag name. |
| `default` | The default value of the flag. |
| `help` | str, the help message. |
| `flag_values` | FlagValues, the FlagValues instance with which the flag will be registered. This should almost never need to be overridden. |
| `serializer` | ArgumentSerializer, the flag serializer instance. |
| `module_name` | str, the name of the Python module declaring this flag. If not provided, it will be computed using the stack trace of this call. |
| `required` | bool, is this a required flag. This must be used as a keyword argument. |
| `**args` | dict, the extra keyword args that are passed to Flag **init**. |
| Returns |
| a handle to defined flag. |
tensorflow tf.compat.v1.saved_model.load tf.compat.v1.saved\_model.load
==============================
Loads the model from a SavedModel as specified by tags. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.loader.load`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/load)
```
tf.compat.v1.saved_model.load(
sess, tags, export_dir, import_scope=None, **saver_kwargs
)
```
Migrate to TF2
--------------
[`tf.compat.v1.saved_model.load`](load) or [`tf.compat.v1.saved_model.loader.load`](load) is not compatible with eager execution. Please use [`tf.saved_model.load`](../../../saved_model/load) instead to load your model. You can refer to the [SavedModel guide](https://www.tensorflow.org/guide/saved_model) for more information as well as "Importing SavedModels from TensorFlow 1.x" in the [`tf.saved_model.load`](https://www.tensorflow.org/api_docs/python/tf/saved_model/load) docstring.
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `sess` | Not supported | - |
| `tags` | `tags` | - |
| `export_dir` | `export_dir` | - |
| `import_scope` | Not supported | Name scopes are not needed. By default, variables are associated with the loaded object and function names are deduped. |
| `saver_kwargs` | Not supported | - |
#### Before & After Usage Example
Before:
```
with tf.compat.v1.Session(graph=tf.Graph()) as sess:
tf.compat.v1.saved_model.loader.load(sess, ["foo-tag"], export_dir)
```
After:
```
model = tf.saved_model.load(export_dir, tags=["foo-tag"])
```
Description
-----------
| Args |
| `sess` | The TensorFlow session to restore the variables. |
| `tags` | Set of string tags to identify the required MetaGraphDef. These should correspond to the tags used when saving the variables using the SavedModel `save()` API. |
| `export_dir` | Directory in which the SavedModel protocol buffer and variables to be loaded are located. |
| `import_scope` | Optional `string` -- if specified, prepend this string followed by '/' to all loaded tensor names. This scope is applied to tensor instances loaded into the passed session, but it is *not* written through to the static `MetaGraphDef` protocol buffer that is returned. |
| `**saver_kwargs` | Optional keyword arguments passed through to Saver. |
| Returns |
| The `MetaGraphDef` protocol buffer loaded in the provided session. This can be used to further extract signature-defs, collection-defs, etc. |
| Raises |
| `RuntimeError` | MetaGraphDef associated with the tags cannot be found. |
tensorflow Module: tf.compat.v1.saved_model.builder Module: tf.compat.v1.saved\_model.builder
=========================================
SavedModel builder.
Builds a SavedModel that can be saved to storage, is language neutral, and enables systems to produce, consume, or transform TensorFlow Models.
Classes
-------
[`class SavedModelBuilder`](builder): Builds the `SavedModel` protocol buffer and saves variables and assets.
tensorflow tf.compat.v1.saved_model.simple_save tf.compat.v1.saved\_model.simple\_save
======================================
Convenience function to build a SavedModel suitable for serving. (deprecated)
```
tf.compat.v1.saved_model.simple_save(
session, export_dir, inputs, outputs, legacy_init_op=None
)
```
In many common cases, saving models for serving will be as simple as:
```
simple_save(session,
export_dir,
inputs={"x": x, "y": y},
outputs={"z": z})
```
Although in many cases it's not necessary to understand all of the many ways to configure a SavedModel, this method has a few practical implications:
* It will be treated as a graph for inference / serving (i.e. uses the tag [`saved_model.SERVING`](https://www.tensorflow.org/api_docs/python/tf/saved_model#SERVING))
* The SavedModel will load in TensorFlow Serving and supports the [Predict API](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/predict.proto). To use the Classify, Regress, or MultiInference APIs, please use either [tf.Estimator](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator) or the lower level [SavedModel APIs](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md).
* Some TensorFlow ops depend on information on disk or other information called "assets". These are generally handled automatically by adding the assets to the `GraphKeys.ASSET_FILEPATHS` collection. Only assets in that collection are exported; if you need more custom behavior, you'll need to use the [SavedModelBuilder](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/builder.py).
More information about SavedModel and signatures can be found here: <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md>
| Args |
| `session` | The TensorFlow session from which to save the meta graph and variables. |
| `export_dir` | The path to which the SavedModel will be stored. |
| `inputs` | dict mapping string input names to tensors. These are added to the SignatureDef as the inputs. |
| `outputs` | dict mapping string output names to tensors. These are added to the SignatureDef as the outputs. |
| `legacy_init_op` | Legacy support for op or group of ops to execute after the restore op upon a load. |
tensorflow tf.compat.v1.saved_model.get_tensor_from_tensor_info tf.compat.v1.saved\_model.get\_tensor\_from\_tensor\_info
=========================================================
Returns the Tensor or CompositeTensor described by a TensorInfo proto. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.utils.get_tensor_from_tensor_info`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/get_tensor_from_tensor_info)
```
tf.compat.v1.saved_model.get_tensor_from_tensor_info(
tensor_info, graph=None, import_scope=None
)
```
| Args |
| `tensor_info` | A TensorInfo proto describing a Tensor or SparseTensor or CompositeTensor. |
| `graph` | The tf.Graph in which tensors are looked up. If None, the current default graph is used. |
| `import_scope` | If not None, names in `tensor_info` are prefixed with this string before lookup. |
| Returns |
| The Tensor or SparseTensor or CompositeTensor in `graph` described by `tensor_info`. |
| Raises |
| `KeyError` | If `tensor_info` does not correspond to a tensor in `graph`. |
| `ValueError` | If `tensor_info` is malformed. |
tensorflow Module: tf.compat.v1.saved_model.tag_constants Module: tf.compat.v1.saved\_model.tag\_constants
================================================
Common tags used for graphs in SavedModel.
| Other Members |
| GPU | `'gpu'` |
| SERVING | `'serve'` |
| TPU | `'tpu'` |
| TRAINING | `'train'` |
tensorflow Module: tf.compat.v1.saved_model.loader Module: tf.compat.v1.saved\_model.loader
========================================
Loader functionality for SavedModel with hermetic, language-neutral exports.
Load and restore capability for a SavedModel, which may include multiple meta graph defs. Each SavedModel is associated with a single checkpoint. Each meta graph def is saved with one or more tags, which are used to identify the exact meta graph def to load.
The `load` operation requires the session in which to restore the graph definition and variables, the tags used to identify the meta graph def to load and the location of the SavedModel.
Upon a load, the subset of variables and assets supplied as part of the specific meta graph def, will be restored into the supplied session. The values of the variables though will correspond to the saved values from the first meta graph added to the SavedModel using `add_meta_graph_and_variables(...)` in `builder.py`.
#### Typical usage:
```
...
builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(export_dir)
with tf.compat.v1.Session(graph=tf.Graph()) as sess:
...
builder.add_meta_graph_and_variables(sess,
["foo-tag"],
signature_def_map=foo_signatures,
assets_collection=foo_assets)
...
with tf.compat.v1.Session(graph=tf.Graph()) as sess:
...
builder.add_meta_graph(["bar-tag", "baz-tag"],
assets_collection=bar_baz_assets)
...
builder.save()
...
with tf.compat.v1.Session(graph=tf.Graph()) as sess:
tf.compat.v1.saved_model.loader.load(sess, ["foo-tag"], export_dir)
...
```
Functions
---------
[`load(...)`](load): Loads the model from a SavedModel as specified by tags. (deprecated)
[`maybe_saved_model_directory(...)`](contains_saved_model): Checks whether the provided export directory could contain a SavedModel.
tensorflow Module: tf.compat.v1.saved_model.utils Module: tf.compat.v1.saved\_model.utils
=======================================
SavedModel utility functions.
Utility functions to assist with setup and construction of the SavedModel proto.
Functions
---------
[`build_tensor_info(...)`](build_tensor_info): Utility function to build TensorInfo proto from a Tensor. (deprecated)
[`get_tensor_from_tensor_info(...)`](get_tensor_from_tensor_info): Returns the Tensor or CompositeTensor described by a TensorInfo proto. (deprecated)
tensorflow tf.compat.v1.saved_model.main_op_with_restore tf.compat.v1.saved\_model.main\_op\_with\_restore
=================================================
Returns a main op to init variables, tables and restore the graph. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.main_op.main_op_with_restore`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/main_op_with_restore)
```
tf.compat.v1.saved_model.main_op_with_restore(
restore_op_name
)
```
Returns the main op including the group of ops that initializes all variables, initialize local variables, initialize all tables and the restore op name.
| Args |
| `restore_op_name` | Name of the op to use to restore the graph. |
| Returns |
| The set of ops to be run as part of the main op upon the load operation. |
tensorflow tf.compat.v1.saved_model.regression_signature_def tf.compat.v1.saved\_model.regression\_signature\_def
====================================================
Creates regression signature from given examples and predictions.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.signature_def_utils.regression_signature_def`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/regression_signature_def)
```
tf.compat.v1.saved_model.regression_signature_def(
examples, predictions
)
```
This function produces signatures intended for use with the TensorFlow Serving Regress API (tensorflow\_serving/apis/prediction\_service.proto), and so constrains the input and output types to those allowed by TensorFlow Serving.
| Args |
| `examples` | A string `Tensor`, expected to accept serialized tf.Examples. |
| `predictions` | A float `Tensor`. |
| Returns |
| A regression-flavored signature\_def. |
| Raises |
| `ValueError` | If examples is `None`. |
tensorflow tf.compat.v1.saved_model.build_signature_def tf.compat.v1.saved\_model.build\_signature\_def
===============================================
Utility function to build a SignatureDef protocol buffer.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.signature_def_utils.build_signature_def`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/build_signature_def)
```
tf.compat.v1.saved_model.build_signature_def(
inputs=None, outputs=None, method_name=None
)
```
| Args |
| `inputs` | Inputs of the SignatureDef defined as a proto map of string to tensor info. |
| `outputs` | Outputs of the SignatureDef defined as a proto map of string to tensor info. |
| `method_name` | Method name of the SignatureDef as a string. |
| Returns |
| A SignatureDef protocol buffer constructed based on the supplied arguments. |
tensorflow Module: tf.compat.v1.saved_model.main_op Module: tf.compat.v1.saved\_model.main\_op
==========================================
SavedModel main op.
Builds a main op that defines the sequence of ops to be run as part of the SavedModel load/restore operations.
Functions
---------
[`main_op(...)`](main_op/main_op): Returns a main op to init variables and tables. (deprecated)
[`main_op_with_restore(...)`](main_op_with_restore): Returns a main op to init variables, tables and restore the graph. (deprecated)
| programming_docs |
tensorflow tf.compat.v1.saved_model.build_tensor_info tf.compat.v1.saved\_model.build\_tensor\_info
=============================================
Utility function to build TensorInfo proto from a Tensor. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.utils.build_tensor_info`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/build_tensor_info)
```
tf.compat.v1.saved_model.build_tensor_info(
tensor
)
```
Migrate to TF2
--------------
This API is not compatible with eager execution as `tensor` needs to be a graph tensor, and there is no replacement for it in TensorFlow 2.x. To start writing programs using TensorFlow 2.x, please refer to the [Effective TensorFlow 2](https://www.tensorflow.org/guide/effective_tf2) guide.
Description
-----------
| Args |
| `tensor` | Tensor or SparseTensor whose name, dtype and shape are used to build the TensorInfo. For SparseTensors, the names of the three constituent Tensors are used. |
| Returns |
| A TensorInfo protocol buffer constructed based on the supplied argument. |
| Raises |
| `RuntimeError` | If eager execution is enabled. |
tensorflow tf.compat.v1.saved_model.classification_signature_def tf.compat.v1.saved\_model.classification\_signature\_def
========================================================
Creates classification signature from given examples and predictions.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.signature_def_utils.classification_signature_def`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/classification_signature_def)
```
tf.compat.v1.saved_model.classification_signature_def(
examples, classes, scores
)
```
This function produces signatures intended for use with the TensorFlow Serving Classify API (tensorflow\_serving/apis/prediction\_service.proto), and so constrains the input and output types to those allowed by TensorFlow Serving.
| Args |
| `examples` | A string `Tensor`, expected to accept serialized tf.Examples. |
| `classes` | A string `Tensor`. Note that the ClassificationResponse message requires that class labels are strings, not integers or anything else. |
| `scores` | a float `Tensor`. |
| Returns |
| A classification-flavored signature\_def. |
| Raises |
| `ValueError` | If examples is `None`. |
tensorflow Module: tf.compat.v1.saved_model.experimental Module: tf.compat.v1.saved\_model.experimental
==============================================
Public API for tf.saved\_model.experimental namespace.
Classes
-------
[`class TrackableResource`](../../../saved_model/experimental/trackableresource): Holds a Tensor which a tf.function can capture.
[`class VariablePolicy`](../../../saved_model/experimental/variablepolicy): Enum defining options for variable handling when saving.
Functions
---------
[`save(...)`](../../../saved_model/save): Exports a [tf.Module](https://www.tensorflow.org/api_docs/python/tf/Module) (and subclasses) `obj` to [SavedModel format](https://www.tensorflow.org/guide/saved_model#the_savedmodel_format_on_disk).
tensorflow tf.compat.v1.saved_model.is_valid_signature tf.compat.v1.saved\_model.is\_valid\_signature
==============================================
Determine whether a SignatureDef can be served by TensorFlow Serving.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.signature_def_utils.is_valid_signature`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/is_valid_signature)
```
tf.compat.v1.saved_model.is_valid_signature(
signature_def
)
```
tensorflow Module: tf.compat.v1.saved_model.signature_constants Module: tf.compat.v1.saved\_model.signature\_constants
======================================================
Signature constants for SavedModel save and restore operations.
| Other Members |
| CLASSIFY\_INPUTS | `'inputs'` |
| CLASSIFY\_METHOD\_NAME | `'tensorflow/serving/classify'` |
| CLASSIFY\_OUTPUT\_CLASSES | `'classes'` |
| CLASSIFY\_OUTPUT\_SCORES | `'scores'` |
| DEFAULT\_SERVING\_SIGNATURE\_DEF\_KEY | `'serving_default'` |
| PREDICT\_INPUTS | `'inputs'` |
| PREDICT\_METHOD\_NAME | `'tensorflow/serving/predict'` |
| PREDICT\_OUTPUTS | `'outputs'` |
| REGRESS\_INPUTS | `'inputs'` |
| REGRESS\_METHOD\_NAME | `'tensorflow/serving/regress'` |
| REGRESS\_OUTPUTS | `'outputs'` |
tensorflow tf.compat.v1.saved_model.contains_saved_model tf.compat.v1.saved\_model.contains\_saved\_model
================================================
Checks whether the provided export directory could contain a SavedModel.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.loader.maybe_saved_model_directory`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/contains_saved_model), [`tf.compat.v1.saved_model.maybe_saved_model_directory`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/contains_saved_model)
```
tf.compat.v1.saved_model.contains_saved_model(
export_dir
)
```
Note that the method does not load any data by itself. If the method returns `false`, the export directory definitely does not contain a SavedModel. If the method returns `true`, the export directory may contain a SavedModel but provides no guarantee that it can be loaded.
| Args |
| `export_dir` | Absolute string path to possible export location. For example, '/my/foo/model'. |
| Returns |
| True if the export directory contains SavedModel files, False otherwise. |
tensorflow Module: tf.compat.v1.saved_model.signature_def_utils Module: tf.compat.v1.saved\_model.signature\_def\_utils
=======================================================
SignatureDef utility functions.
Utility functions for building and inspecting SignatureDef protos.
Classes
-------
[`class MethodNameUpdater`](signature_def_utils/methodnameupdater): Updates the method name(s) of the SavedModel stored in the given path.
Functions
---------
[`build_signature_def(...)`](build_signature_def): Utility function to build a SignatureDef protocol buffer.
[`classification_signature_def(...)`](classification_signature_def): Creates classification signature from given examples and predictions.
[`is_valid_signature(...)`](is_valid_signature): Determine whether a SignatureDef can be served by TensorFlow Serving.
[`predict_signature_def(...)`](predict_signature_def): Creates prediction signature from given inputs and outputs.
[`regression_signature_def(...)`](regression_signature_def): Creates regression signature from given examples and predictions.
tensorflow Module: tf.compat.v1.saved_model.constants Module: tf.compat.v1.saved\_model.constants
===========================================
Constants for SavedModel save and restore operations.
The source of truth for these constants is in tensorflow/cc/saved\_model/constants.h.
| Other Members |
| ASSETS\_DIRECTORY | `'assets'` |
| ASSETS\_KEY | `'saved_model_assets'` |
| DEBUG\_DIRECTORY | `'debug'` |
| DEBUG\_INFO\_FILENAME\_PB | `'saved_model_debug_info.pb'` |
| LEGACY\_INIT\_OP\_KEY | `'legacy_init_op'` |
| MAIN\_OP\_KEY | `'saved_model_main_op'` |
| SAVED\_MODEL\_FILENAME\_PB | `'saved_model.pb'` |
| SAVED\_MODEL\_FILENAME\_PBTXT | `'saved_model.pbtxt'` |
| SAVED\_MODEL\_SCHEMA\_VERSION | `1` |
| VARIABLES\_DIRECTORY | `'variables'` |
| VARIABLES\_FILENAME | `'variables'` |
tensorflow tf.compat.v1.saved_model.predict_signature_def tf.compat.v1.saved\_model.predict\_signature\_def
=================================================
Creates prediction signature from given inputs and outputs.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.saved_model.signature_def_utils.predict_signature_def`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/saved_model/predict_signature_def)
```
tf.compat.v1.saved_model.predict_signature_def(
inputs, outputs
)
```
This function produces signatures intended for use with the TensorFlow Serving Predict API (tensorflow\_serving/apis/prediction\_service.proto). This API imposes no constraints on the input and output types.
| Args |
| `inputs` | dict of string to `Tensor`. |
| `outputs` | dict of string to `Tensor`. |
| Returns |
| A prediction-flavored signature\_def. |
| Raises |
| `ValueError` | If inputs or outputs is `None`. |
tensorflow tf.compat.v1.saved_model.main_op.main_op tf.compat.v1.saved\_model.main\_op.main\_op
===========================================
Returns a main op to init variables and tables. (deprecated)
```
tf.compat.v1.saved_model.main_op.main_op()
```
Returns the main op including the group of ops that initializes all variables, initializes local variables and initialize all tables.
| Returns |
| The set of ops to be run as part of the main op upon the load operation. |
tensorflow tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater tf.compat.v1.saved\_model.signature\_def\_utils.MethodNameUpdater
=================================================================
Updates the method name(s) of the SavedModel stored in the given path.
```
tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater(
export_dir
)
```
The `MethodNameUpdater` class provides the functionality to update the method name field in the signature\_defs of the given SavedModel. For example, it can be used to replace the `predict` `method_name` to `regress`.
Typical usages of the `MethodNameUpdater`
```
...
updater = tf.compat.v1.saved_model.signature_def_utils.MethodNameUpdater(
export_dir)
# Update all signature_defs with key "foo" in all meta graph defs.
updater.replace_method_name(signature_key="foo", method_name="regress")
# Update a single signature_def with key "bar" in the meta graph def with
# tags ["serve"]
updater.replace_method_name(signature_key="bar", method_name="classify",
tags="serve")
updater.save(new_export_dir)
```
>
> **Note:** This function will only be available through the v1 compatibility library as tf.compat.v1.saved\_model.builder.MethodNameUpdater.
>
| Args |
| `export_dir` | Directory containing the SavedModel files. |
| Raises |
| `IOError` | If the saved model file does not exist, or cannot be successfully parsed. |
Methods
-------
### `replace_method_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/saved_model/method_name_updater.py#L69-L111)
```
replace_method_name(
signature_key, method_name, tags=None
)
```
Replaces the method\_name in the specified signature\_def.
This will match and replace multiple sig defs iff tags is None (i.e when multiple `MetaGraph`s have a signature\_def with the same key). If tags is not None, this will only replace a single signature\_def in the `MetaGraph` with matching tags.
| Args |
| `signature_key` | Key of the signature\_def to be updated. |
| `method_name` | new method\_name to replace the existing one. |
| `tags` | A tag or sequence of tags identifying the `MetaGraph` to update. If None, all meta graphs will be updated. |
| Raises |
| `ValueError` | if signature\_key or method\_name are not defined or if no metagraphs were found with the associated tags or if no meta graph has a signature\_def that matches signature\_key. |
### `save`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/saved_model/method_name_updater.py#L113-L143)
```
save(
new_export_dir=None
)
```
Saves the updated `SavedModel`.
| Args |
| `new_export_dir` | Path where the updated `SavedModel` will be saved. If None, the input `SavedModel` will be overriden with the updates. |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If there are errors during the file save operation. |
tensorflow Module: tf.compat.v1.linalg.experimental Module: tf.compat.v1.linalg.experimental
========================================
Public API for tf.linalg.experimental namespace.
Functions
---------
[`conjugate_gradient(...)`](../../../linalg/experimental/conjugate_gradient): Conjugate gradient solver.
tensorflow tf.compat.v1.app.run tf.compat.v1.app.run
====================
Runs the program with an optional 'main' function and 'argv' list.
```
tf.compat.v1.app.run(
main=None, argv=None
)
```
tensorflow tf.compat.v1.layers.batch_normalization tf.compat.v1.layers.batch\_normalization
========================================
Functional interface for the batch normalization layer from\_config(Ioffe et al., 2015).
```
tf.compat.v1.layers.batch_normalization(
inputs,
axis=-1,
momentum=0.99,
epsilon=0.001,
center=True,
scale=True,
beta_initializer=tf.compat.v1.zeros_initializer(),
gamma_initializer=tf.compat.v1.ones_initializer(),
moving_mean_initializer=tf.compat.v1.zeros_initializer(),
moving_variance_initializer=tf.compat.v1.ones_initializer(),
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
training=False,
trainable=True,
name=None,
reuse=None,
renorm=False,
renorm_clipping=None,
renorm_momentum=0.99,
fused=None,
virtual_batch_size=None,
adjustment=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.BatchNormalization`](../../../keras/layers/batchnormalization).
The batch updating pattern with [`tf.control_dependencies(tf.GraphKeys.UPDATE_OPS)`](../../../control_dependencies) should not be used in native TF2. Consult the [`tf.keras.layers.BatchNormalization`](../../../keras/layers/batchnormalization) documentation for further information.
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
x_norm = tf.compat.v1.layers.batch_normalization(x)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input(shape=(28, 28, 1),)
y = tf.keras.layers.BatchNormalization()(x)
model = tf.keras.Model(x, y)
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `name` | `name` | Layer base class |
| `trainable` | `trainable` | Layer base class |
| `axis` | `axis` | - |
| `momentum` | `momentum` | - |
| `epsilon` | `epsilon` | - |
| `center` | `center` | - |
| `scale` | `scale` | - |
| `beta_initializer` | `beta_initializer` | - |
| `gamma_initializer` | `gamma_initializer` | - |
| `moving_mean_initializer` | `moving_mean_initializer` | - |
| `beta_regularizer` | `beta\_regularizer' | - |
| `gamma_regularizer` | `gamma\_regularizer' | - |
| `beta_constraint` | `beta\_constraint' | - |
| `gamma_constraint` | `gamma\_constraint' | - |
| `renorm` | Not supported | - |
| `renorm_clipping` | Not supported | - |
| `renorm_momentum` | Not supported | - |
| `fused` | Not supported | - |
| `virtual_batch_size` | Not supported | - |
| `adjustment` | Not supported | - |
Description
-----------
>
> **Note:** when training, the moving\_mean and moving\_variance need to be updated. By default the update ops are placed in `tf.GraphKeys.UPDATE_OPS`, so they need to be executed alongside the `train_op`. Also, be sure to add any batch\_normalization ops before getting the update\_ops collection. Otherwise, update\_ops will be empty, and training/inference will not work properly. For example:
>
```
x_norm = tf.compat.v1.layers.batch_normalization(x, training=training)
# ...
update_ops = tf.compat.v1.get_collection(tf.GraphKeys.UPDATE_OPS)
train_op = optimizer.minimize(loss)
train_op = tf.group([train_op, update_ops])
```
| Args |
| `inputs` | Tensor input. |
| `axis` | An `int`, the axis that should be normalized (typically the features axis). For instance, after a `Convolution2D` layer with `data_format="channels_first"`, set `axis=1` in `BatchNormalization`. |
| `momentum` | Momentum for the moving average. |
| `epsilon` | Small float added to variance to avoid dividing by zero. |
| `center` | If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. |
| `scale` | If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. [`nn.relu`](https://www.tensorflow.org/api_docs/python/tf/nn/relu)), this can be disabled since the scaling can be done by the next layer. |
| `beta_initializer` | Initializer for the beta weight. |
| `gamma_initializer` | Initializer for the gamma weight. |
| `moving_mean_initializer` | Initializer for the moving mean. |
| `moving_variance_initializer` | Initializer for the moving variance. |
| `beta_regularizer` | Optional regularizer for the beta weight. |
| `gamma_regularizer` | Optional regularizer for the gamma weight. |
| `beta_constraint` | An optional projection function to be applied to the `beta` weight after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `gamma_constraint` | An optional projection function to be applied to the `gamma` weight after being updated by an `Optimizer`. |
| `training` | Either a Python boolean, or a TensorFlow boolean scalar tensor (e.g. a placeholder). Whether to return the output in training mode (normalized with statistics of the current batch) or in inference mode (normalized with moving statistics). **NOTE**: make sure to set this parameter correctly, or else your training/inference will not work properly. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). |
| `name` | String, the name of the layer. |
| `reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
| `renorm` | Whether to use Batch Renormalization (Ioffe, 2017). This adds extra variables during training. The inference is the same for either value of this parameter. |
| `renorm_clipping` | A dictionary that may map keys 'rmax', 'rmin', 'dmax' to scalar `Tensors` used to clip the renorm correction. The correction `(r, d)` is used as `corrected_value = normalized_value * r + d`, with `r` clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin, dmax are set to inf, 0, inf, respectively. |
| `renorm_momentum` | Momentum used to update the moving means and standard deviations with renorm. Unlike `momentum`, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). Note that `momentum` is still applied to get the means and variances for inference. |
| `fused` | if `None` or `True`, use a faster, fused implementation if possible. If `False`, use the system recommended implementation. |
| `virtual_batch_size` | An `int`. By default, `virtual_batch_size` is `None`, which means batch normalization is performed across the whole batch. When `virtual_batch_size` is not `None`, instead perform "Ghost Batch Normalization", which creates virtual sub-batches which are each normalized separately (with shared gamma, beta, and moving statistics). Must divide the actual batch size during execution. |
| `adjustment` | A function taking the `Tensor` containing the (dynamic) shape of the input tensor and returning a pair (scale, bias) to apply to the normalized values (before gamma and beta), only during training. For example, if axis==-1, `adjustment = lambda shape: ( tf.random.uniform(shape[-1:], 0.93, 1.07), tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized value by up to 7% up or down, then shift the result by up to 0.1 (with independent scaling and bias for each feature but shared across all examples), and finally apply gamma and/or beta. If `None`, no adjustment is applied. Cannot be specified if virtual\_batch\_size is specified. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
#### References:
Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) Batch Renormalization - Towards Reducing Minibatch Dependence in Batch-Normalized Models: [Ioffe, 2017](http://papers.nips.cc/paper/6790-batch-renormalization-towards-reducing-minibatch-dependence-in-batch-normalized-models) ([pdf](http://papers.nips.cc/paper/6790-batch-renormalization-towards-reducing-minibatch-dependence-in-batch-normalized-models.pdf))
| programming_docs |
tensorflow tf.compat.v1.layers.AveragePooling3D tf.compat.v1.layers.AveragePooling3D
====================================
Average pooling layer for 3D inputs (e.g. volumes).
Inherits From: [`AveragePooling3D`](../../../keras/layers/averagepooling3d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.AveragePooling3D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling3D`](../../../keras/layers/averagepooling3d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.AveragePooling3D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.AveragePooling3D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of 3 integers: (pool\_depth, pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.AveragePooling1D tf.compat.v1.layers.AveragePooling1D
====================================
Average Pooling layer for 1D inputs.
Inherits From: [`AveragePooling1D`](../../../keras/layers/averagepooling1d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.AveragePooling1D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling1D`](../../../keras/layers/averagepooling1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.AveragePooling1D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.AveragePooling1D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of a single integer, representing the size of the pooling window. |
| `strides` | An integer or tuple/list of a single integer, specifying the strides of the pooling operation. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Conv2DTranspose tf.compat.v1.layers.Conv2DTranspose
===================================
Transposed 2D convolution layer (sometimes called 2D Deconvolution).
Inherits From: [`Conv2DTranspose`](../../../keras/layers/conv2dtranspose), [`Conv2D`](../../../keras/layers/conv2d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Conv2DTranspose(
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv2DTranspose`](../../../keras/layers/conv2dtranspose).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.Conv2DTranspose(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.Conv2DTranspose(filters=3, kernels_size=3)
```
Description
-----------
The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A tuple or list of 2 positive integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | A tuple or list of 2 positive integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | one of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Conv2D tf.compat.v1.layers.Conv2D
==========================
2D convolution layer (e.g. spatial convolution over images).
Inherits From: [`Conv2D`](../../../keras/layers/conv2d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Conv2D(
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
dilation_rate=(1, 1),
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv2D`](../../../keras/layers/conv2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.Conv2D(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.Conv2D(filters=3, kernels_size=3)
```
Description
-----------
This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | An integer or tuple/list of 2 integers, specifying the height and width of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 2 integers, specifying the strides of the convolution along the height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `dilation_rate` | An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.conv3d_transpose tf.compat.v1.layers.conv3d\_transpose
=====================================
Functional interface for transposed 3D convolution layer.
```
tf.compat.v1.layers.conv3d_transpose(
inputs,
filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv3DTranspose`](../../../keras/layers/conv3dtranspose).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.conv3d_transpose(x, filters=3, kernel_size=3)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.Conv3DTranspose(filters=3, kernels_size=3)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | Input tensor. |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A tuple or list of 3 positive integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | A tuple or list of 3 positive integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | one of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| `reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.layers.MaxPooling3D tf.compat.v1.layers.MaxPooling3D
================================
Max pooling layer for 3D inputs (e.g. volumes).
Inherits From: [`MaxPool3D`](../../../keras/layers/maxpool3d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.MaxPooling3D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling3D`](../../../keras/layers/maxpool3d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.MaxPooling3D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.MaxPooling3D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of 3 integers: (pool\_depth, pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Conv3DTranspose tf.compat.v1.layers.Conv3DTranspose
===================================
Transposed 3D convolution layer (sometimes called 3D Deconvolution).
Inherits From: [`Conv3DTranspose`](../../../keras/layers/conv3dtranspose), [`Conv3D`](../../../keras/layers/conv3d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Conv3DTranspose(
filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv3DTranspose`](../../../keras/layers/conv3dtranspose).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.Conv3DTranspose(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.Conv3DTranspose(filters=3, kernels_size=3)
```
Description
-----------
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the convolution along the depth, height and width. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `activation` | Activation function. Set it to `None` to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If `None`, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.MaxPooling1D tf.compat.v1.layers.MaxPooling1D
================================
Max Pooling layer for 1D inputs.
Inherits From: [`MaxPool1D`](../../../keras/layers/maxpool1d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.MaxPooling1D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling1D`](../../../keras/layers/maxpool1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.MaxPooling1D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.MaxPooling1D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of a single integer, representing the size of the pooling window. |
| `strides` | An integer or tuple/list of a single integer, specifying the strides of the pooling operation. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Conv3D tf.compat.v1.layers.Conv3D
==========================
3D convolution layer (e.g. spatial convolution over volumes).
Inherits From: [`Conv3D`](../../../keras/layers/conv3d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Conv3D(
filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format='channels_last',
dilation_rate=(1, 1, 1),
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv3D`](../../../keras/layers/conv3d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.Conv3D(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.Conv3D(filters=3, kernels_size=3)
```
Description
-----------
This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | An integer or tuple/list of 3 integers, specifying the depth, height and width of the 3D convolution window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the convolution along the depth, height and width. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `dilation_rate` | An integer or tuple/list of 3 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.BatchNormalization tf.compat.v1.layers.BatchNormalization
======================================
Batch Normalization layer from (Ioffe et al., 2015).
Inherits From: [`BatchNormalization`](../keras/layers/batchnormalization), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.BatchNormalization(
axis=-1,
momentum=0.99,
epsilon=0.001,
center=True,
scale=True,
beta_initializer=tf.compat.v1.zeros_initializer(),
gamma_initializer=tf.compat.v1.ones_initializer(),
moving_mean_initializer=tf.compat.v1.zeros_initializer(),
moving_variance_initializer=tf.compat.v1.ones_initializer(),
beta_regularizer=None,
gamma_regularizer=None,
beta_constraint=None,
gamma_constraint=None,
renorm=False,
renorm_clipping=None,
renorm_momentum=0.99,
fused=None,
trainable=True,
virtual_batch_size=None,
adjustment=None,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.BatchNormalization`](../../../keras/layers/batchnormalization).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
bn = tf.compat.v1.layers.BatchNormalization()
```
After:
```
bn = tf.keras.layers.BatchNormalization()
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `name` | `name` | Layer base class |
| `trainable` | `trainable` | Layer base class |
| `axis` | `axis` | - |
| `momentum` | `momentum` | - |
| `epsilon` | `epsilon` | - |
| `center` | `center` | - |
| `scale` | `scale` | - |
| `beta_initializer` | `beta_initializer` | - |
| `gamma_initializer` | `gamma_initializer` | - |
| `moving_mean_initializer` | `moving_mean_initializer` | - |
| `beta_regularizer` | `beta\_regularizer' | - |
| `gamma_regularizer` | `gamma\_regularizer' | - |
| `beta_constraint` | `beta\_constraint' | - |
| `gamma_constraint` | `gamma\_constraint' | - |
| `renorm` | Not supported | - |
| `renorm_clipping` | Not supported | - |
| `renorm_momentum` | Not supported | - |
| `fused` | Not supported | - |
| `virtual_batch_size` | Not supported | - |
| `adjustment` | Not supported | - |
Description
-----------
Keras APIs handle BatchNormalization updates to the moving\_mean and moving\_variance as part of their `fit()` and `evaluate()` loops. However, if a custom training loop is used with an instance of `Model`, these updates need to be explicitly included. Here's a simple example of how it can be done:
```
# model is an instance of Model that contains BatchNormalization layer.
update_ops = model.get_updates_for(None) + model.get_updates_for(features)
train_op = optimizer.minimize(loss)
train_op = tf.group([train_op, update_ops])
```
| Args |
| `axis` | An `int` or list of `int`, the axis or axes that should be normalized, typically the features axis/axes. For instance, after a `Conv2D` layer with `data_format="channels_first"`, set `axis=1`. If a list of axes is provided, each axis in `axis` will be normalized simultaneously. Default is `-1` which uses the last axis. Note: when using multi-axis batch norm, the `beta`, `gamma`, `moving_mean`, and `moving_variance` variables are the same rank as the input Tensor, with dimension size 1 in all reduced (non-axis) dimensions). |
| `momentum` | Momentum for the moving average. |
| `epsilon` | Small float added to variance to avoid dividing by zero. |
| `center` | If True, add offset of `beta` to normalized tensor. If False, `beta` is ignored. |
| `scale` | If True, multiply by `gamma`. If False, `gamma` is not used. When the next layer is linear (also e.g. [`nn.relu`](https://www.tensorflow.org/api_docs/python/tf/nn/relu)), this can be disabled since the scaling can be done by the next layer. |
| `beta_initializer` | Initializer for the beta weight. |
| `gamma_initializer` | Initializer for the gamma weight. |
| `moving_mean_initializer` | Initializer for the moving mean. |
| `moving_variance_initializer` | Initializer for the moving variance. |
| `beta_regularizer` | Optional regularizer for the beta weight. |
| `gamma_regularizer` | Optional regularizer for the gamma weight. |
| `beta_constraint` | An optional projection function to be applied to the `beta` weight after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `gamma_constraint` | An optional projection function to be applied to the `gamma` weight after being updated by an `Optimizer`. |
| `renorm` | Whether to use Batch Renormalization (Ioffe, 2017). This adds extra variables during training. The inference is the same for either value of this parameter. |
| `renorm_clipping` | A dictionary that may map keys 'rmax', 'rmin', 'dmax' to scalar `Tensors` used to clip the renorm correction. The correction `(r, d)` is used as `corrected_value = normalized_value * r + d`, with `r` clipped to [rmin, rmax], and `d` to [-dmax, dmax]. Missing rmax, rmin, dmax are set to inf, 0, inf, respectively. |
| `renorm_momentum` | Momentum used to update the moving means and standard deviations with renorm. Unlike `momentum`, this affects training and should be neither too small (which would add noise) nor too large (which would give stale estimates). Note that `momentum` is still applied to get the means and variances for inference. |
| `fused` | if `None` or `True`, use a faster, fused implementation if possible. If `False`, use the system recommended implementation. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see tf.Variable). |
| `virtual_batch_size` | An `int`. By default, `virtual_batch_size` is `None`, which means batch normalization is performed across the whole batch. When `virtual_batch_size` is not `None`, instead perform "Ghost Batch Normalization", which creates virtual sub-batches which are each normalized separately (with shared gamma, beta, and moving statistics). Must divide the actual batch size during execution. |
| `adjustment` | A function taking the `Tensor` containing the (dynamic) shape of the input tensor and returning a pair (scale, bias) to apply to the normalized values (before gamma and beta), only during training. For example, if axis==-1, `adjustment = lambda shape: ( tf.random.uniform(shape[-1:], 0.93, 1.07), tf.random.uniform(shape[-1:], -0.1, 0.1))` will scale the normalized value by up to 7% up or down, then shift the result by up to 0.1 (with independent scaling and bias for each feature but shared across all examples), and finally apply gamma and/or beta. If `None`, no adjustment is applied. Cannot be specified if virtual\_batch\_size is specified. |
| `name` | A string, the name of the layer. |
#### References:
Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf)) Batch Renormalization - Towards Reducing Minibatch Dependence in Batch-Normalized Models: [Ioffe, 2017](http://papers.nips.cc/paper/6790-batch-renormalization-towards-reducing-minibatch-dependence-in-batch-normalized-models) ([pdf](http://papers.nips.cc/paper/6790-batch-renormalization-towards-reducing-minibatch-dependence-in-batch-normalized-models.pdf))
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
| programming_docs |
tensorflow tf.compat.v1.layers.Conv1D tf.compat.v1.layers.Conv1D
==========================
1D convolution layer (e.g. temporal convolution).
Inherits From: [`Conv1D`](../../../keras/layers/conv1d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Conv1D(
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv1D`](../../../keras/layers/conv1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.Conv1D(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.Conv1D(filters=3, kernels_size=3)
```
Description
-----------
This layer creates a convolution kernel that is convolved (actually cross-correlated) with the layer input to produce a tensor of outputs. If `use_bias` is True (and a `bias_initializer` is provided), a bias vector is created and added to the outputs. Finally, if `activation` is not `None`, it is applied to the outputs as well.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | An integer or tuple/list of a single integer, specifying the length of the 1D convolution window. |
| `strides` | An integer or tuple/list of a single integer, specifying the stride length of the convolution. Specifying any stride value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `dilation_rate` | An integer or tuple/list of a single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any `strides` value != 1. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Dense tf.compat.v1.layers.Dense
=========================
Densely-connected layer class.
Inherits From: [`Dense`](../../../keras/layers/dense), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Dense(
units,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Dense`](../../../keras/layers/dense).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
dense = tf.compat.v1.layers.Dense(units=3)
```
After:
```
dense = tf.keras.layers.Dense(units=3)
```
Description
-----------
This layer implements the operation: `outputs = activation(inputs * kernel + bias)` Where `activation` is the activation function passed as the `activation` argument (if not `None`), `kernel` is a weights matrix created by the layer, and `bias` is a bias vector created by the layer (only if `use_bias` is `True`).
| Args |
| `units` | Integer or Long, dimensionality of the output space. |
| `activation` | Activation function (callable). Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | Initializer function for the weight matrix. If `None` (default), weights are initialized using the default initializer used by [`tf.compat.v1.get_variable`](../get_variable). |
| `bias_initializer` | Initializer function for the bias. |
| `kernel_regularizer` | Regularizer function for the weight matrix. |
| `bias_regularizer` | Regularizer function for the bias. |
| `activity_regularizer` | Regularizer function for the output. |
| `kernel_constraint` | An optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | An optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. |
| `_reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
#### Properties:
* **`units`**: Python integer, dimensionality of the output space.
* **`activation`**: Activation function (callable).
* **`use_bias`**: Boolean, whether the layer uses a bias.
* **`kernel_initializer`**: Initializer instance (or name) for the kernel matrix.
* **`bias_initializer`**: Initializer instance (or name) for the bias.
* **`kernel_regularizer`**: Regularizer instance for the kernel matrix (callable)
* **`bias_regularizer`**: Regularizer instance for the bias (callable).
* **`activity_regularizer`**: Regularizer instance for the output (callable)
* **`kernel_constraint`**: Constraint function for the kernel matrix.
* **`bias_constraint`**: Constraint function for the bias.
* **`kernel`**: Weight matrix (TensorFlow variable or tensor).
* **`bias`**: Bias vector, if applicable (TensorFlow variable or tensor).
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.AveragePooling2D tf.compat.v1.layers.AveragePooling2D
====================================
Average pooling layer for 2D inputs (e.g. images).
Inherits From: [`AveragePooling2D`](../../../keras/layers/averagepooling2d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.AveragePooling2D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling2D`](../../../keras/layers/averagepooling2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.AveragePooling2D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.AveragePooling2D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of 2 integers: (pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.Flatten tf.compat.v1.layers.Flatten
===========================
Flattens an input tensor while preserving the batch axis (axis 0).
Inherits From: [`Flatten`](../../../keras/layers/flatten), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Flatten(
data_format=None, **kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Flatten`](../../../keras/layers/flatten).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
flatten = tf.compat.v1.layers.Flatten()
```
After:
```
flatten = tf.keras.layers.Flatten()
```
Description
-----------
| Args |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, ..., channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, ...)`. |
#### Examples:
```
x = tf.compat.v1.placeholder(shape=(None, 4, 4), dtype='float32')
y = Flatten()(x)
# now `y` has shape `(None, 16)`
x = tf.compat.v1.placeholder(shape=(None, 3, None), dtype='float32')
y = Flatten()(x)
# now `y` has shape `(None, None)`
```
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.MaxPooling2D tf.compat.v1.layers.MaxPooling2D
================================
Max pooling layer for 2D inputs (e.g. images).
Inherits From: [`MaxPool2D`](../../../keras/layers/maxpool2d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.MaxPooling2D(
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling2D`](../../../keras/layers/maxpool2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
pooling = tf.compat.v1.layers.MaxPooling2D(pool_size=2, strides=2)
```
After:
```
pooling = tf.keras.layers.MaxPooling2D(pool_size=2, strides=2)
```
Description
-----------
| Args |
| `pool_size` | An integer or tuple/list of 2 integers: (pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
| programming_docs |
tensorflow tf.compat.v1.layers.conv2d_transpose tf.compat.v1.layers.conv2d\_transpose
=====================================
Functional interface for transposed 2D convolution layer.
```
tf.compat.v1.layers.conv2d_transpose(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Conv2DTranspose`](../../../keras/layers/conv2dtranspose).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.conv2d_transpose(x, filters=3, kernel_size=3)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.Conv2DTranspose(filters=3, kernels_size=3)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
The need for transposed convolutions generally arises from the desire to use a transformation going in the opposite direction of a normal convolution, i.e., from something that has the shape of the output of some convolution to something that has the shape of its input while maintaining a connectivity pattern that is compatible with said convolution.
| Args |
| `inputs` | Input tensor. |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A tuple or list of 2 positive integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | A tuple or list of 2 positive integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | one of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `activation` | Activation function. Set it to `None` to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `kernel_initializer` | An initializer for the convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If `None`, the default initializer will be used. |
| `kernel_regularizer` | Optional regularizer for the convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `kernel_constraint` | Optional projection function to be applied to the kernel after being updated by an `Optimizer` (e.g. used to implement norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| `reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.max_pooling1d tf.compat.v1.layers.max\_pooling1d
==================================
Max Pooling layer for 1D inputs.
```
tf.compat.v1.layers.max_pooling1d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling1D`](../../../keras/layers/maxpool1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.max_pooling1d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.MaxPooling1D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | The tensor over which to pool. Must have rank 3. |
| `pool_size` | An integer or tuple/list of a single integer, representing the size of the pooling window. |
| `strides` | An integer or tuple/list of a single integer, specifying the strides of the pooling operation. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `name` | A string, the name of the layer. |
| Returns |
| The output tensor, of rank 3. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.SeparableConv1D tf.compat.v1.layers.SeparableConv1D
===================================
Depthwise separable 1D convolution.
Inherits From: [`SeparableConv1D`](../../../keras/layers/separableconv1d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.SeparableConv1D(
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
depth_multiplier=1,
activation=None,
use_bias=True,
depthwise_initializer=None,
pointwise_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
depthwise_regularizer=None,
pointwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
pointwise_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.SeparableConv1D`](../../../keras/layers/separableconv1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.SeparableConv1D(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.SeparableConv1D(filters=3, kernels_size=3)
```
Description
-----------
This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A single integer specifying the spatial dimensions of the filters. |
| `strides` | A single integer specifying the strides of the convolution. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `dilation_rate` | A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `depth_multiplier` | The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `depthwise_initializer` | An initializer for the depthwise convolution kernel. |
| `pointwise_initializer` | An initializer for the pointwise convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `depthwise_regularizer` | Optional regularizer for the depthwise convolution kernel. |
| `pointwise_regularizer` | Optional regularizer for the pointwise convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `depthwise_constraint` | Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `pointwise_constraint` | Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.max_pooling3d tf.compat.v1.layers.max\_pooling3d
==================================
Max pooling layer for 3D inputs (e.g.
```
tf.compat.v1.layers.max_pooling3d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling3D`](../../../keras/layers/maxpool3d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.max_pooling3d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.MaxPooling3D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
volumes).
| Args |
| `inputs` | The tensor over which to pool. Must have rank 5. |
| `pool_size` | An integer or tuple/list of 3 integers: (pool\_depth, pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `name` | A string, the name of the layer. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow Module: tf.compat.v1.layers.experimental Module: tf.compat.v1.layers.experimental
========================================
Public API for tf.keras.**internal**.legacy.layers.experimental namespace.
Functions
---------
[`keras_style_scope(...)`](experimental/keras_style_scope): Use Keras-style variable management.
[`set_keras_style(...)`](experimental/set_keras_style): Use Keras-style variable management.
tensorflow tf.compat.v1.layers.separable_conv1d tf.compat.v1.layers.separable\_conv1d
=====================================
Functional interface for the depthwise separable 1D convolution layer.
```
tf.compat.v1.layers.separable_conv1d(
inputs,
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
depth_multiplier=1,
activation=None,
use_bias=True,
depthwise_initializer=None,
pointwise_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
depthwise_regularizer=None,
pointwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
pointwise_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.SeparableConv1D`](../../../keras/layers/separableconv1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.separable_conv1d(x, filters=3, kernel_size=3)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.SeparableConv1D(filters=3, kernels_size=3)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output.
| Args |
| `inputs` | Input tensor. |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A single integer specifying the spatial dimensions of the filters. |
| `strides` | A single integer specifying the strides of the convolution. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `dilation_rate` | A single integer, specifying the dilation rate to use for dilated convolution. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `depth_multiplier` | The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `depthwise_initializer` | An initializer for the depthwise convolution kernel. |
| `pointwise_initializer` | An initializer for the pointwise convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `depthwise_regularizer` | Optional regularizer for the depthwise convolution kernel. |
| `pointwise_regularizer` | Optional regularizer for the pointwise convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `depthwise_constraint` | Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `pointwise_constraint` | Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| `reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.layers.average_pooling2d tf.compat.v1.layers.average\_pooling2d
======================================
Average pooling layer for 2D inputs (e.g. images).
```
tf.compat.v1.layers.average_pooling2d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling2D`](../../../keras/layers/averagepooling2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.average_pooling2d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.AveragePooling2D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | The tensor over which to pool. Must have rank 4. |
| `pool_size` | An integer or tuple/list of 2 integers: (pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `name` | A string, the name of the layer. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.SeparableConv2D tf.compat.v1.layers.SeparableConv2D
===================================
Depthwise separable 2D convolution.
Inherits From: [`SeparableConv2D`](../../../keras/layers/separableconv2d), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.SeparableConv2D(
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
dilation_rate=(1, 1),
depth_multiplier=1,
activation=None,
use_bias=True,
depthwise_initializer=None,
pointwise_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
depthwise_regularizer=None,
pointwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
pointwise_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.SeparableConv2D`](../../../keras/layers/separableconv2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
conv = tf.compat.v1.layers.SeparableConv2D(filters=3, kernel_size=3)
```
After:
```
conv = tf.keras.layers.SeparableConv2D(filters=3, kernels_size=3)
```
Description
-----------
This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output.
| Args |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A tuple or list of 2 integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | A tuple or list of 2 positive integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `dilation_rate` | An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `depth_multiplier` | The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `depthwise_initializer` | An initializer for the depthwise convolution kernel. |
| `pointwise_initializer` | An initializer for the pointwise convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `depthwise_regularizer` | Optional regularizer for the depthwise convolution kernel. |
| `pointwise_regularizer` | Optional regularizer for the pointwise convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `depthwise_constraint` | Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `pointwise_constraint` | Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `convolution_op`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/convolutional/base_conv.py#L217-L232)
```
convolution_op(
inputs, kernel
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.max_pooling2d tf.compat.v1.layers.max\_pooling2d
==================================
Max pooling layer for 2D inputs (e.g. images).
```
tf.compat.v1.layers.max_pooling2d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.MaxPooling2D`](../../../keras/layers/maxpool2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.max_pooling2d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.MaxPooling2D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | The tensor over which to pool. Must have rank 4. |
| `pool_size` | An integer or tuple/list of 2 integers: (pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 2 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `name` | A string, the name of the layer. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.separable_conv2d tf.compat.v1.layers.separable\_conv2d
=====================================
Functional interface for the depthwise separable 2D convolution layer.
```
tf.compat.v1.layers.separable_conv2d(
inputs,
filters,
kernel_size,
strides=(1, 1),
padding='valid',
data_format='channels_last',
dilation_rate=(1, 1),
depth_multiplier=1,
activation=None,
use_bias=True,
depthwise_initializer=None,
pointwise_initializer=None,
bias_initializer=tf.compat.v1.zeros_initializer(),
depthwise_regularizer=None,
pointwise_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
depthwise_constraint=None,
pointwise_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
reuse=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.SeparableConv2D`](../../../keras/layers/separableconv2d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.separable_conv2d(x, filters=3, kernel_size=3)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.SeparableConv2D(filters=3, kernels_size=3)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
This layer performs a depthwise convolution that acts separately on channels, followed by a pointwise convolution that mixes channels. If `use_bias` is True and a bias initializer is provided, it adds a bias vector to the output. It then optionally applies an activation function to produce the final output.
| Args |
| `inputs` | Input tensor. |
| `filters` | Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). |
| `kernel_size` | A tuple or list of 2 integers specifying the spatial dimensions of the filters. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | A tuple or list of 2 positive integers specifying the strides of the convolution. Can be a single integer to specify the same value for all spatial dimensions. Specifying any `stride` value != 1 is incompatible with specifying any `dilation_rate` value != 1. |
| `padding` | One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, height, width)`. |
| `dilation_rate` | An integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any `dilation_rate` value != 1 is incompatible with specifying any stride value != 1. |
| `depth_multiplier` | The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`. |
| `activation` | Activation function. Set it to None to maintain a linear activation. |
| `use_bias` | Boolean, whether the layer uses a bias. |
| `depthwise_initializer` | An initializer for the depthwise convolution kernel. |
| `pointwise_initializer` | An initializer for the pointwise convolution kernel. |
| `bias_initializer` | An initializer for the bias vector. If None, the default initializer will be used. |
| `depthwise_regularizer` | Optional regularizer for the depthwise convolution kernel. |
| `pointwise_regularizer` | Optional regularizer for the pointwise convolution kernel. |
| `bias_regularizer` | Optional regularizer for the bias vector. |
| `activity_regularizer` | Optional regularizer function for the output. |
| `depthwise_constraint` | Optional projection function to be applied to the depthwise kernel after being updated by an `Optimizer` (e.g. used for norm constraints or value constraints for layer weights). The function must take as input the unprojected variable and must return the projected variable (which must have the same shape). Constraints are not safe to use when doing asynchronous distributed training. |
| `pointwise_constraint` | Optional projection function to be applied to the pointwise kernel after being updated by an `Optimizer`. |
| `bias_constraint` | Optional projection function to be applied to the bias after being updated by an `Optimizer`. |
| `trainable` | Boolean, if `True` also add variables to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `name` | A string, the name of the layer. |
| `reuse` | Boolean, whether to reuse the weights of a previous layer by the same name. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.Dropout tf.compat.v1.layers.Dropout
===========================
Applies Dropout to the input.
Inherits From: [`Dropout`](../../../keras/layers/dropout), [`Layer`](layer), [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Dropout(
rate=0.5, noise_shape=None, seed=None, name=None, **kwargs
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.Dropout`](../../../keras/layers/dropout).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
dropout = tf.compat.v1.layers.Dropout()
```
After:
```
dropout = tf.keras.layers.Dropout()
```
Description
-----------
Dropout consists in randomly setting a fraction `rate` of input units to 0 at each update during training time, which helps prevent overfitting. The units that are kept are scaled by `1 / (1 - rate)`, so that their sum is unchanged at training time and inference time.
| Args |
| `rate` | The dropout rate, between 0 and 1. E.g. `rate=0.1` would drop out 10% of input units. |
| `noise_shape` | 1D tensor of type `int32` representing the shape of the binary dropout mask that will be multiplied with the input. For instance, if your inputs have shape `(batch_size, timesteps, features)`, and you want the dropout mask to be the same for all timesteps, you can use `noise_shape=[batch_size, 1, features]`. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.compat.v1.set_random_seed`](../set_random_seed). for behavior. |
| `name` | The name of the layer (string). |
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
| programming_docs |
tensorflow tf.compat.v1.layers.average_pooling3d tf.compat.v1.layers.average\_pooling3d
======================================
Average pooling layer for 3D inputs (e.g. volumes).
```
tf.compat.v1.layers.average_pooling3d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling3D`](../../../keras/layers/averagepooling3d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.average_pooling3d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.AveragePooling3D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | The tensor over which to pool. Must have rank 5. |
| `pool_size` | An integer or tuple/list of 3 integers: (pool\_depth, pool\_height, pool\_width) specifying the size of the pooling window. Can be a single integer to specify the same value for all spatial dimensions. |
| `strides` | An integer or tuple/list of 3 integers, specifying the strides of the pooling operation. Can be a single integer to specify the same value for all spatial dimensions. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string. The ordering of the dimensions in the inputs. `channels_last` (default) and `channels_first` are supported. `channels_last` corresponds to inputs with shape `(batch, depth, height, width, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, depth, height, width)`. |
| `name` | A string, the name of the layer. |
| Returns |
| Output tensor. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.average_pooling1d tf.compat.v1.layers.average\_pooling1d
======================================
Average Pooling layer for 1D inputs.
```
tf.compat.v1.layers.average_pooling1d(
inputs,
pool_size,
strides,
padding='valid',
data_format='channels_last',
name=None
)
```
Migrate to TF2
--------------
This API is a legacy api that is only compatible with eager execution and [`tf.function`](../../../function) if you combine it with [`tf.compat.v1.keras.utils.track_tf1_style_variables`](../keras/utils/track_tf1_style_variables)
Please refer to [tf.layers model mapping section of the migration guide](https://www.tensorflow.org/guide/migrate/model_mapping) to learn how to use your TensorFlow v1 model in TF2 with Keras.
The corresponding TensorFlow v2 layer is [`tf.keras.layers.AveragePooling1D`](../../../keras/layers/averagepooling1d).
#### Structural Mapping to Native TF2
None of the supported arguments have changed name.
Before:
```
y = tf.compat.v1.layers.average_pooling1d(x, pool_size=2, strides=2)
```
After:
To migrate code using TF1 functional layers use the [Keras Functional API](https://www.tensorflow.org/guide/keras/functional):
```
x = tf.keras.Input((28, 28, 1))
y = tf.keras.layers.AveragePooling1D(pool_size=2, strides=2)(x)
model = tf.keras.Model(x, y)
```
Description
-----------
| Args |
| `inputs` | The tensor over which to pool. Must have rank 3. |
| `pool_size` | An integer or tuple/list of a single integer, representing the size of the pooling window. |
| `strides` | An integer or tuple/list of a single integer, specifying the strides of the pooling operation. |
| `padding` | A string. The padding method, either 'valid' or 'same'. Case-insensitive. |
| `data_format` | A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, length, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, length)`. |
| `name` | A string, the name of the layer. |
| Returns |
| The output tensor, of rank 3. |
| Raises |
| `ValueError` | if eager execution is enabled. |
tensorflow tf.compat.v1.layers.Layer tf.compat.v1.layers.Layer
=========================
Base layer class.
Inherits From: [`Layer`](../../../keras/layers/layer), [`Module`](../../../module)
```
tf.compat.v1.layers.Layer(
trainable=True, name=None, dtype=None, **kwargs
)
```
It is considered legacy, and we recommend the use of [`tf.keras.layers.Layer`](../../../keras/layers/layer) instead.
| Args |
| `trainable` | Boolean, whether the layer's variables should be trainable. |
| `name` | String name of the layer. |
| `dtype` | Default dtype of the layer's weights (default of `None` means use the type of the first input). |
Read-only properties: name: The name of the layer (string). dtype: Default dtype of the layer's weights (default of `None` means use the type of the first input). trainable\_variables: List of trainable variables. non\_trainable\_variables: List of non-trainable variables. variables: List of all variables of this layer, trainable and non-trainable. updates: List of update ops of this layer. losses: List of losses added by this layer. trainable\_weights: List of variables to be included in backprop. non\_trainable\_weights: List of variables that should not be included in backprop. weights: The concatenation of the lists trainable\_weights and non\_trainable\_weights (in this order).
#### Mutable properties:
* **`trainable`**: Whether the layer should be trained (boolean).
* **`input_spec`**: Optional (list of) `InputSpec` object(s) specifying the constraints on inputs that can be accepted by the layer.
| Attributes |
| `graph` | |
| `scope_name` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
tensorflow tf.compat.v1.layers.experimental.set_keras_style tf.compat.v1.layers.experimental.set\_keras\_style
==================================================
Use Keras-style variable management.
```
tf.compat.v1.layers.experimental.set_keras_style()
```
All tf.layers and tf RNN cells created after keras style ha been enabled use Keras-style variable management. Creating such layers with a scope= argument is disallowed, and reuse=True is disallowed.
The purpose of this function is to allow users of existing layers to slowly transition to Keras layers API without breaking existing functionality.
For more details, see the documentation for `keras_style_scope`.
Note, once keras style has been set, it is set globally for the entire program and cannot be unset.
#### Example:
```
set_keras_style()
model_1 = RNNModel(name="model_1")
model_2 = RNNModel(name="model_2")
# model_1 and model_2 are guaranteed to create their own variables.
output_1, next_state_1 = model_1(input, state)
output_2, next_state_2 = model_2(input, state)
assert len(model_1.weights) > 0
assert len(model_2.weights) > 0
assert(model_1.weights != model_2.weights)
```
tensorflow tf.compat.v1.layers.experimental.keras_style_scope tf.compat.v1.layers.experimental.keras\_style\_scope
====================================================
Use Keras-style variable management.
```
@tf_contextlib.contextmanager
tf.compat.v1.layers.experimental.keras_style_scope()
```
All tf.layers and tf RNN cells created in this scope use Keras-style variable management. Creating such layers with a scope= argument is disallowed, and reuse=True is disallowed.
The purpose of this scope is to allow users of existing layers to slowly transition to a Keras layers API without breaking existing functionality.
One example of this is when using TensorFlow's RNN classes with Keras Models or Networks. Because Keras models do not properly set variable scopes, users of RNNs may either accidentally share scopes between two different models, or get errors about variables that already exist.
#### Example:
```
class RNNModel(tf.keras.Model):
def __init__(self, name):
super(RNNModel, self).__init__(name=name)
self.rnn = tf.compat.v1.nn.rnn_cell.MultiRNNCell(
[tf.compat.v1.nn.rnn_cell.LSTMCell(64) for _ in range(2)])
def call(self, input, state):
return self.rnn(input, state)
model_1 = RNNModel("model_1")
model_2 = RNNModel("model_2")
# OK
output_1, next_state_1 = model_1(input, state)
# Raises an error about trying to create an already existing variable.
output_2, next_state_2 = model_2(input, state)
```
The solution is to wrap the model construction and execution in a keras-style scope:
```
with keras_style_scope():
model_1 = RNNModel("model_1")
model_2 = RNNModel("model_2")
# model_1 and model_2 are guaranteed to create their own variables.
output_1, next_state_1 = model_1(input, state)
output_2, next_state_2 = model_2(input, state)
assert len(model_1.weights) > 0
assert len(model_2.weights) > 0
assert(model_1.weights != model_2.weights)
```
| Yields |
| A keras layer style scope. |
tensorflow tf.compat.v1.nn.max_pool tf.compat.v1.nn.max\_pool
=========================
Performs the max pooling on the input.
```
tf.compat.v1.nn.max_pool(
value,
ksize,
strides,
padding,
data_format='NHWC',
name=None,
input=None
)
```
| Args |
| `value` | A 4-D `Tensor` of the format specified by `data_format`. |
| `ksize` | An int or list of `ints` that has length `1`, `2` or `4`. The size of the window for each dimension of the input tensor. |
| `strides` | An int or list of `ints` that has length `1`, `2` or `4`. The stride of the sliding window for each dimension of the input tensor. |
| `padding` | Either the `string` `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. When using explicit padding, the size of the paddings cannot be greater than the sliding window size. |
| `data_format` | A string. 'NHWC', 'NCHW' and 'NCHW\_VECT\_C' are supported. |
| `name` | Optional name for the operation. |
| `input` | Alias for value. |
| Returns |
| A `Tensor` of format specified by `data_format`. The max pooled output tensor. |
tensorflow tf.compat.v1.nn.crelu tf.compat.v1.nn.crelu
=====================
Computes Concatenated ReLU.
```
tf.compat.v1.nn.crelu(
features, name=None, axis=-1
)
```
Concatenates a ReLU which selects only the positive part of the activation with a ReLU which selects only the *negative* part of the activation. Note that as a result this non-linearity doubles the depth of the activations. Source: [Understanding and Improving Convolutional Neural Networks via Concatenated Rectified Linear Units. W. Shang, et al.](https://arxiv.org/abs/1603.05201)
| Args |
| `features` | A `Tensor` with type `float`, `double`, `int32`, `int64`, `uint8`, `int16`, or `int8`. |
| `name` | A name for the operation (optional). |
| `axis` | The axis that the output values are concatenated along. Default is -1. |
| Returns |
| A `Tensor` with the same type as `features`. |
#### References:
Understanding and Improving Convolutional Neural Networks via Concatenated Rectified Linear Units: [Shang et al., 2016](http://proceedings.mlr.press/v48/shang16) ([pdf](http://proceedings.mlr.press/v48/shang16.pdf))
tensorflow tf.compat.v1.nn.conv2d tf.compat.v1.nn.conv2d
======================
Computes a 2-D convolution given 4-D `input` and `filter` tensors.
```
tf.compat.v1.nn.conv2d(
input,
filter=None,
strides=None,
padding=None,
use_cudnn_on_gpu=True,
data_format='NHWC',
dilations=[1, 1, 1, 1],
name=None,
filters=None
)
```
Given an input tensor of shape `[batch, in_height, in_width, in_channels]` and a filter / kernel tensor of shape `[filter_height, filter_width, in_channels, out_channels]`, this op performs the following:
1. Flattens the filter to a 2-D matrix with shape `[filter_height * filter_width * in_channels, output_channels]`.
2. Extracts image patches from the input tensor to form a *virtual* tensor of shape `[batch, out_height, out_width, filter_height * filter_width * in_channels]`.
3. For each patch, right-multiplies the filter matrix and the image patch vector.
In detail, with the default NHWC format,
```
output[b, i, j, k] =
sum_{di, dj, q} input[b, strides[1] * i + di, strides[2] * j + dj, q]
* filter[di, dj, q, k]
```
Must have `strides[0] = strides[3] = 1`. For the most common case of the same horizontal and vertical strides, `strides = [1, stride, stride, 1]`.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. A 4-D tensor. The dimension order is interpreted according to the value of `data_format`, see below for details. |
| `filter` | A `Tensor`. Must have the same type as `input`. A 4-D tensor of shape `[filter_height, filter_width, in_channels, out_channels]` |
| `strides` | An int or list of `ints` that has length `1`, `2` or `4`. The stride of the sliding window for each dimension of `input`. If a single value is given it is replicated in the `H` and `W` dimension. By default the `N` and `C` dimensions are set to 1. The dimension order is determined by the value of `data_format`, see below for details. |
| `padding` | Either the `string` `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `use_cudnn_on_gpu` | An optional `bool`. Defaults to `True`. |
| `data_format` | An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, height, width, channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, channels, height, width]. |
| `dilations` | An int or list of `ints` that has length `1`, `2` or `4`, defaults to 1. The dilation factor for each dimension of`input`. If a single value is given it is replicated in the `H` and `W` dimension. By default the `N` and `C` dimensions are set to 1. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions if a 4-d tensor must be 1. |
| `name` | A name for the operation (optional). |
| `filters` | Alias for filter. |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow tf.compat.v1.nn.ctc_loss_v2 tf.compat.v1.nn.ctc\_loss\_v2
=============================
Computes CTC (Connectionist Temporal Classification) loss.
```
tf.compat.v1.nn.ctc_loss_v2(
labels,
logits,
label_length,
logit_length,
logits_time_major=True,
unique=None,
blank_index=None,
name=None
)
```
This op implements the CTC loss as presented in (Graves et al., 2006).
#### Notes:
* Same as the "Classic CTC" in TensorFlow 1.x's tf.compat.v1.nn.ctc\_loss setting of preprocess\_collapse\_repeated=False, ctc\_merge\_repeated=True
* Labels may be supplied as either a dense, zero-padded tensor with a vector of label sequence lengths OR as a SparseTensor.
* On TPU and GPU: Only dense padded labels are supported.
* On CPU: Caller may use SparseTensor or dense padded labels but calling with a SparseTensor will be significantly faster.
* Default blank label is 0 rather num\_classes - 1, unless overridden by blank\_index.
| Args |
| `labels` | tensor of shape [batch\_size, max\_label\_seq\_length] or SparseTensor |
| `logits` | tensor of shape [frames, batch\_size, num\_labels], if logits\_time\_major == False, shape is [batch\_size, frames, num\_labels]. |
| `label_length` | tensor of shape [batch\_size], None if labels is SparseTensor Length of reference label sequence in labels. |
| `logit_length` | tensor of shape [batch\_size] Length of input sequence in logits. |
| `logits_time_major` | (optional) If True (default), logits is shaped [time, batch, logits]. If False, shape is [batch, time, logits] |
| `unique` | (optional) Unique label indices as computed by ctc\_unique\_labels(labels). If supplied, enable a faster, memory efficient implementation on TPU. |
| `blank_index` | (optional) Set the class index to use for the blank label. Negative values will start from num\_classes, ie, -1 will reproduce the ctc\_loss behavior of using num\_classes - 1 for the blank symbol. There is some memory/performance overhead to switching from the default of 0 as an additional shifted copy of the logits may be created. |
| `name` | A name for this `Op`. Defaults to "ctc\_loss\_dense". |
| Returns |
| `loss` | tensor of shape [batch\_size], negative log probabilities. |
#### References:
Connectionist Temporal Classification - Labeling Unsegmented Sequence Data with Recurrent Neural Networks: [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) ([pdf](http://www.cs.toronto.edu/%7Egraves/icml_2006.pdf))
tensorflow tf.compat.v1.nn.embedding_lookup tf.compat.v1.nn.embedding\_lookup
=================================
Looks up embeddings for the given `ids` from a list of tensors.
```
tf.compat.v1.nn.embedding_lookup(
params,
ids,
partition_strategy='mod',
name=None,
validate_indices=True,
max_norm=None
)
```
This function is used to perform parallel lookups on the list of tensors in `params`. It is a generalization of [`tf.gather`](../../../gather), where `params` is interpreted as a partitioning of a large embedding tensor. `params` may be a `PartitionedVariable` as returned by using [`tf.compat.v1.get_variable()`](../get_variable) with a partitioner.
If `len(params) > 1`, each element `id` of `ids` is partitioned between the elements of `params` according to the `partition_strategy`. In all strategies, if the id space does not evenly divide the number of partitions, each of the first `(max_id + 1) % len(params)` partitions will be assigned one more id.
If `partition_strategy` is `"mod"`, we assign each id to partition `p = id % len(params)`. For instance, 13 ids are split across 5 partitions as: `[[0, 5, 10], [1, 6, 11], [2, 7, 12], [3, 8], [4, 9]]`
If `partition_strategy` is `"div"`, we assign ids to partitions in a contiguous manner. In this case, 13 ids are split across 5 partitions as: `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10], [11, 12]]`
If the input ids are ragged tensors, partition variables are not supported and the partition strategy and the max\_norm are ignored. The results of the lookup are concatenated into a dense tensor. The returned tensor has shape `shape(ids) + shape(params)[1:]`.
| Args |
| `params` | A single tensor representing the complete embedding tensor, or a list of P tensors all of same shape except for the first dimension, representing sharded embedding tensors. Alternatively, a `PartitionedVariable`, created by partitioning along dimension 0. Each element must be appropriately sized for the given `partition_strategy`. |
| `ids` | A `Tensor` or a 'RaggedTensor' with type `int32` or `int64` containing the ids to be looked up in `params`. |
| `partition_strategy` | A string specifying the partitioning strategy, relevant if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. |
| `name` | A name for the operation (optional). |
| `validate_indices` | DEPRECATED. If this operation is assigned to CPU, values in `indices` are always validated to be within range. If assigned to GPU, out-of-bound indices result in safe but unspecified behavior, which may include raising an error. |
| `max_norm` | If not `None`, each embedding is clipped if its l2-norm is larger than this value. |
| Returns |
| A `Tensor` or a 'RaggedTensor', depending on the input, with the same type as the tensors in `params`. |
| Raises |
| `ValueError` | If `params` is empty. |
| programming_docs |
tensorflow tf.compat.v1.nn.depthwise_conv2d_native tf.compat.v1.nn.depthwise\_conv2d\_native
=========================================
Computes a 2-D depthwise convolution.
```
tf.compat.v1.nn.depthwise_conv2d_native(
input,
filter,
strides,
padding,
data_format='NHWC',
dilations=[1, 1, 1, 1],
name=None
)
```
Given an input tensor of shape `[batch, in_height, in_width, in_channels]` and a filter / kernel tensor of shape `[filter_height, filter_width, in_channels, channel_multiplier]`, containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies a different filter to each input channel (expanding from 1 channel to `channel_multiplier` channels for each), then concatenates the results together. Thus, the output has `in_channels * channel_multiplier` channels.
```
for k in 0..in_channels-1
for q in 0..channel_multiplier-1
output[b, i, j, k * channel_multiplier + q] =
sum_{di, dj} input[b, strides[1] * i + di, strides[2] * j + dj, k] *
filter[di, dj, k, q]
```
Must have `strides[0] = strides[3] = 1`. For the most common case of the same horizontal and vertices strides, `strides = [1, stride, stride, 1]`.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. |
| `filter` | A `Tensor`. Must have the same type as `input`. |
| `strides` | A list of `ints`. 1-D of length 4. The stride of the sliding window for each dimension of `input`. |
| `padding` | Controls how to pad the image before applying the convolution. Can be the string `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `data_format` | An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, height, width, channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, channels, height, width]. |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D tensor of length 4. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow tf.compat.v1.nn.conv3d_transpose tf.compat.v1.nn.conv3d\_transpose
=================================
The transpose of `conv3d`.
```
tf.compat.v1.nn.conv3d_transpose(
value,
filter=None,
output_shape=None,
strides=None,
padding='SAME',
data_format='NDHWC',
name=None,
input=None,
filters=None,
dilations=None
)
```
This operation is sometimes called "deconvolution" after (Zeiler et al., 2010), but is really the transpose (gradient) of `conv3d` rather than an actual deconvolution.
| Args |
| `value` | A 5-D `Tensor` of type `float` and shape `[batch, depth, height, width, in_channels]`. |
| `filter` | A 5-D `Tensor` with the same type as `value` and shape `[depth, height, width, output_channels, in_channels]`. `filter`'s `in_channels` dimension must match that of `value`. |
| `output_shape` | A 1-D `Tensor` representing the output shape of the deconvolution op. |
| `strides` | A list of ints. The stride of the sliding window for each dimension of the input tensor. |
| `padding` | A string, either `'VALID'` or `'SAME'`. The padding algorithm. See the "returns" section of [`tf.nn.convolution`](../../../nn/convolution) for details. |
| `data_format` | A string, either `'NDHWC'` or `'NCDHW`' specifying the layout of the input and output tensors. Defaults to `'NDHWC'`. |
| `name` | Optional name for the returned tensor. |
| `input` | Alias of value. |
| `filters` | Alias of filter. |
| `dilations` | An int or list of `ints` that has length `1`, `3` or `5`, defaults to 1. The dilation factor for each dimension of`input`. If a single value is given it is replicated in the `D`, `H` and `W` dimension. By default the `N` and `C` dimensions are set to 1. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions if a 5-d tensor must be 1. |
| Returns |
| A `Tensor` with the same type as `value`. |
| Raises |
| `ValueError` | If input/output depth does not match `filter`'s shape, or if padding is other than `'VALID'` or `'SAME'`. |
#### References:
Deconvolutional Networks: [Zeiler et al., 2010](https://ieeexplore.ieee.org/abstract/document/5539957) ([pdf](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
tensorflow tf.compat.v1.nn.conv3d_backprop_filter tf.compat.v1.nn.conv3d\_backprop\_filter
========================================
Computes the gradients of 3-D convolution with respect to the filter.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.nn.conv3d_backprop_filter_v2`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/nn/conv3d_backprop_filter)
```
tf.compat.v1.nn.conv3d_backprop_filter(
input,
filter_sizes,
out_backprop,
strides,
padding,
data_format='NDHWC',
dilations=[1, 1, 1, 1, 1],
name=None
)
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. Shape `[batch, depth, rows, cols, in_channels]`. |
| `filter_sizes` | A `Tensor` of type `int32`. An integer vector representing the tensor shape of `filter`, where `filter` is a 5-D `[filter_depth, filter_height, filter_width, in_channels, out_channels]` tensor. |
| `out_backprop` | A `Tensor`. Must have the same type as `input`. Backprop signal of shape `[batch, out_depth, out_rows, out_cols, out_channels]`. |
| `strides` | A list of `ints` that has length `>= 5`. 1-D tensor of length 5. The stride of the sliding window for each dimension of `input`. Must have `strides[0] = strides[4] = 1`. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `data_format` | An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in\_depth, in\_height, in\_width, in\_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in\_channels, in\_depth, in\_height, in\_width]. |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. 1-D tensor of length 5. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow tf.compat.v1.nn.batch_norm_with_global_normalization tf.compat.v1.nn.batch\_norm\_with\_global\_normalization
========================================================
Batch normalization.
```
tf.compat.v1.nn.batch_norm_with_global_normalization(
t=None,
m=None,
v=None,
beta=None,
gamma=None,
variance_epsilon=None,
scale_after_normalization=None,
name=None,
input=None,
mean=None,
variance=None
)
```
This op is deprecated. See [`tf.nn.batch_normalization`](../../../nn/batch_normalization).
| Args |
| `t` | A 4D input Tensor. |
| `m` | A 1D mean Tensor with size matching the last dimension of t. This is the first output from tf.nn.moments, or a saved moving average thereof. |
| `v` | A 1D variance Tensor with size matching the last dimension of t. This is the second output from tf.nn.moments, or a saved moving average thereof. |
| `beta` | A 1D beta Tensor with size matching the last dimension of t. An offset to be added to the normalized tensor. |
| `gamma` | A 1D gamma Tensor with size matching the last dimension of t. If "scale\_after\_normalization" is true, this tensor will be multiplied with the normalized tensor. |
| `variance_epsilon` | A small float number to avoid dividing by 0. |
| `scale_after_normalization` | A bool indicating whether the resulted tensor needs to be multiplied with gamma. |
| `name` | A name for this operation (optional). |
| `input` | Alias for t. |
| `mean` | Alias for m. |
| `variance` | Alias for v. |
| Returns |
| A batch-normalized `t`. |
#### References:
Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))
tensorflow tf.compat.v1.nn.sigmoid_cross_entropy_with_logits tf.compat.v1.nn.sigmoid\_cross\_entropy\_with\_logits
=====================================================
Computes sigmoid cross entropy given `logits`.
```
tf.compat.v1.nn.sigmoid_cross_entropy_with_logits(
_sentinel=None, labels=None, logits=None, name=None
)
```
Measures the probability error in tasks with two outcomes in which each outcome is independent and need not have a fully certain label. For instance, one could perform a regression where the probability of an event happening is known and used as a label. This loss may also be used for binary classification, where labels are either zero or one.
For brevity, let `x = logits`, `z = labels`. The logistic loss is
```
z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
= z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
= z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
= z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
= (1 - z) * x + log(1 + exp(-x))
= x - x * z + log(1 + exp(-x))
```
For x < 0, to avoid overflow in exp(-x), we reformulate the above
```
x - x * z + log(1 + exp(-x))
= log(exp(x)) - x * z + log(1 + exp(-x))
= - x * z + log(1 + exp(x))
```
Hence, to ensure stability and avoid overflow, the implementation uses this equivalent formulation
```
max(x, 0) - x * z + log(1 + exp(-abs(x)))
```
`logits` and `labels` must have the same type and shape.
```
logits = tf.constant([1., -1., 0., 1., -1., 0., 0.])
labels = tf.constant([0., 0., 0., 1., 1., 1., 0.5])
tf.nn.sigmoid_cross_entropy_with_logits(
labels=labels, logits=logits).numpy()
array([1.3132617, 0.3132617, 0.6931472, 0.3132617, 1.3132617, 0.6931472,
0.6931472], dtype=float32)
```
Compared to the losses which handle multiple outcomes, [`tf.nn.softmax_cross_entropy_with_logits`](../../../nn/softmax_cross_entropy_with_logits) for general multi-class classification and [`tf.nn.sparse_softmax_cross_entropy_with_logits`](../../../nn/sparse_softmax_cross_entropy_with_logits) for more efficient multi-class classification with hard labels, `sigmoid_cross_entropy_with_logits` is a slight simplification for binary classification:
```
sigmoid(x) = softmax([x, 0])[0]
```
\[\frac{1}{1 + e^{-x} } = \frac{e^x}{e^x + e^0}\]
While `sigmoid_cross_entropy_with_logits` works for soft binary labels (probabilities between 0 and 1), it can also be used for binary classification where the labels are hard. There is an equivalence between all three symbols in this case, with a probability 0 indicating the second class or 1 indicating the first class:
```
sigmoid_logits = tf.constant([1., -1., 0.])
softmax_logits = tf.stack([sigmoid_logits, tf.zeros_like(sigmoid_logits)],
axis=-1)
soft_binary_labels = tf.constant([1., 1., 0.])
soft_multiclass_labels = tf.stack(
[soft_binary_labels, 1. - soft_binary_labels], axis=-1)
hard_labels = tf.constant([0, 0, 1])
tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=hard_labels, logits=softmax_logits).numpy()
array([0.31326166, 1.3132616 , 0.6931472 ], dtype=float32)
tf.nn.softmax_cross_entropy_with_logits(
labels=soft_multiclass_labels, logits=softmax_logits).numpy()
array([0.31326166, 1.3132616, 0.6931472], dtype=float32)
tf.nn.sigmoid_cross_entropy_with_logits(
labels=soft_binary_labels, logits=sigmoid_logits).numpy()
array([0.31326166, 1.3132616, 0.6931472], dtype=float32)
```
| Args |
| `labels` | A `Tensor` of the same type and shape as `logits`. Between 0 and 1, inclusive. |
| `logits` | A `Tensor` of type `float32` or `float64`. Any real number. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of the same shape as `logits` with the componentwise logistic losses. |
| Raises |
| `ValueError` | If `logits` and `labels` do not have the same shape. |
tensorflow Module: tf.compat.v1.nn.rnn_cell Module: tf.compat.v1.nn.rnn\_cell
=================================
Public API for tf.keras.**internal**.legacy.rnn\_cell namespace.
Classes
-------
[`class BasicLSTMCell`](rnn_cell/basiclstmcell): DEPRECATED: Please use [`tf.compat.v1.nn.rnn_cell.LSTMCell`](rnn_cell/lstmcell) instead.
[`class BasicRNNCell`](rnn_cell/basicrnncell): The most basic RNN cell.
[`class DeviceWrapper`](rnn_cell/devicewrapper): Operator that ensures an RNNCell runs on a particular device.
[`class DropoutWrapper`](rnn_cell/dropoutwrapper): Operator adding dropout to inputs and outputs of the given cell.
[`class GRUCell`](rnn_cell/grucell): Gated Recurrent Unit cell.
[`class LSTMCell`](rnn_cell/lstmcell): Long short-term memory unit (LSTM) recurrent network cell.
[`class LSTMStateTuple`](rnn_cell/lstmstatetuple): Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
[`class MultiRNNCell`](rnn_cell/multirnncell): RNN cell composed sequentially of multiple simple cells.
[`class RNNCell`](rnn_cell/rnncell): Abstract object representing an RNN cell.
[`class ResidualWrapper`](rnn_cell/residualwrapper): RNNCell wrapper that ensures cell inputs are added to the outputs.
tensorflow tf.compat.v1.nn.softmax_cross_entropy_with_logits tf.compat.v1.nn.softmax\_cross\_entropy\_with\_logits
=====================================================
Computes softmax cross entropy between `logits` and `labels`. (deprecated)
```
tf.compat.v1.nn.softmax_cross_entropy_with_logits(
_sentinel=None, labels=None, logits=None, dim=-1, name=None, axis=None
)
```
Future major versions of TensorFlow will allow gradients to flow into the labels input on backprop by default.
See `tf.nn.softmax_cross_entropy_with_logits_v2`.
Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both.
>
> **Note:** While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of `labels` is a valid probability distribution. If they are not, the computation of the gradient will be incorrect.
>
If using exclusive `labels` (wherein one and only one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.
A common use case is to have logits and labels of shape `[batch_size, num_classes]`, but higher dimensions are supported, with the `dim` argument specifying the class dimension.
Backpropagation will happen only into `logits`. To calculate a cross entropy loss that allows backpropagation into both `logits` and `labels`, see `tf.nn.softmax_cross_entropy_with_logits_v2`.
**Note that to avoid confusion, it is required to pass only named arguments to this function.**
| Args |
| `_sentinel` | Used to prevent positional parameters. Internal, do not use. |
| `labels` | Each vector along the class dimension should hold a valid probability distribution e.g. for the case in which labels are of shape `[batch_size, num_classes]`, each row of `labels[i]` must be a valid probability distribution. |
| `logits` | Per-label activations, typically a linear output. These activation energies are interpreted as unnormalized log probabilities. |
| `dim` | The class dimension. Defaulted to -1 which is the last dimension. |
| `name` | A name for the operation (optional). |
| `axis` | Alias for dim. |
| Returns |
| A `Tensor` that contains the softmax cross entropy loss. Its type is the same as `logits` and its shape is the same as `labels` except that it does not have the last dimension of `labels`. |
tensorflow tf.compat.v1.nn.ctc_beam_search_decoder tf.compat.v1.nn.ctc\_beam\_search\_decoder
==========================================
Performs beam search decoding on the logits given in input.
```
tf.compat.v1.nn.ctc_beam_search_decoder(
inputs, sequence_length, beam_width=100, top_paths=1, merge_repeated=True
)
```
>
> **Note:** Although in general greedy search is a special case of beam-search with `top_paths=1` and `beam_width=1`, `ctc_beam_search_decoder` differs from `ctc_greedy_decoder` in the treatment of blanks when computing the probability of a sequence:
>
* `ctc_beam_search_decoder` treats blanks as sequence termination
* `ctc_greedy_decoder` treats blanks as regular elements
If `merge_repeated` is `True`, merge repeated classes in the output beams. This means that if consecutive entries in a beam are the same, only the first of these is emitted. That is, when the sequence is `A B B * B * B` (where '\*' is the blank label), the return value is:
* `A B` if `merge_repeated = True`.
* `A B B B` if `merge_repeated = False`.
| Args |
| `inputs` | 3-D `float` `Tensor`, size `[max_time x batch_size x num_classes]`. The logits. |
| `sequence_length` | 1-D `int32` vector containing sequence lengths, having size `[batch_size]`. |
| `beam_width` | An int scalar >= 0 (beam search beam width). |
| `top_paths` | An int scalar >= 0, <= beam\_width (controls output size). |
| `merge_repeated` | Boolean. Default: True. |
| Returns |
| A tuple `(decoded, log_probabilities)` where |
| `decoded` | A list of length top\_paths, where `decoded[j]` is a `SparseTensor` containing the decoded outputs: `decoded[j].indices`: Indices matrix `(total_decoded_outputs[j] x 2)` The rows store: [batch, time]. `decoded[j].values`: Values vector, size `(total_decoded_outputs[j])`. The vector stores the decoded classes for beam j. `decoded[j].dense_shape`: Shape vector, size `(2)`. The shape values are: `[batch_size, max_decoded_length[j]]`. |
| `log_probability` | A `float` matrix `(batch_size x top_paths)` containing sequence log-probabilities. |
tensorflow tf.compat.v1.nn.softmax_cross_entropy_with_logits_v2 tf.compat.v1.nn.softmax\_cross\_entropy\_with\_logits\_v2
=========================================================
Computes softmax cross entropy between `logits` and `labels`. (deprecated arguments)
```
tf.compat.v1.nn.softmax_cross_entropy_with_logits_v2(
labels, logits, axis=None, name=None, dim=None
)
```
Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both.
>
> **Note:** While the classes are mutually exclusive, their probabilities need not be. All that is required is that each row of `labels` is a valid probability distribution. If they are not, the computation of the gradient will be incorrect.
>
If using exclusive `labels` (wherein one and only one class is true at a time), see `sparse_softmax_cross_entropy_with_logits`.
A common use case is to have logits and labels of shape `[batch_size, num_classes]`, but higher dimensions are supported, with the `axis` argument specifying the class dimension.
`logits` and `labels` must have the same dtype (either `float16`, `float32`, or `float64`).
Backpropagation will happen into both `logits` and `labels`. To disallow backpropagation into `labels`, pass label tensors through [`tf.stop_gradient`](../../../stop_gradient) before feeding it to this function.
**Note that to avoid confusion, it is required to pass only named arguments to this function.**
| Args |
| `labels` | Each vector along the class dimension should hold a valid probability distribution e.g. for the case in which labels are of shape `[batch_size, num_classes]`, each row of `labels[i]` must be a valid probability distribution. |
| `logits` | Unscaled log probabilities. |
| `axis` | The class dimension. Defaulted to -1 which is the last dimension. |
| `name` | A name for the operation (optional). |
| `dim` | Deprecated alias for axis. |
| Returns |
| A `Tensor` that contains the softmax cross entropy loss. Its type is the same as `logits` and its shape is the same as `labels` except that it does not have the last dimension of `labels`. |
| programming_docs |
tensorflow tf.compat.v1.nn.embedding_lookup_sparse tf.compat.v1.nn.embedding\_lookup\_sparse
=========================================
Looks up embeddings for the given ids and weights from a list of tensors.
```
tf.compat.v1.nn.embedding_lookup_sparse(
params,
sp_ids,
sp_weights,
partition_strategy='mod',
name=None,
combiner=None,
max_norm=None
)
```
This op assumes that there is at least one id for each row in the dense tensor represented by sp\_ids (i.e. there are no rows with empty features), and that all the indices of sp\_ids are in canonical row-major order.
`sp_ids` and `sp_weights` (if not None) are `SparseTensor`s with rank of 2. Embeddings are always aggregated along the last dimension.
It also assumes that all id values lie in the range [0, p0), where p0 is the sum of the size of params along dimension 0.
| Args |
| `params` | A single tensor representing the complete embedding tensor, or a list tensors all of same shape except for the first dimension, representing sharded embedding tensors. Alternatively, a `PartitionedVariable`, created by partitioning along dimension 0. Each element must be appropriately sized for the given `partition_strategy`. |
| `sp_ids` | N x M `SparseTensor` of int64 ids where N is typically batch size and M is arbitrary. |
| `sp_weights` | either a `SparseTensor` of float / double weights, or `None` to indicate all weights should be taken to be 1. If specified, `sp_weights` must have exactly the same shape and indices as `sp_ids`. |
| `partition_strategy` | A string specifying the partitioning strategy, relevant if `len(params) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. |
| `name` | Optional name for the op. |
| `combiner` | A string specifying the reduction op. Currently "mean", "sqrtn" and "sum" are supported. "sum" computes the weighted sum of the embedding results for each row. "mean" is the weighted sum divided by the total weight. "sqrtn" is the weighted sum divided by the square root of the sum of the squares of the weights. Defaults to `mean`. |
| `max_norm` | If not `None`, each embedding is clipped if its l2-norm is larger than this value, before combining. |
| Returns |
| A dense tensor representing the combined embeddings for the sparse ids. For each row in the dense tensor represented by `sp_ids`, the op looks up the embeddings for all ids in that row, multiplies them by the corresponding weight, and combines these embeddings as specified. In other words, if `shape(combined params) = [p0, p1, ..., pm]` and `shape(sp_ids) = shape(sp_weights) = [d0, d1]` then `shape(output) = [d0, p1, ..., pm]`. For instance, if params is a 10x20 matrix, and sp\_ids / sp\_weights are
```
[0, 0]: id 1, weight 2.0
[0, 1]: id 3, weight 0.5
[1, 0]: id 0, weight 1.0
[2, 3]: id 1, weight 3.0
```
with `combiner`="mean", then the output will be a 3x20 matrix where
```
output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
output[1, :] = (params[0, :] * 1.0) / 1.0
output[2, :] = (params[1, :] * 3.0) / 3.0
```
|
| Raises |
| `TypeError` | If `sp_ids` is not a `SparseTensor`, or if `sp_weights` is neither `None` nor `SparseTensor`. |
| `ValueError` | If `combiner` is not one of {"mean", "sqrtn", "sum"}. |
tensorflow tf.compat.v1.nn.quantized_avg_pool tf.compat.v1.nn.quantized\_avg\_pool
====================================
Produces the average pool of the input tensor for quantized types.
```
tf.compat.v1.nn.quantized_avg_pool(
input, min_input, max_input, ksize, strides, padding, name=None
)
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. 4-D with shape `[batch, height, width, channels]`. |
| `min_input` | A `Tensor` of type `float32`. The float value that the lowest quantized input value represents. |
| `max_input` | A `Tensor` of type `float32`. The float value that the highest quantized input value represents. |
| `ksize` | A list of `ints`. The size of the window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input. |
| `strides` | A list of `ints`. The stride of the sliding window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (output, min\_output, max\_output). |
| `output` | A `Tensor`. Has the same type as `input`. |
| `min_output` | A `Tensor` of type `float32`. |
| `max_output` | A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.nn.conv3d tf.compat.v1.nn.conv3d
======================
Computes a 3-D convolution given 5-D `input` and `filter` tensors.
```
tf.compat.v1.nn.conv3d(
input,
filter=None,
strides=None,
padding=None,
data_format='NDHWC',
dilations=[1, 1, 1, 1, 1],
name=None,
filters=None
)
```
In signal processing, cross-correlation is a measure of similarity of two waveforms as a function of a time-lag applied to one of them. This is also known as a sliding dot product or sliding inner-product.
Our Conv3D implements a form of cross-correlation.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. Shape `[batch, in_depth, in_height, in_width, in_channels]`. |
| `filter` | A `Tensor`. Must have the same type as `input`. Shape `[filter_depth, filter_height, filter_width, in_channels, out_channels]`. `in_channels` must match between `input` and `filter`. |
| `strides` | A list of `ints` that has length `>= 5`. 1-D tensor of length 5. The stride of the sliding window for each dimension of `input`. Must have `strides[0] = strides[4] = 1`. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `data_format` | An optional `string` from: `"NDHWC", "NCDHW"`. Defaults to `"NDHWC"`. The data format of the input and output data. With the default format "NDHWC", the data is stored in the order of: [batch, in\_depth, in\_height, in\_width, in\_channels]. Alternatively, the format could be "NCDHW", the data storage order is: [batch, in\_channels, in\_depth, in\_height, in\_width]. |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1, 1]`. 1-D tensor of length 5. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow tf.compat.v1.nn.pool tf.compat.v1.nn.pool
====================
Performs an N-D pooling operation.
```
tf.compat.v1.nn.pool(
input,
window_shape,
pooling_type,
padding,
dilation_rate=None,
strides=None,
name=None,
data_format=None,
dilations=None
)
```
In the case that `data_format` does not start with "NC", computes for 0 <= b < batch\_size, 0 <= x[i] < output\_spatial\_shape[i], 0 <= c < num\_channels:
```
output[b, x[0], ..., x[N-1], c] =
REDUCE_{z[0], ..., z[N-1]}
input[b,
x[0] * strides[0] - pad_before[0] + dilation_rate[0]*z[0],
...
x[N-1]*strides[N-1] - pad_before[N-1] + dilation_rate[N-1]*z[N-1],
c],
```
where the reduction function REDUCE depends on the value of `pooling_type`, and pad\_before is defined based on the value of `padding` as described in the "returns" section of [`tf.nn.convolution`](../../../nn/convolution) for details. The reduction never includes out-of-bounds positions.
In the case that `data_format` starts with `"NC"`, the `input` and output are simply transposed as follows:
```
pool(input, data_format, **kwargs) =
tf.transpose(pool(tf.transpose(input, [0] + range(2,N+2) + [1]),
**kwargs),
[0, N+1] + range(1, N+1))
```
| Args |
| `input` | Tensor of rank N+2, of shape `[batch_size] + input_spatial_shape + [num_channels]` if data\_format does not start with "NC" (default), or `[batch_size, num_channels] + input_spatial_shape` if data\_format starts with "NC". Pooling happens over the spatial dimensions only. |
| `window_shape` | Sequence of N ints >= 1. |
| `pooling_type` | Specifies pooling operation, must be "AVG" or "MAX". |
| `padding` | The padding algorithm, must be "SAME" or "VALID". See the "returns" section of [`tf.nn.convolution`](../../../nn/convolution) for details. |
| `dilation_rate` | Optional. Dilation rate. List of N ints >= 1. Defaults to `[1]*N`. If any value of dilation\_rate is > 1, then all values of strides must be 1. |
| `strides` | Optional. Sequence of N ints >= 1. Defaults to `[1]*N`. If any value of strides is > 1, then all values of dilation\_rate must be 1. |
| `name` | Optional. Name of the op. |
| `data_format` | A string or None. Specifies whether the channel dimension of the `input` and output is the last dimension (default, or if `data_format` does not start with "NC"), or the second dimension (if `data_format` starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". |
| `dilations` | Alias for dilation\_rate |
| Returns |
| Tensor of rank N+2, of shape [batch\_size] + output\_spatial\_shape + [num\_channels] if data\_format is None or does not start with "NC", or [batch\_size, num\_channels] + output\_spatial\_shape if data\_format starts with "NC", where `output_spatial_shape` depends on the value of padding: If padding = "SAME": output\_spatial\_shape[i] = ceil(input\_spatial\_shape[i] / strides[i]) If padding = "VALID": output\_spatial\_shape[i] = ceil((input\_spatial\_shape[i] - (window\_shape[i] - 1) \* dilation\_rate[i]) / strides[i]). |
| Raises |
| `ValueError` | if arguments are invalid. |
tensorflow tf.compat.v1.nn.conv1d tf.compat.v1.nn.conv1d
======================
Computes a 1-D convolution of input with rank `>=3` and a `3-D` filter. (deprecated argument values) (deprecated argument values)
```
tf.compat.v1.nn.conv1d(
value=None,
filters=None,
stride=None,
padding=None,
use_cudnn_on_gpu=None,
data_format=None,
name=None,
input=None,
dilations=None
)
```
Given an input tensor of shape `batch_shape + [in_width, in_channels]` if `data_format` is `"NWC"`, or `batch_shape + [in_channels, in_width]` if `data_format` is `"NCW"`, and a filter / kernel tensor of shape `[filter_width, in_channels, out_channels]`, this op reshapes the arguments to pass them to `conv2d` to perform the equivalent convolution operation.
Internally, this op reshapes the input tensors and invokes [`tf.nn.conv2d`](../../../nn/conv2d). For example, if `data_format` does not start with "NC", a tensor of shape `batch_shape + [in_width, in_channels]` is reshaped to `batch_shape + [1, in_width, in_channels]`, and the filter is reshaped to `[1, filter_width, in_channels, out_channels]`. The result is then reshaped back to `batch_shape + [out_width, out_channels]` (where out\_width is a function of the stride and padding as in conv2d) and returned to the caller.
| Args |
| `value` | A Tensor of rank at least 3. Must be of type `float16`, `float32`, or `float64`. |
| `filters` | A Tensor of rank at least 3. Must have the same type as `value`. |
| `stride` | An int or list of `ints` that has length `1` or `3`. The number of entries by which the filter is moved right at each step. |
| `padding` | 'SAME' or 'VALID' |
| `use_cudnn_on_gpu` | An optional `bool`. Defaults to `True`. |
| `data_format` | An optional `string` from `"NWC", "NCW"`. Defaults to `"NWC"`, the data is stored in the order of `batch_shape + [in_width, in_channels]`. The `"NCW"` format stores data as `batch_shape + [in_channels, in_width]`. |
| `name` | A name for the operation (optional). |
| `input` | Alias for value. |
| `dilations` | An int or list of `ints` that has length `1` or `3` which defaults to 1. The dilation factor for each dimension of input. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. Dilations in the batch and depth dimensions must be 1. |
| Returns |
| A `Tensor`. Has the same type as input. |
| Raises |
| `ValueError` | if `data_format` is invalid. |
tensorflow tf.compat.v1.nn.convolution tf.compat.v1.nn.convolution
===========================
Computes sums of N-D convolutions (actually cross-correlation).
```
tf.compat.v1.nn.convolution(
input,
filter,
padding,
strides=None,
dilation_rate=None,
name=None,
data_format=None,
filters=None,
dilations=None
)
```
This also supports either output striding via the optional `strides` parameter or atrous convolution (also known as convolution with holes or dilated convolution, based on the French word "trous" meaning holes in English) via the optional `dilation_rate` parameter. Currently, however, output striding is not supported for atrous convolutions.
Specifically, in the case that `data_format` does not start with "NC", given a rank (N+2) `input` Tensor of shape
[num\_batches, input\_spatial\_shape[0], ..., input\_spatial\_shape[N-1], num\_input\_channels],
a rank (N+2) `filter` Tensor of shape
[spatial\_filter\_shape[0], ..., spatial\_filter\_shape[N-1], num\_input\_channels, num\_output\_channels],
an optional `dilation_rate` tensor of shape N (defaults to `[1]*N`) specifying the filter upsampling/input downsampling rate, and an optional list of N `strides` (defaults to `[1]*N`), this computes for each N-D spatial output position `(x[0], ..., x[N-1])`:
```
output[b, x[0], ..., x[N-1], k] =
sum_{z[0], ..., z[N-1], q}
filter[z[0], ..., z[N-1], q, k] *
padded_input[b,
x[0]*strides[0] + dilation_rate[0]*z[0],
...,
x[N-1]*strides[N-1] + dilation_rate[N-1]*z[N-1],
q]
```
where b is the index into the batch, k is the output channel number, q is the input channel number, and z is the N-D spatial offset within the filter. Here, `padded_input` is obtained by zero padding the input using an effective spatial filter shape of `(spatial_filter_shape-1) * dilation_rate + 1` and output striding `strides`.
In the case that `data_format` does start with `"NC"`, the `input` and output (but not the `filter`) are simply transposed as follows:
```
convolution(input, data_format, **kwargs) =
tf.transpose(convolution(tf.transpose(input, [0] + range(2,N+2) + [1]),
**kwargs),
[0, N+1] + range(1, N+1))
```
It is required that 1 <= N <= 3.
| Args |
| `input` | An (N+2)-D `Tensor` of type `T`, of shape `[batch_size] + input_spatial_shape + [in_channels]` if data\_format does not start with "NC" (default), or `[batch_size, in_channels] + input_spatial_shape` if data\_format starts with "NC". |
| `filter` | An (N+2)-D `Tensor` with the same type as `input` and shape `spatial_filter_shape + [in_channels, out_channels]`. |
| `padding` | A string, either `"VALID"` or `"SAME"`. The padding algorithm. `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input when the strides are 1. See [here](https://www.tensorflow.org/api_docs/python/tf/nn#notes_on_padding_2) for more information. |
| `strides` | Optional. Sequence of N ints >= 1. Specifies the output stride. Defaults to `[1]*N`. If any value of strides is > 1, then all values of dilation\_rate must be 1. |
| `dilation_rate` | Optional. Sequence of N ints >= 1. Specifies the filter upsampling/input downsampling rate. In the literature, the same parameter is sometimes called `input stride` or `dilation`. The effective filter size used for the convolution will be `spatial_filter_shape + (spatial_filter_shape - 1) * (rate - 1)`, obtained by inserting (dilation\_rate[i]-1) zeros between consecutive elements of the original filter in each spatial dimension i. If any value of dilation\_rate is > 1, then all values of strides must be 1. |
| `name` | Optional name for the returned tensor. |
| `data_format` | A string or None. Specifies whether the channel dimension of the `input` and output is the last dimension (default, or if `data_format` does not start with "NC"), or the second dimension (if `data_format` starts with "NC"). For N=1, the valid values are "NWC" (default) and "NCW". For N=2, the valid values are "NHWC" (default) and "NCHW". For N=3, the valid values are "NDHWC" (default) and "NCDHW". |
| Returns |
| A `Tensor` with the same type as `input` of shape
```
`[batch_size] + output_spatial_shape + [out_channels]`
```
if data\_format is None or does not start with "NC", or
```
`[batch_size, out_channels] + output_spatial_shape`
```
if data\_format starts with "NC", where `output_spatial_shape` depends on the value of `padding`. If padding == "SAME": output\_spatial\_shape[i] = ceil(input\_spatial\_shape[i] / strides[i]) If padding == "VALID": output\_spatial\_shape[i] = ceil((input\_spatial\_shape[i] - (spatial\_filter\_shape[i]-1) \* dilation\_rate[i]) / strides[i]). |
| Raises |
| `ValueError` | If input/output depth does not match `filter` shape, if padding is other than `"VALID"` or `"SAME"`, or if data\_format is invalid. |
tensorflow tf.compat.v1.nn.bidirectional_dynamic_rnn tf.compat.v1.nn.bidirectional\_dynamic\_rnn
===========================================
Creates a dynamic version of bidirectional recurrent neural network. (deprecated)
```
tf.compat.v1.nn.bidirectional_dynamic_rnn(
cell_fw,
cell_bw,
inputs,
sequence_length=None,
initial_state_fw=None,
initial_state_bw=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None
)
```
Takes input and builds independent forward and backward RNNs. The input\_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given.
| Args |
| `cell_fw` | An instance of RNNCell, to be used for forward direction. |
| `cell_bw` | An instance of RNNCell, to be used for backward direction. |
| `inputs` | The RNN inputs. If time\_major == False (default), this must be a tensor of shape: `[batch_size, max_time, ...]`, or a nested tuple of such elements. If time\_major == True, this must be a tensor of shape: `[max_time, batch_size, ...]`, or a nested tuple of such elements. |
| `sequence_length` | (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences in the batch. If not provided, all batch entries are assumed to be full sequences; and time reversal is applied from time `0` to `max_time` for each sequence. |
| `initial_state_fw` | (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size, cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. |
| `initial_state_bw` | (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. |
| `dtype` | (optional) The data type for the initial states and expected output. Required if initial\_states are not provided or RNN states have a heterogeneous dtype. |
| `parallel_iterations` | (Default: 32). The number of iterations to run in parallel. Those operations which do not have any temporal dependency and can be run in parallel, will be. This parameter trades off time for space. Values >> 1 use more memory but take less time, while smaller values use less memory but computations take longer. |
| `swap_memory` | Transparently swap the tensors produced in forward inference but needed for back prop from GPU to CPU. This allows training RNNs which would typically not fit on a single GPU, with very minimal (or no) performance penalty. |
| `time_major` | The shape format of the `inputs` and `outputs` Tensors. If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. |
| `scope` | VariableScope for the created subgraph; defaults to "bidirectional\_rnn" |
| Returns |
| A tuple (outputs, output\_states) where: outputs: A tuple (output\_fw, output\_bw) containing the forward and the backward rnn output `Tensor`. If time\_major == False (default), output\_fw will be a `Tensor` shaped: `[batch_size, max_time, cell_fw.output_size]` and output\_bw will be a `Tensor` shaped: `[batch_size, max_time, cell_bw.output_size]`. If time\_major == True, output\_fw will be a `Tensor` shaped: `[max_time, batch_size, cell_fw.output_size]` and output\_bw will be a `Tensor` shaped: `[max_time, batch_size, cell_bw.output_size]`. It returns a tuple instead of a single concatenated `Tensor`, unlike in the `bidirectional_rnn`. If the concatenated one is preferred, the forward and backward outputs can be concatenated as [`tf.concat(outputs, 2)`](../../../concat). output\_states: A tuple (output\_state\_fw, output\_state\_bw) containing the forward and the backward final states of bidirectional rnn. |
| Raises |
| `TypeError` | If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. |
| programming_docs |
tensorflow tf.compat.v1.nn.erosion2d tf.compat.v1.nn.erosion2d
=========================
Computes the grayscale erosion of 4-D `value` and 3-D `kernel` tensors.
```
tf.compat.v1.nn.erosion2d(
value, kernel, strides, rates, padding, name=None
)
```
The `value` tensor has shape `[batch, in_height, in_width, depth]` and the `kernel` tensor has shape `[kernel_height, kernel_width, depth]`, i.e., each input channel is processed independently of the others with its own structuring function. The `output` tensor has shape `[batch, out_height, out_width, depth]`. The spatial dimensions of the output tensor depend on the `padding` algorithm. We currently only support the default "NHWC" `data_format`.
In detail, the grayscale morphological 2-D erosion is given by:
```
output[b, y, x, c] =
min_{dy, dx} value[b,
strides[1] * y - rates[1] * dy,
strides[2] * x - rates[2] * dx,
c] -
kernel[dy, dx, c]
```
Duality: The erosion of `value` by the `kernel` is equal to the negation of the dilation of `-value` by the reflected `kernel`.
| Args |
| `value` | A `Tensor`. 4-D with shape `[batch, in_height, in_width, depth]`. |
| `kernel` | A `Tensor`. Must have the same type as `value`. 3-D with shape `[kernel_height, kernel_width, depth]`. |
| `strides` | A list of `ints` that has length `>= 4`. 1-D of length 4. The stride of the sliding window for each dimension of the input tensor. Must be: `[1, stride_height, stride_width, 1]`. |
| `rates` | A list of `ints` that has length `>= 4`. 1-D of length 4. The input stride for atrous morphological dilation. Must be: `[1, rate_height, rate_width, 1]`. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `name` | A name for the operation (optional). If not specified "erosion2d" is used. |
| Returns |
| A `Tensor`. Has the same type as `value`. 4-D with shape `[batch, out_height, out_width, depth]`. |
| Raises |
| `ValueError` | If the `value` depth does not match `kernel`' shape, or if padding is other than `'VALID'` or `'SAME'`. |
tensorflow tf.compat.v1.nn.static_state_saving_rnn tf.compat.v1.nn.static\_state\_saving\_rnn
==========================================
RNN that accepts a state saver for time-truncated RNN calculation. (deprecated)
```
tf.compat.v1.nn.static_state_saving_rnn(
cell, inputs, state_saver, state_name, sequence_length=None, scope=None
)
```
| Args |
| `cell` | An instance of `RNNCell`. |
| `inputs` | A length T list of inputs, each a `Tensor` of shape `[batch_size, input_size]`. |
| `state_saver` | A state saver object with methods `state` and `save_state`. |
| `state_name` | Python string or tuple of strings. The name to use with the state\_saver. If the cell returns tuples of states (i.e., `cell.state_size` is a tuple) then `state_name` should be a tuple of strings having the same length as `cell.state_size`. Otherwise it should be a single string. |
| `sequence_length` | (optional) An int32/int64 vector size [batch\_size]. See the documentation for rnn() for more details about sequence\_length. |
| `scope` | VariableScope for the created subgraph; defaults to "rnn". |
| Returns |
| A pair (outputs, state) where: outputs is a length T list of outputs (one for each input) states is the final state |
| Raises |
| `TypeError` | If `cell` is not an instance of RNNCell. |
| `ValueError` | If `inputs` is `None` or an empty list, or if the arity and type of `state_name` does not match that of `cell.state_size`. |
tensorflow tf.compat.v1.nn.fused_batch_norm tf.compat.v1.nn.fused\_batch\_norm
==================================
Batch normalization.
```
tf.compat.v1.nn.fused_batch_norm(
x,
scale,
offset,
mean=None,
variance=None,
epsilon=0.001,
data_format='NHWC',
is_training=True,
name=None,
exponential_avg_factor=1.0
)
```
See Source: [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift; S. Ioffe, C. Szegedy](http://arxiv.org/abs/1502.03167).
| Args |
| `x` | Input `Tensor` of 4 or 5 dimensions. |
| `scale` | A `Tensor` of 1 dimension for scaling. |
| `offset` | A `Tensor` of 1 dimension for bias. |
| `mean` | A `Tensor` of 1 dimension for population mean. The shape and meaning of this argument depends on the value of is\_training and exponential\_avg\_factor as follows: is\_trainingFalse (inference): Mean must be a `Tensor` of the same shape as scale containing the estimated population mean computed during training. is\_trainingTrue and exponential\_avg\_factor == 1.0: Mean must be None. is\_trainingTrue and exponential\_avg\_factor != 1.0: Mean must be a `Tensor` of the same shape as scale containing the exponential running mean. |
| `variance` | A `Tensor` of 1 dimension for population variance. The shape and meaning of this argument depends on the value of is\_training and exponential\_avg\_factor as follows: is\_trainingFalse (inference): Variance must be a `Tensor` of the same shape as scale containing the estimated population variance computed during training. is\_training==True and exponential\_avg\_factor == 1.0: Variance must be None. is\_training==True and exponential\_avg\_factor != 1.0: Variance must be a `Tensor` of the same shape as scale containing the exponential running variance. |
| `epsilon` | A small float number added to the variance of x. |
| `data_format` | The data format for x. Support "NHWC" (default) or "NCHW" for 4D tenors and "NDHWC" or "NCDHW" for 5D tensors. |
| `is_training` | A bool value to specify if the operation is used for training or inference. |
| `name` | A name for this operation (optional). |
| `exponential_avg_factor` | A float number (usually between 0 and 1) used for controlling the decay of the running population average of mean and variance. If set to 1.0, the current batch average is returned. |
| Returns |
| `y` | A 4D or 5D Tensor for the normalized, scaled, offsetted x. |
| `running_mean` | A 1D Tensor for the exponential running mean of x. The output value is (1 - exponential\_avg\_factor) \* mean + exponential\_avg\_factor \* batch\_mean), where batch\_mean is the mean of the current batch in x. |
| `running_var` | A 1D Tensor for the exponential running variance The output value is (1 - exponential\_avg\_factor) \* variance + exponential\_avg\_factor \* batch\_variance), where batch\_variance is the variance of the current batch in x. |
#### References:
Batch Normalization - Accelerating Deep Network Training by Reducing Internal Covariate Shift: [Ioffe et al., 2015](http://proceedings.mlr.press/v37/ioffe15.html) ([pdf](http://proceedings.mlr.press/v37/ioffe15.pdf))
tensorflow tf.compat.v1.nn.fractional_avg_pool tf.compat.v1.nn.fractional\_avg\_pool
=====================================
Performs fractional average pooling on the input. (deprecated)
```
tf.compat.v1.nn.fractional_avg_pool(
value,
pooling_ratio,
pseudo_random=False,
overlapping=False,
deterministic=False,
seed=0,
seed2=0,
name=None
)
```
This is a deprecated version of `fractional_avg_pool`.
Fractional average pooling is similar to Fractional max pooling in the pooling region generation step. The only difference is that after pooling regions are generated, a mean operation is performed instead of a max operation in each pooling region.
| Args |
| `value` | A `Tensor`. 4-D with shape `[batch, height, width, channels]`. |
| `pooling_ratio` | A list of `floats` that has length >= 4. Pooling ratio for each dimension of `value`, currently only supports row and col dimension and should be >= 1.0. For example, a valid pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions respectively. |
| `pseudo_random` | An optional `bool`. Defaults to `False`. When set to `True`, generates the pooling sequence in a pseudorandom fashion, otherwise, in a random fashion. Check paper (Graham, 2015) for difference between pseudorandom and random. |
| `overlapping` | An optional `bool`. Defaults to `False`. When set to `True`, it means when pooling, the values at the boundary of adjacent pooling cells are used by both cells. For example: `index 0 1 2 3 4` `value 20 5 16 3 7` If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. The result would be [20, 16] for fractional avg pooling. |
| `deterministic` | An optional `bool`. Deprecated; use `fractional_avg_pool_v2` instead. |
| `seed` | An optional `int`. Defaults to `0`. If set to be non-zero, the random number generator is seeded by the given seed. Otherwise it is seeded by a random seed. |
| `seed2` | An optional `int`. Deprecated; use `fractional_avg_pool_v2` instead. |
| `name` | A name for the operation (optional). |
| Returns |
A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, `col_pooling_sequence`). output: Output `Tensor` after fractional avg pooling. Has the same type as `value`. row\_pooling\_sequence: A `Tensor` of type `int64`. col\_pooling\_sequence: A `Tensor` of type `int64`.
#### References:
Fractional Max-Pooling: [Graham, 2015](https://arxiv.org/abs/1412.6071) ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
tensorflow tf.compat.v1.nn.sampled_softmax_loss tf.compat.v1.nn.sampled\_softmax\_loss
======================================
Computes and returns the sampled softmax training loss.
```
tf.compat.v1.nn.sampled_softmax_loss(
weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=True,
partition_strategy='mod',
name='sampled_softmax_loss',
seed=None
)
```
This is a faster way to train a softmax classifier over a huge number of classes.
This operation is for training only. It is generally an underestimate of the full softmax loss.
A common use case is to use this method for training, and calculate the full softmax loss for evaluation or inference. In this case, you must set `partition_strategy="div"` for the two losses to be consistent, as in the following example:
```
if mode == "train":
loss = tf.nn.sampled_softmax_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.softmax_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
```
See our Candidate Sampling Algorithms Reference ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)). Also see Section 3 of (Jean et al., 2014) for the math.
| Args |
| `weights` | A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` objects whose concatenation along dimension 0 has shape [num\_classes, dim]. The (possibly-sharded) class embeddings. |
| `biases` | A `Tensor` of shape `[num_classes]`. The class biases. |
| `labels` | A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The target classes. Note that this format differs from the `labels` argument of [`nn.softmax_cross_entropy_with_logits`](https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits). |
| `inputs` | A `Tensor` of shape `[batch_size, dim]`. The forward activations of the input network. |
| `num_sampled` | An `int`. The number of classes to randomly sample per batch. |
| `num_classes` | An `int`. The number of possible classes. |
| `num_true` | An `int`. The number of target classes per training example. |
| `sampled_values` | a tuple of (`sampled_candidates`, `true_expected_count`, `sampled_expected_count`) returned by a `*_candidate_sampler` function. (if None, we default to `log_uniform_candidate_sampler`) |
| `remove_accidental_hits` | A `bool`. whether to remove "accidental hits" where a sampled class equals one of the target classes. Default is True. |
| `partition_strategy` | A string specifying the partitioning strategy, relevant if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. |
| `name` | A name for the operation (optional). |
| `seed` | random seed for candidate sampling. Default to None, which doesn't set the op-level random seed for candidate sampling. |
| Returns |
| A `batch_size` 1-D tensor of per-example sampled softmax losses. |
#### References:
On Using Very Large Target Vocabulary for Neural Machine Translation: [Jean et al., 2014](https://aclanthology.coli.uni-saarland.de/papers/P15-1001/p15-1001) ([pdf](http://aclweb.org/anthology/P15-1001))
tensorflow tf.compat.v1.nn.sufficient_statistics tf.compat.v1.nn.sufficient\_statistics
======================================
Calculate the sufficient statistics for the mean and variance of `x`.
```
tf.compat.v1.nn.sufficient_statistics(
x, axes, shift=None, keep_dims=None, name=None, keepdims=None
)
```
These sufficient statistics are computed using the one pass algorithm on an input that's optionally shifted. See: <https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Computing_shifted_data>
#### For example:
```
t = [[1, 2, 3], [4, 5, 6]]
sufficient_statistics(t, [1])
(<tf.Tensor: shape=(), dtype=int32, numpy=3>, <tf.Tensor: shape=(2,),
dtype=int32, numpy=array([ 6, 15], dtype=int32)>, <tf.Tensor: shape=(2,),
dtype=int32, numpy=array([14, 77], dtype=int32)>, None)
sufficient_statistics(t, [-1])
(<tf.Tensor: shape=(), dtype=int32, numpy=3>, <tf.Tensor: shape=(2,),
dtype=int32, numpy=array([ 6, 15], dtype=int32)>, <tf.Tensor: shape=(2,),
dtype=int32, numpy=array([14, 77], dtype=int32)>, None)
```
| Args |
| `x` | A `Tensor`. |
| `axes` | Array of ints. Axes along which to compute mean and variance. As in Python, the axes can also be negative numbers. A negative axis is interpreted as counting from the end of the rank, i.e., axis + rank(values)-th dimension. |
| `shift` | A `Tensor` containing the value by which to shift the data for numerical stability, or `None` if no shift is to be performed. A shift close to the true mean provides the most numerically stable results. |
| `keep_dims` | produce statistics with the same dimensionality as the input. |
| `name` | Name used to scope the operations that compute the sufficient stats. |
| `keepdims` | Alias for keep\_dims. |
| Returns |
| Four `Tensor` objects of the same type as `x`: * the count (number of elements to average over).
* the (possibly shifted) sum of the elements in the array.
* the (possibly shifted) sum of squares of the elements in the array.
* the shift by which the mean must be corrected or None if `shift` is None.
|
tensorflow tf.compat.v1.nn.weighted_moments tf.compat.v1.nn.weighted\_moments
=================================
Returns the frequency-weighted mean and variance of `x`.
```
tf.compat.v1.nn.weighted_moments(
x, axes, frequency_weights, name=None, keep_dims=None, keepdims=None
)
```
| Args |
| `x` | A tensor. |
| `axes` | 1-d tensor of int32 values; these are the axes along which to compute mean and variance. |
| `frequency_weights` | A tensor of positive weights which can be broadcast with x. |
| `name` | Name used to scope the operation. |
| `keep_dims` | Produce moments with the same dimensionality as the input. |
| `keepdims` | Alias of keep\_dims. |
| Returns |
| Two tensors: `weighted_mean` and `weighted_variance`. |
tensorflow tf.compat.v1.nn.sparse_softmax_cross_entropy_with_logits tf.compat.v1.nn.sparse\_softmax\_cross\_entropy\_with\_logits
=============================================================
Computes sparse softmax cross entropy between `logits` and `labels`.
```
tf.compat.v1.nn.sparse_softmax_cross_entropy_with_logits(
_sentinel=None, labels=None, logits=None, name=None
)
```
Measures the probability error in discrete classification tasks in which the classes are mutually exclusive (each entry is in exactly one class). For example, each CIFAR-10 image is labeled with one and only one label: an image can be a dog or a truck, but not both.
>
> **Note:** For this operation, the probability of a given label is considered exclusive. That is, soft classes are not allowed, and the `labels` vector must provide a single specific index for the true class for each row of `logits` (each minibatch entry). For soft softmax classification with a probability distribution for each entry, see `softmax_cross_entropy_with_logits_v2`.
>
A common use case is to have logits of shape `[batch_size, num_classes]` and have labels of shape `[batch_size]`, but higher dimensions are supported, in which case the `dim`-th dimension is assumed to be of size `num_classes`. `logits` must have the dtype of `float16`, `float32`, or `float64`, and `labels` must have the dtype of `int32` or `int64`.
**Note that to avoid confusion, it is required to pass only named arguments to this function.**
| Args |
| `_sentinel` | Used to prevent positional parameters. Internal, do not use. |
| `labels` | `Tensor` of shape `[d_0, d_1, ..., d_{r-1}]` (where `r` is rank of `labels` and result) and dtype `int32` or `int64`. Each entry in `labels` must be an index in `[0, num_classes)`. Other values will raise an exception when this op is run on CPU, and return `NaN` for corresponding loss and gradient rows on GPU. |
| `logits` | Per-label activations (typically a linear output) of shape `[d_0, d_1, ..., d_{r-1}, num_classes]` and dtype `float16`, `float32`, or `float64`. These activation energies are interpreted as unnormalized log probabilities. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of the same shape as `labels` and of the same type as `logits` with the softmax cross entropy loss. |
| Raises |
| `ValueError` | If logits are scalars (need to have rank >= 1) or if the rank of the labels is not equal to the rank of the logits minus one. |
tensorflow tf.compat.v1.nn.conv2d_transpose tf.compat.v1.nn.conv2d\_transpose
=================================
The transpose of `conv2d`.
```
tf.compat.v1.nn.conv2d_transpose(
value=None,
filter=None,
output_shape=None,
strides=None,
padding='SAME',
data_format='NHWC',
name=None,
input=None,
filters=None,
dilations=None
)
```
This operation is sometimes called "deconvolution" after (Zeiler et al., 2010), but is really the transpose (gradient) of `conv2d` rather than an actual deconvolution.
| Args |
| `value` | A 4-D `Tensor` of type `float` and shape `[batch, height, width, in_channels]` for `NHWC` data format or `[batch, in_channels, height, width]` for `NCHW` data format. |
| `filter` | A 4-D `Tensor` with the same type as `value` and shape `[height, width, output_channels, in_channels]`. `filter`'s `in_channels` dimension must match that of `value`. |
| `output_shape` | A 1-D `Tensor` representing the output shape of the deconvolution op. |
| `strides` | An int or list of `ints` that has length `1`, `2` or `4`. The stride of the sliding window for each dimension of `input`. If a single value is given it is replicated in the `H` and `W` dimension. By default the `N` and `C` dimensions are set to 0. The dimension order is determined by the value of `data_format`, see below for details. |
| `padding` | A string, either `'VALID'` or `'SAME'`. The padding algorithm. See the "returns" section of [`tf.nn.convolution`](../../../nn/convolution) for details. |
| `data_format` | A string. 'NHWC' and 'NCHW' are supported. |
| `name` | Optional name for the returned tensor. |
| `input` | Alias for value. |
| `filters` | Alias for filter. |
| `dilations` | An int or list of `ints` that has length `1`, `2` or `4`, defaults to 1. The dilation factor for each dimension of`input`. If a single value is given it is replicated in the `H` and `W` dimension. By default the `N` and `C` dimensions are set to 1. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions if a 4-d tensor must be 1. |
| Returns |
| A `Tensor` with the same type as `value`. |
| Raises |
| `ValueError` | If input/output depth does not match `filter`'s shape, or if padding is other than `'VALID'` or `'SAME'`. |
#### References:
Deconvolutional Networks: [Zeiler et al., 2010](https://ieeexplore.ieee.org/abstract/document/5539957) ([pdf](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.232.4023&rep=rep1&type=pdf))
| programming_docs |
tensorflow tf.compat.v1.nn.static_rnn tf.compat.v1.nn.static\_rnn
===========================
Creates a recurrent neural network specified by RNNCell `cell`. (deprecated)
```
tf.compat.v1.nn.static_rnn(
cell,
inputs,
initial_state=None,
dtype=None,
sequence_length=None,
scope=None
)
```
The simplest form of RNN network generated is:
```
state = cell.zero_state(...)
outputs = []
for input_ in inputs:
output, state = cell(input_, state)
outputs.append(output)
return (outputs, state)
```
However, a few other options are available:
An initial state can be provided. If the sequence\_length vector is provided, dynamic calculation is performed. This method of calculation does not compute the RNN steps past the maximum sequence length of the minibatch (thus saving computational time), and properly propagates the state at an example's sequence length to the final state output.
The dynamic calculation performed is, at time `t` for batch row `b`,
```
(output, state)(b, t) =
(t >= sequence_length(b))
? (zeros(cell.output_size), states(b, sequence_length(b) - 1))
: cell(input(b, t), state(b, t - 1))
```
| Args |
| `cell` | An instance of RNNCell. |
| `inputs` | A length T list of inputs, each a `Tensor` of shape `[batch_size, input_size]`, or a nested tuple of such elements. |
| `initial_state` | (optional) An initial state for the RNN. If `cell.state_size` is an integer, this must be a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`. If `cell.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell.state_size`. |
| `dtype` | (optional) The data type for the initial state and expected output. Required if initial\_state is not provided or RNN state has a heterogeneous dtype. |
| `sequence_length` | Specifies the length of each sequence in inputs. An int32 or int64 vector (tensor) size `[batch_size]`, values in `[0, T)`. |
| `scope` | VariableScope for the created subgraph; defaults to "rnn". |
| Returns |
| A pair (outputs, state) where: * outputs is a length T list of outputs (one for each input), or a nested tuple of such elements.
* state is the final state
|
| Raises |
| `TypeError` | If `cell` is not an instance of RNNCell. |
| `ValueError` | If `inputs` is `None` or an empty list, or if the input depth (column size) cannot be inferred from inputs via shape inference. |
tensorflow tf.compat.v1.nn.dynamic_rnn tf.compat.v1.nn.dynamic\_rnn
============================
Creates a recurrent neural network specified by RNNCell `cell`. (deprecated)
```
tf.compat.v1.nn.dynamic_rnn(
cell,
inputs,
sequence_length=None,
initial_state=None,
dtype=None,
parallel_iterations=None,
swap_memory=False,
time_major=False,
scope=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.nn.dynamic_rnn`](dynamic_rnn) is not compatible with eager execution and [`tf.function`](../../../function). Please use [`tf.keras.layers.RNN`](../../../keras/layers/rnn) instead for TF2 migration. Take LSTM as an example, you can instantiate a [`tf.keras.layers.RNN`](../../../keras/layers/rnn) layer with [`tf.keras.layers.LSTMCell`](../../../keras/layers/lstmcell), or directly via [`tf.keras.layers.LSTM`](../../../keras/layers/lstm). Once the keras layer is created, you can get the output and states by calling the layer with input and states. Please refer to [this guide](https://www.tensorflow.org/guide/keras/rnn) for more details about Keras RNN. You can also find more details about the difference and comparison between Keras RNN and TF compat v1 rnn in [this document](https://github.com/tensorflow/community/blob/master/rfcs/20180920-unify-rnn-interface.md)
#### Structural Mapping to Native TF2
Before:
```
# create 2 LSTMCells
rnn_layers = [tf.compat.v1.nn.rnn_cell.LSTMCell(size) for size in [128, 256]]
# create a RNN cell composed sequentially of a number of RNNCells
multi_rnn_cell = tf.compat.v1.nn.rnn_cell.MultiRNNCell(rnn_layers)
# 'outputs' is a tensor of shape [batch_size, max_time, 256]
# 'state' is a N-tuple where N is the number of LSTMCells containing a
# tf.nn.rnn_cell.LSTMStateTuple for each cell
outputs, state = tf.compat.v1.nn.dynamic_rnn(cell=multi_rnn_cell,
inputs=data,
dtype=tf.float32)
```
After:
```
# RNN layer can take a list of cells, which will then stack them together.
# By default, keras RNN will only return the last timestep output and will not
# return states. If you need whole time sequence output as well as the states,
# you can set `return_sequences` and `return_state` to True.
rnn_layer = tf.keras.layers.RNN([tf.keras.layers.LSTMCell(128),
tf.keras.layers.LSTMCell(256)],
return_sequences=True,
return_state=True)
outputs, output_states = rnn_layer(inputs, states)
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `cell` | `cell` | In the RNN layer constructor |
| `inputs` | `inputs` | In the RNN layer `__call__` |
| `sequence_length` | Not used | Adding masking layer before RNN : to achieve the same result. |
| `initial_state` | `initial_state` | In the RNN layer `__call__` |
| `dtype` | `dtype` | In the RNN layer constructor |
| `parallel_iterations` | Not supported | |
| `swap_memory` | Not supported | |
| `time_major` | `time_major` | In the RNN layer constructor |
| `scope` | Not supported | |
Description
-----------
Performs fully dynamic unrolling of `inputs`.
#### Example:
```
# create a BasicRNNCell
rnn_cell = tf.compat.v1.nn.rnn_cell.BasicRNNCell(hidden_size)
# 'outputs' is a tensor of shape [batch_size, max_time, cell_state_size]
# defining initial state
initial_state = rnn_cell.zero_state(batch_size, dtype=tf.float32)
# 'state' is a tensor of shape [batch_size, cell_state_size]
outputs, state = tf.compat.v1.nn.dynamic_rnn(rnn_cell, input_data,
initial_state=initial_state,
dtype=tf.float32)
```
```
# create 2 LSTMCells
rnn_layers = [tf.compat.v1.nn.rnn_cell.LSTMCell(size) for size in [128, 256]]
# create a RNN cell composed sequentially of a number of RNNCells
multi_rnn_cell = tf.compat.v1.nn.rnn_cell.MultiRNNCell(rnn_layers)
# 'outputs' is a tensor of shape [batch_size, max_time, 256]
# 'state' is a N-tuple where N is the number of LSTMCells containing a
# tf.nn.rnn_cell.LSTMStateTuple for each cell
outputs, state = tf.compat.v1.nn.dynamic_rnn(cell=multi_rnn_cell,
inputs=data,
dtype=tf.float32)
```
| Args |
| `cell` | An instance of RNNCell. |
| `inputs` | The RNN inputs. If `time_major == False` (default), this must be a `Tensor` of shape: `[batch_size, max_time, ...]`, or a nested tuple of such elements. If `time_major == True`, this must be a `Tensor` of shape: `[max_time, batch_size, ...]`, or a nested tuple of such elements. This may also be a (possibly nested) tuple of Tensors satisfying this property. The first two dimensions must match across all the inputs, but otherwise the ranks and other shape components may differ. In this case, input to `cell` at each time-step will replicate the structure of these tuples, except for the time dimension (from which the time is taken). The input to `cell` at each time step will be a `Tensor` or (possibly nested) tuple of Tensors each with dimensions `[batch_size, ...]`. |
| `sequence_length` | (optional) An int32/int64 vector sized `[batch_size]`. Used to copy-through state and zero-out outputs when past a batch element's sequence length. This parameter enables users to extract the last valid state and properly padded outputs, so it is provided for correctness. |
| `initial_state` | (optional) An initial state for the RNN. If `cell.state_size` is an integer, this must be a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`. If `cell.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell.state_size`. |
| `dtype` | (optional) The data type for the initial state and expected output. Required if initial\_state is not provided or RNN state has a heterogeneous dtype. |
| `parallel_iterations` | (Default: 32). The number of iterations to run in parallel. Those operations which do not have any temporal dependency and can be run in parallel, will be. This parameter trades off time for space. Values >> 1 use more memory but take less time, while smaller values use less memory but computations take longer. |
| `swap_memory` | Transparently swap the tensors produced in forward inference but needed for back prop from GPU to CPU. This allows training RNNs which would typically not fit on a single GPU, with very minimal (or no) performance penalty. |
| `time_major` | The shape format of the `inputs` and `outputs` Tensors. If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`. If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`. Using `time_major = True` is a bit more efficient because it avoids transposes at the beginning and end of the RNN calculation. However, most TensorFlow data is batch-major, so by default this function accepts input and emits output in batch-major form. |
| `scope` | VariableScope for the created subgraph; defaults to "rnn". |
| Returns |
| A pair (outputs, state) where: |
| `outputs` | The RNN output `Tensor`. If time\_major == False (default), this will be a `Tensor` shaped: `[batch_size, max_time, cell.output_size]`. If time\_major == True, this will be a `Tensor` shaped: `[max_time, batch_size, cell.output_size]`. Note, if `cell.output_size` is a (possibly nested) tuple of integers or `TensorShape` objects, then `outputs` will be a tuple having the same structure as `cell.output_size`, containing Tensors having shapes corresponding to the shape data in `cell.output_size`. |
| `state` | The final state. If `cell.state_size` is an int, this will be shaped `[batch_size, cell.state_size]`. If it is a `TensorShape`, this will be shaped `[batch_size] + cell.state_size`. If it is a (possibly nested) tuple of ints or `TensorShape`, this will be a tuple having the corresponding shapes. If cells are `LSTMCells` `state` will be a tuple containing a `LSTMStateTuple` for each cell. |
| Raises |
| `TypeError` | If `cell` is not an instance of RNNCell. |
| `ValueError` | If inputs is None or an empty list. |
tensorflow tf.compat.v1.nn.moments tf.compat.v1.nn.moments
=======================
Calculate the mean and variance of `x`.
```
tf.compat.v1.nn.moments(
x, axes, shift=None, name=None, keep_dims=None, keepdims=None
)
```
The mean and variance are calculated by aggregating the contents of `x` across `axes`. If `x` is 1-D and `axes = [0]` this is just the mean and variance of a vector.
>
> **Note:** shift is currently not used; the true mean is computed and used.
>
When using these moments for batch normalization (see [`tf.nn.batch_normalization`](../../../nn/batch_normalization)):
* for so-called "global normalization", used with convolutional filters with shape `[batch, height, width, depth]`, pass `axes=[0, 1, 2]`.
* for simple batch normalization pass `axes=[0]` (batch only).
| Args |
| `x` | A `Tensor`. |
| `axes` | Array of ints. Axes along which to compute mean and variance. |
| `shift` | Not used in the current implementation |
| `name` | Name used to scope the operations that compute the moments. |
| `keep_dims` | produce moments with the same dimensionality as the input. |
| `keepdims` | Alias to keep\_dims. |
| Returns |
| Two `Tensor` objects: `mean` and `variance`. |
tensorflow tf.compat.v1.nn.quantized_relu_x tf.compat.v1.nn.quantized\_relu\_x
==================================
Computes Quantized Rectified Linear X: `min(max(features, 0), max_value)`
```
tf.compat.v1.nn.quantized_relu_x(
features,
max_value,
min_features,
max_features,
out_type=tf.dtypes.quint8,
name=None
)
```
| Args |
| `features` | A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. |
| `max_value` | A `Tensor` of type `float32`. |
| `min_features` | A `Tensor` of type `float32`. The float value that the lowest quantized value represents. |
| `max_features` | A `Tensor` of type `float32`. The float value that the highest quantized value represents. |
| `out_type` | An optional [`tf.DType`](../../../dtypes/dtype) from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to [`tf.quint8`](../../../../tf#quint8). |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (activations, min\_activations, max\_activations). |
| `activations` | A `Tensor` of type `out_type`. |
| `min_activations` | A `Tensor` of type `float32`. |
| `max_activations` | A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.nn.static_bidirectional_rnn tf.compat.v1.nn.static\_bidirectional\_rnn
==========================================
Creates a bidirectional recurrent neural network. (deprecated)
```
tf.compat.v1.nn.static_bidirectional_rnn(
cell_fw,
cell_bw,
inputs,
initial_state_fw=None,
initial_state_bw=None,
dtype=None,
sequence_length=None,
scope=None
)
```
Similar to the unidirectional case above (rnn) but takes input and builds independent forward and backward RNNs with the final forward and backward outputs depth-concatenated, such that the output will have the format [time][batch][cell\_fw.output\_size + cell\_bw.output\_size]. The input\_size of forward and backward cell must match. The initial state for both directions is zero by default (but can be set optionally) and no intermediate states are ever returned -- the network is fully unrolled for the given (passed in) length(s) of the sequence(s) or completely unrolled if length(s) is not given.
| Args |
| `cell_fw` | An instance of RNNCell, to be used for forward direction. |
| `cell_bw` | An instance of RNNCell, to be used for backward direction. |
| `inputs` | A length T list of inputs, each a tensor of shape [batch\_size, input\_size], or a nested tuple of such elements. |
| `initial_state_fw` | (optional) An initial state for the forward RNN. This must be a tensor of appropriate type and shape `[batch_size, cell_fw.state_size]`. If `cell_fw.state_size` is a tuple, this should be a tuple of tensors having shapes `[batch_size, s] for s in cell_fw.state_size`. |
| `initial_state_bw` | (optional) Same as for `initial_state_fw`, but using the corresponding properties of `cell_bw`. |
| `dtype` | (optional) The data type for the initial state. Required if either of the initial states are not provided. |
| `sequence_length` | (optional) An int32/int64 vector, size `[batch_size]`, containing the actual lengths for each of the sequences. |
| `scope` | VariableScope for the created subgraph; defaults to "bidirectional\_rnn" |
| Returns |
| A tuple (outputs, output\_state\_fw, output\_state\_bw) where: outputs is a length `T` list of outputs (one for each input), which are depth-concatenated forward and backward outputs. output\_state\_fw is the final state of the forward rnn. output\_state\_bw is the final state of the backward rnn. |
| Raises |
| `TypeError` | If `cell_fw` or `cell_bw` is not an instance of `RNNCell`. |
| `ValueError` | If inputs is None or an empty list. |
tensorflow tf.compat.v1.nn.xw_plus_b tf.compat.v1.nn.xw\_plus\_b
===========================
Computes matmul(x, weights) + biases.
```
tf.compat.v1.nn.xw_plus_b(
x, weights, biases, name=None
)
```
| Args |
| `x` | a 2D tensor. Dimensions typically: batch, in\_units |
| `weights` | a 2D tensor. Dimensions typically: in\_units, out\_units |
| `biases` | a 1D tensor. Dimensions: out\_units |
| `name` | A name for the operation (optional). If not specified "xw\_plus\_b" is used. |
| Returns |
| A 2-D Tensor computing matmul(x, weights) + biases. Dimensions typically: batch, out\_units. |
tensorflow tf.compat.v1.nn.depthwise_conv2d tf.compat.v1.nn.depthwise\_conv2d
=================================
Depthwise 2-D convolution.
```
tf.compat.v1.nn.depthwise_conv2d(
input,
filter,
strides,
padding,
rate=None,
name=None,
data_format=None,
dilations=None
)
```
Given a 4D input tensor ('NHWC' or 'NCHW' data formats) and a filter tensor of shape `[filter_height, filter_width, in_channels, channel_multiplier]` containing `in_channels` convolutional filters of depth 1, `depthwise_conv2d` applies a different filter to each input channel (expanding from 1 channel to `channel_multiplier` channels for each), then concatenates the results together. The output has `in_channels * channel_multiplier` channels.
In detail, with the default NHWC format,
```
output[b, i, j, k * channel_multiplier + q] = sum_{di, dj}
filter[di, dj, k, q] * input[b, strides[1] * i + rate[0] * di,
strides[2] * j + rate[1] * dj, k]
```
Must have `strides[0] = strides[3] = 1`. For the most common case of the same horizontal and vertical strides, `strides = [1, stride, stride, 1]`. If any value in `rate` is greater than 1, we perform atrous depthwise convolution, in which case all values in the `strides` tensor must be equal to 1.
#### Usage Example:
```
x = np.array([
[1., 2.],
[3., 4.],
[5., 6.]
], dtype=np.float32).reshape((1, 3, 2, 1))
kernel = np.array([
[1., 2.],
[3., 4]
], dtype=np.float32).reshape((2, 1, 1, 2))
tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],
padding='VALID').numpy()
array([[[[10., 14.],
[14., 20.]],
[[18., 26.],
[22., 32.]]]], dtype=float32)
```
```
tf.compat.v1.nn.depthwise_conv2d(x, kernel, strides=[1, 1, 1, 1],
padding=[[0, 0], [1, 0], [1, 0], [0, 0]]
).numpy()
array([[[[ 0., 0.],
[ 3., 4.],
[ 6., 8.]],
[[ 0., 0.],
[10., 14.],
[14., 20.]],
[[ 0., 0.],
[18., 26.],
[22., 32.]]]], dtype=float32)
```
| Args |
| `input` | 4-D with shape according to `data_format`. |
| `filter` | 4-D with shape `[filter_height, filter_width, in_channels, channel_multiplier]`. |
| `strides` | 1-D of size 4. The stride of the sliding window for each dimension of `input`. |
| `padding` | Controls how to pad the image before applying the convolution. Can be the string `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `rate` | 1-D of size 2. The dilation rate in which we sample input values across the `height` and `width` dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1. |
| `name` | A name for this operation (optional). |
| `data_format` | The data format for input. Either "NHWC" (default) or "NCHW". |
| `dilations` | Alias of rate. |
| Returns |
| A 4-D `Tensor` with shape according to `data_format`. E.g., for "NHWC" format, shape is `[batch, out_height, out_width, in_channels * channel_multiplier].` |
| programming_docs |
tensorflow tf.compat.v1.nn.dilation2d tf.compat.v1.nn.dilation2d
==========================
Computes the grayscale dilation of 4-D `input` and 3-D `filter` tensors.
```
tf.compat.v1.nn.dilation2d(
input,
filter=None,
strides=None,
rates=None,
padding=None,
name=None,
filters=None,
dilations=None
)
```
The `input` tensor has shape `[batch, in_height, in_width, depth]` and the `filter` tensor has shape `[filter_height, filter_width, depth]`, i.e., each input channel is processed independently of the others with its own structuring function. The `output` tensor has shape `[batch, out_height, out_width, depth]`. The spatial dimensions of the output tensor depend on the `padding` algorithm. We currently only support the default "NHWC" `data_format`.
In detail, the grayscale morphological 2-D dilation is the max-sum correlation (for consistency with `conv2d`, we use unmirrored filters):
```
output[b, y, x, c] =
max_{dy, dx} input[b,
strides[1] * y + rates[1] * dy,
strides[2] * x + rates[2] * dx,
c] +
filter[dy, dx, c]
```
Max-pooling is a special case when the filter has size equal to the pooling kernel size and contains all zeros.
Note on duality: The dilation of `input` by the `filter` is equal to the negation of the erosion of `-input` by the reflected `filter`.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. 4-D with shape `[batch, in_height, in_width, depth]`. |
| `filter` | A `Tensor`. Must have the same type as `input`. 3-D with shape `[filter_height, filter_width, depth]`. |
| `strides` | A list of `ints` that has length `>= 4`. The stride of the sliding window for each dimension of the input tensor. Must be: `[1, stride_height, stride_width, 1]`. |
| `rates` | A list of `ints` that has length `>= 4`. The input stride for atrous morphological dilation. Must be: `[1, rate_height, rate_width, 1]`. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow Module: tf.compat.v1.nn.experimental Module: tf.compat.v1.nn.experimental
====================================
Public API for tf.nn.experimental namespace.
Functions
---------
[`stateless_dropout(...)`](../../../nn/experimental/stateless_dropout): Computes dropout: randomly sets elements to zero to prevent overfitting.
tensorflow tf.compat.v1.nn.quantized_max_pool tf.compat.v1.nn.quantized\_max\_pool
====================================
Produces the max pool of the input tensor for quantized types.
```
tf.compat.v1.nn.quantized_max_pool(
input, min_input, max_input, ksize, strides, padding, name=None
)
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. The 4D (batch x rows x cols x depth) Tensor to MaxReduce over. |
| `min_input` | A `Tensor` of type `float32`. The float value that the lowest quantized input value represents. |
| `max_input` | A `Tensor` of type `float32`. The float value that the highest quantized input value represents. |
| `ksize` | A list of `ints`. The size of the window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input. |
| `strides` | A list of `ints`. The stride of the sliding window for each dimension of the input tensor. The length must be 4 to match the number of dimensions of the input. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (output, min\_output, max\_output). |
| `output` | A `Tensor`. Has the same type as `input`. |
| `min_output` | A `Tensor` of type `float32`. |
| `max_output` | A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.nn.relu_layer tf.compat.v1.nn.relu\_layer
===========================
Computes Relu(x \* weight + biases).
```
tf.compat.v1.nn.relu_layer(
x, weights, biases, name=None
)
```
| Args |
| `x` | a 2D tensor. Dimensions typically: batch, in\_units |
| `weights` | a 2D tensor. Dimensions typically: in\_units, out\_units |
| `biases` | a 1D tensor. Dimensions: out\_units |
| `name` | A name for the operation (optional). If not specified "nn\_relu\_layer" is used. |
| Returns |
| A 2-D Tensor computing relu(matmul(x, weights) + biases). Dimensions typically: batch, out\_units. |
tensorflow tf.compat.v1.nn.fractional_max_pool tf.compat.v1.nn.fractional\_max\_pool
=====================================
Performs fractional max pooling on the input. (deprecated)
```
tf.compat.v1.nn.fractional_max_pool(
value,
pooling_ratio,
pseudo_random=False,
overlapping=False,
deterministic=False,
seed=0,
seed2=0,
name=None
)
```
This is a deprecated version of `fractional_max_pool`.
Fractional max pooling is slightly different than regular max pooling. In regular max pooling, you downsize an input set by taking the maximum value of smaller N x N subsections of the set (often 2x2), and try to reduce the set by a factor of N, where N is an integer. Fractional max pooling, as you might expect from the word "fractional", means that the overall reduction ratio N does not have to be an integer.
The sizes of the pooling regions are generated randomly but are fairly uniform. For example, let's look at the height dimension, and the constraints on the list of rows that will be pool boundaries.
First we define the following:
1. input\_row\_length : the number of rows from the input set
2. output\_row\_length : which will be smaller than the input
3. alpha = input\_row\_length / output\_row\_length : our reduction ratio
4. K = floor(alpha)
5. row\_pooling\_sequence : this is the result list of pool boundary rows
Then, row\_pooling\_sequence should satisfy:
1. a[0] = 0 : the first value of the sequence is 0
2. a[end] = input\_row\_length : the last value of the sequence is the size
3. K <= (a[i+1] - a[i]) <= K+1 : all intervals are K or K+1 size
4. length(row\_pooling\_sequence) = output\_row\_length+1
| Args |
| `value` | A `Tensor`. 4-D with shape `[batch, height, width, channels]`. |
| `pooling_ratio` | A list of `floats` that has length >= 4. Pooling ratio for each dimension of `value`, currently only supports row and col dimension and should be >= 1.0. For example, a valid pooling ratio looks like [1.0, 1.44, 1.73, 1.0]. The first and last elements must be 1.0 because we don't allow pooling on batch and channels dimensions. 1.44 and 1.73 are pooling ratio on height and width dimensions respectively. |
| `pseudo_random` | An optional `bool`. Defaults to `False`. When set to `True`, generates the pooling sequence in a pseudorandom fashion, otherwise, in a random fashion. Check (Graham, 2015) for difference between pseudorandom and random. |
| `overlapping` | An optional `bool`. Defaults to `False`. When set to `True`, it means when pooling, the values at the boundary of adjacent pooling cells are used by both cells. For example: `index 0 1 2 3 4` `value 20 5 16 3 7` If the pooling sequence is [0, 2, 4], then 16, at index 2 will be used twice. The result would be [20, 16] for fractional max pooling. |
| `deterministic` | An optional `bool`. Deprecated; use `fractional_max_pool_v2` instead. |
| `seed` | An optional `int`. Defaults to `0`. If set to be non-zero, the random number generator is seeded by the given seed. Otherwise it is seeded by a random seed. |
| `seed2` | An optional `int`. Deprecated; use `fractional_max_pool_v2` instead. |
| `name` | A name for the operation (optional). |
| Returns |
A tuple of `Tensor` objects (`output`, `row_pooling_sequence`, `col_pooling_sequence`). output: Output `Tensor` after fractional max pooling. Has the same type as `value`. row\_pooling\_sequence: A `Tensor` of type `int64`. col\_pooling\_sequence: A `Tensor` of type `int64`.
| Raises |
| `ValueError` | If op determinism is enabled and either the seeds are not set or the "deterministic" argument is False. |
#### References:
Fractional Max-Pooling: [Graham, 2015](https://arxiv.org/abs/1412.6071) ([pdf](https://arxiv.org/pdf/1412.6071.pdf))
tensorflow tf.compat.v1.nn.conv2d_backprop_filter tf.compat.v1.nn.conv2d\_backprop\_filter
========================================
Computes the gradients of convolution with respect to the filter.
```
tf.compat.v1.nn.conv2d_backprop_filter(
input,
filter_sizes,
out_backprop,
strides,
padding,
use_cudnn_on_gpu=True,
data_format='NHWC',
dilations=[1, 1, 1, 1],
name=None
)
```
| Args |
| `input` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. 4-D with shape `[batch, in_height, in_width, in_channels]`. |
| `filter_sizes` | A `Tensor` of type `int32`. An integer vector representing the tensor shape of `filter`, where `filter` is a 4-D `[filter_height, filter_width, in_channels, out_channels]` tensor. |
| `out_backprop` | A `Tensor`. Must have the same type as `input`. 4-D with shape `[batch, out_height, out_width, out_channels]`. Gradients w.r.t. the output of the convolution. |
| `strides` | A list of `ints`. The stride of the sliding window for each dimension of the input of the convolution. Must be in the same order as the dimension specified with format. |
| `padding` | Either the `string` `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `use_cudnn_on_gpu` | An optional `bool`. Defaults to `True`. |
| `data_format` | An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, in\_height, in\_width, in\_channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, in\_channels, in\_height, in\_width]. |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D tensor of length 4. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type as `input`. |
tensorflow tf.compat.v1.nn.conv2d_backprop_input tf.compat.v1.nn.conv2d\_backprop\_input
=======================================
Computes the gradients of convolution with respect to the input.
```
tf.compat.v1.nn.conv2d_backprop_input(
input_sizes,
filter=None,
out_backprop=None,
strides=None,
padding=None,
use_cudnn_on_gpu=True,
data_format='NHWC',
dilations=[1, 1, 1, 1],
name=None,
filters=None
)
```
| Args |
| `input_sizes` | A `Tensor` of type `int32`. An integer vector representing the shape of `input`, where `input` is a 4-D `[batch, height, width, channels]` tensor. |
| `filter` | A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`. 4-D with shape `[filter_height, filter_width, in_channels, out_channels]`. |
| `out_backprop` | A `Tensor`. Must have the same type as `filter`. 4-D with shape `[batch, out_height, out_width, out_channels]`. Gradients w.r.t. the output of the convolution. |
| `strides` | A list of `ints`. The stride of the sliding window for each dimension of the input of the convolution. Must be in the same order as the dimension specified with format. |
| `padding` | Either the `string` `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `use_cudnn_on_gpu` | An optional `bool`. Defaults to `True`. |
| `data_format` | An optional `string` from: `"NHWC", "NCHW"`. Defaults to `"NHWC"`. Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, in\_height, in\_width, in\_channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, in\_channels, in\_height, in\_width]. |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D tensor of length 4. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| `filters` | Alias for filter. |
| Returns |
| A `Tensor`. Has the same type as `filter`. |
tensorflow tf.compat.v1.nn.quantized_conv2d tf.compat.v1.nn.quantized\_conv2d
=================================
Computes a 2D convolution given quantized 4D input and filter tensors.
```
tf.compat.v1.nn.quantized_conv2d(
input,
filter,
min_input,
max_input,
min_filter,
max_filter,
strides,
padding,
out_type=tf.dtypes.qint32,
dilations=[1, 1, 1, 1],
name=None
)
```
The inputs are quantized tensors where the lowest value represents the real number of the associated minimum, and the highest represents the maximum. This means that you can only interpret the quantized output in the same way, by taking the returned minimum and maximum values into account.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. |
| `filter` | A `Tensor`. Must be one of the following types: `qint8`, `quint8`, `qint32`, `qint16`, `quint16`. filter's input\_depth dimension must match input's depth dimensions. |
| `min_input` | A `Tensor` of type `float32`. The float value that the lowest quantized input value represents. |
| `max_input` | A `Tensor` of type `float32`. The float value that the highest quantized input value represents. |
| `min_filter` | A `Tensor` of type `float32`. The float value that the lowest quantized filter value represents. |
| `max_filter` | A `Tensor` of type `float32`. The float value that the highest quantized filter value represents. |
| `strides` | A list of `ints`. The stride of the sliding window for each dimension of the input tensor. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `out_type` | An optional [`tf.DType`](../../../dtypes/dtype) from: `tf.qint8, tf.quint8, tf.qint32, tf.qint16, tf.quint16`. Defaults to [`tf.qint32`](../../../../tf#qint32). |
| `dilations` | An optional list of `ints`. Defaults to `[1, 1, 1, 1]`. 1-D tensor of length 4. The dilation factor for each dimension of `input`. If set to k > 1, there will be k-1 skipped cells between each filter element on that dimension. The dimension order is determined by the value of `data_format`, see above for details. Dilations in the batch and depth dimensions must be 1. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (output, min\_output, max\_output). |
| `output` | A `Tensor` of type `out_type`. |
| `min_output` | A `Tensor` of type `float32`. |
| `max_output` | A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.nn.max_pool_with_argmax tf.compat.v1.nn.max\_pool\_with\_argmax
=======================================
Performs max pooling on the input and outputs both max values and indices.
```
tf.compat.v1.nn.max_pool_with_argmax(
input,
ksize,
strides,
padding,
data_format='NHWC',
Targmax=None,
name=None,
output_dtype=None,
include_batch_in_index=False
)
```
The indices in `argmax` are flattened, so that a maximum value at position `[b, y, x, c]` becomes flattened index: `(y * width + x) * channels + c` if `include_batch_in_index` is False; `((b * height + y) * width + x) * channels + c` if `include_batch_in_index` is True.
The indices returned are always in `[0, height) x [0, width)` before flattening, even if padding is involved and the mathematically correct answer is outside (either negative or too large). This is a bug, but fixing it is difficult to do in a safe backwards compatible way, especially due to flattening.
| Args |
| `input` | A `Tensor`. Must be one of the following types: `float32`, `float64`, `int32`, `uint8`, `int16`, `int8`, `int64`, `bfloat16`, `uint16`, `half`, `uint32`, `uint64`. 4-D with shape `[batch, height, width, channels]`. Input to pool over. |
| `ksize` | A list of `ints` that has length `>= 4`. The size of the window for each dimension of the input tensor. |
| `strides` | A list of `ints` that has length `>= 4`. The stride of the sliding window for each dimension of the input tensor. |
| `padding` | A `string` from: `"SAME", "VALID"`. The type of padding algorithm to use. |
| `Targmax` | An optional [`tf.DType`](../../../dtypes/dtype) from: `tf.int32, tf.int64`. Defaults to [`tf.int64`](../../../../tf#int64). |
| `include_batch_in_index` | An optional `bool`. Defaults to `False`. Whether to include batch dimension in flattened index of `argmax`. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (output, argmax). |
| `output` | A `Tensor`. Has the same type as `input`. |
| `argmax` | A `Tensor` of type `Targmax`. |
tensorflow tf.compat.v1.nn.safe_embedding_lookup_sparse tf.compat.v1.nn.safe\_embedding\_lookup\_sparse
===============================================
Lookup embedding results, accounting for invalid IDs and empty features.
```
tf.compat.v1.nn.safe_embedding_lookup_sparse(
embedding_weights,
sparse_ids,
sparse_weights=None,
combiner='mean',
default_id=None,
name=None,
partition_strategy='div',
max_norm=None
)
```
The partitioned embedding in `embedding_weights` must all be the same shape except for the first dimension. The first dimension is allowed to vary as the vocabulary size is not necessarily a multiple of `P`. `embedding_weights` may be a `PartitionedVariable` as returned by using [`tf.compat.v1.get_variable()`](../get_variable) with a partitioner.
Invalid IDs (< 0) are pruned from input IDs and weights, as well as any IDs with non-positive weight. For an entry with no features, the embedding vector for `default_id` is returned, or the 0-vector if `default_id` is not supplied.
The ids and weights may be multi-dimensional. Embeddings are always aggregated along the last dimension.
| Args |
| `embedding_weights` | A single tensor representing the complete embedding tensor, or a list tensors all of same shape except for the first dimension, representing sharded embedding tensors. Alternatively, a `PartitionedVariable`, created by partitioning along dimension 0. Each element must be appropriately sized for the given `partition_strategy`. |
| `sparse_ids` | `SparseTensor` of shape `[d_0, d_1, ..., d_n]` containing the ids. `d_0` is typically batch size. |
| `sparse_weights` | `SparseTensor` of same shape as `sparse_ids`, containing float weights corresponding to `sparse_ids`, or `None` if all weights are be assumed to be 1.0. |
| `combiner` | A string specifying how to combine embedding results for each entry. Currently "mean", "sqrtn" and "sum" are supported, with "mean" the default. |
| `default_id` | The id to use for an entry with no features. |
| `name` | A name for this operation (optional). |
| `partition_strategy` | A string specifying the partitioning strategy. Currently `"div"` and `"mod"` are supported. Default is `"div"`. |
| `max_norm` | If not `None`, all embeddings are l2-normalized to max\_norm before combining. |
| Returns |
| A dense tensor representing the combined embeddings for the sparse ids. For each row in the dense tensor represented by `sp_ids`, the op looks up the embeddings for all ids in that row, multiplies them by the corresponding weight, and combines these embeddings as specified. In other words, if `shape(combined embedding_weights) = [p0, p1, ..., pm]` and `shape(sparse_ids) = shape(sparse_weights) = [d0, d1, ..., dn]` then `shape(output) = [d0, d1, ... dn-1, p1, ..., pm]`. For instance, if params is a 10x20 matrix, and sp\_ids / sp\_weights are
```
[0, 0]: id 1, weight 2.0
[0, 1]: id 3, weight 0.5
[1, 0]: id -1, weight 1.0
[2, 3]: id 1, weight 3.0
```
`default_id` is 0. with `combiner`="mean", then the output will be a 3x20 matrix where
```
output[0, :] = (params[1, :] * 2.0 + params[3, :] * 0.5) / (2.0 + 0.5)
output[1, :] = (params[0, :] * 1.0) / 1.0
output[2, :] = (params[1, :] * 3.0) / 3.0
```
|
| Raises |
| `ValueError` | if `embedding_weights` is empty. |
| programming_docs |
tensorflow tf.compat.v1.nn.weighted_cross_entropy_with_logits tf.compat.v1.nn.weighted\_cross\_entropy\_with\_logits
======================================================
Computes a weighted cross entropy. (deprecated arguments)
```
tf.compat.v1.nn.weighted_cross_entropy_with_logits(
labels=None, logits=None, pos_weight=None, name=None, targets=None
)
```
This is like `sigmoid_cross_entropy_with_logits()` except that `pos_weight`, allows one to trade off recall and precision by up- or down-weighting the cost of a positive error relative to a negative error.
The usual cross-entropy cost is defined as:
```
labels * -log(sigmoid(logits)) +
(1 - labels) * -log(1 - sigmoid(logits))
```
A value `pos_weight > 1` decreases the false negative count, hence increasing the recall. Conversely setting `pos_weight < 1` decreases the false positive count and increases the precision. This can be seen from the fact that `pos_weight` is introduced as a multiplicative coefficient for the positive labels term in the loss expression:
```
labels * -log(sigmoid(logits)) * pos_weight +
(1 - labels) * -log(1 - sigmoid(logits))
```
For brevity, let `x = logits`, `z = labels`, `q = pos_weight`. The loss is:
```
qz * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x))
= qz * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x)))
= qz * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x))
= (1 - z) * x + (qz + 1 - z) * log(1 + exp(-x))
= (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))
```
Setting `l = (1 + (q - 1) * z)`, to ensure stability and avoid overflow, the implementation uses
```
(1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))
```
`logits` and `labels` must have the same type and shape.
| Args |
| `labels` | A `Tensor` of the same type and shape as `logits`. |
| `logits` | A `Tensor` of type `float32` or `float64`. |
| `pos_weight` | A coefficient to use on the positive examples. |
| `name` | A name for the operation (optional). |
| `targets` | Deprecated alias for labels. |
| Returns |
| A `Tensor` of the same shape as `logits` with the componentwise weighted logistic losses. |
| Raises |
| `ValueError` | If `logits` and `labels` do not have the same shape. |
tensorflow tf.compat.v1.nn.avg_pool tf.compat.v1.nn.avg\_pool
=========================
Performs the average pooling on the input.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.nn.avg_pool2d`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/nn/avg_pool)
```
tf.compat.v1.nn.avg_pool(
value,
ksize,
strides,
padding,
data_format='NHWC',
name=None,
input=None
)
```
Each entry in `output` is the mean of the corresponding size `ksize` window in `value`.
| Args |
| `value` | A 4-D `Tensor` of shape `[batch, height, width, channels]` and type `float32`, `float64`, `qint8`, `quint8`, or `qint32`. |
| `ksize` | An int or list of `ints` that has length `1`, `2` or `4`. The size of the window for each dimension of the input tensor. |
| `strides` | An int or list of `ints` that has length `1`, `2` or `4`. The stride of the sliding window for each dimension of the input tensor. |
| `padding` | A string, either `'VALID'` or `'SAME'`. The padding algorithm. See the "returns" section of [`tf.nn.convolution`](../../../nn/convolution) for details. |
| `data_format` | A string. 'NHWC' and 'NCHW' are supported. |
| `name` | Optional name for the operation. |
| `input` | Alias for value. |
| Returns |
| A `Tensor` with the same type as `value`. The average pooled output tensor. |
tensorflow tf.compat.v1.nn.ctc_loss tf.compat.v1.nn.ctc\_loss
=========================
Computes the CTC (Connectionist Temporal Classification) Loss.
```
tf.compat.v1.nn.ctc_loss(
labels,
inputs=None,
sequence_length=None,
preprocess_collapse_repeated=False,
ctc_merge_repeated=True,
ignore_longer_outputs_than_inputs=False,
time_major=True,
logits=None
)
```
This op implements the CTC loss as presented in (Graves et al., 2006).
#### Input requirements:
```
sequence_length(b) <= time for all b
max(labels.indices(labels.indices[:, 1] == b, 2))
<= sequence_length(b) for all b.
```
#### Notes:
This class performs the softmax operation for you, so inputs should be e.g. linear projections of outputs by an LSTM.
The `inputs` Tensor's innermost dimension size, `num_classes`, represents `num_labels + 1` classes, where num\_labels is the number of true labels, and the largest value `(num_classes - 1)` is reserved for the blank label.
For example, for a vocabulary containing 3 labels `[a, b, c]`, `num_classes = 4` and the labels indexing is `{a: 0, b: 1, c: 2, blank: 3}`.
Regarding the arguments `preprocess_collapse_repeated` and `ctc_merge_repeated`:
If `preprocess_collapse_repeated` is True, then a preprocessing step runs before loss calculation, wherein repeated labels passed to the loss are merged into single labels. This is useful if the training labels come from, e.g., forced alignments and therefore have unnecessary repetitions.
If `ctc_merge_repeated` is set False, then deep within the CTC calculation, repeated non-blank labels will not be merged and are interpreted as individual labels. This is a simplified (non-standard) version of CTC.
Here is a table of the (roughly) expected first order behavior:
* `preprocess_collapse_repeated=False`, `ctc_merge_repeated=True`
Classical CTC behavior: Outputs true repeated classes with blanks in between, and can also output repeated classes with no blanks in between that need to be collapsed by the decoder.
* `preprocess_collapse_repeated=True`, `ctc_merge_repeated=False`
Never learns to output repeated classes, as they are collapsed in the input labels before training.
* `preprocess_collapse_repeated=False`, `ctc_merge_repeated=False`
Outputs repeated classes with blanks in between, but generally does not require the decoder to collapse/merge repeated classes.
* `preprocess_collapse_repeated=True`, `ctc_merge_repeated=True`
Untested. Very likely will not learn to output repeated classes.
The `ignore_longer_outputs_than_inputs` option allows to specify the behavior of the CTCLoss when dealing with sequences that have longer outputs than inputs. If true, the CTCLoss will simply return zero gradient for those items, otherwise an InvalidArgument error is returned, stopping training.
| Args |
| `labels` | An `int32` `SparseTensor`. `labels.indices[i, :] == [b, t]` means `labels.values[i]` stores the id for (batch b, time t). `labels.values[i]` must take on values in `[0, num_labels)`. See `core/ops/ctc_ops.cc` for more details. |
| `inputs` | 3-D `float` `Tensor`. If time\_major == False, this will be a `Tensor` shaped: `[batch_size, max_time, num_classes]`. If time\_major == True (default), this will be a `Tensor` shaped: `[max_time, batch_size, num_classes]`. The logits. |
| `sequence_length` | 1-D `int32` vector, size `[batch_size]`. The sequence lengths. |
| `preprocess_collapse_repeated` | Boolean. Default: False. If True, repeated labels are collapsed prior to the CTC calculation. |
| `ctc_merge_repeated` | Boolean. Default: True. |
| `ignore_longer_outputs_than_inputs` | Boolean. Default: False. If True, sequences with longer outputs than inputs will be ignored. |
| `time_major` | The shape format of the `inputs` Tensors. If True, these `Tensors` must be shaped `[max_time, batch_size, num_classes]`. If False, these `Tensors` must be shaped `[batch_size, max_time, num_classes]`. Using `time_major = True` (default) is a bit more efficient because it avoids transposes at the beginning of the ctc\_loss calculation. However, most TensorFlow data is batch-major, so by this function also accepts inputs in batch-major form. |
| `logits` | Alias for inputs. |
| Returns |
| A 1-D `float` `Tensor`, size `[batch]`, containing the negative log probabilities. |
| Raises |
| `TypeError` | if labels is not a `SparseTensor`. |
#### References:
Connectionist Temporal Classification - Labeling Unsegmented Sequence Data with Recurrent Neural Networks: [Graves et al., 2006](https://dl.acm.org/citation.cfm?id=1143891) ([pdf](http://www.cs.toronto.edu/%7Egraves/icml_2006.pdf))
tensorflow tf.compat.v1.nn.nce_loss tf.compat.v1.nn.nce\_loss
=========================
Computes and returns the noise-contrastive estimation training loss.
```
tf.compat.v1.nn.nce_loss(
weights,
biases,
labels,
inputs,
num_sampled,
num_classes,
num_true=1,
sampled_values=None,
remove_accidental_hits=False,
partition_strategy='mod',
name='nce_loss'
)
```
A common use case is to use this method for training, and calculate the full sigmoid loss for evaluation or inference. In this case, you must set `partition_strategy="div"` for the two losses to be consistent, as in the following example:
```
if mode == "train":
loss = tf.nn.nce_loss(
weights=weights,
biases=biases,
labels=labels,
inputs=inputs,
...,
partition_strategy="div")
elif mode == "eval":
logits = tf.matmul(inputs, tf.transpose(weights))
logits = tf.nn.bias_add(logits, biases)
labels_one_hot = tf.one_hot(labels, n_classes)
loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=labels_one_hot,
logits=logits)
loss = tf.reduce_sum(loss, axis=1)
```
>
> **Note:** By default this uses a log-uniform (Zipfian) distribution for sampling, so your labels must be sorted in order of decreasing frequency to achieve good results. For more details, see [`tf.random.log_uniform_candidate_sampler`](../../../random/log_uniform_candidate_sampler).
>
>
> **Note:** In the case where `num_true` > 1, we assign to each target class the target probability 1 / `num_true` so that the target probabilities sum to 1 per-example.
>
>
> **Note:** It would be useful to allow a variable number of target classes per example. We hope to provide this functionality in a future release. For now, if you have a variable number of target classes, you can pad them out to a constant number by either repeating them or by padding with an otherwise unused class.
>
| Args |
| `weights` | A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor` objects whose concatenation along dimension 0 has shape [num\_classes, dim]. The (possibly-partitioned) class embeddings. |
| `biases` | A `Tensor` of shape `[num_classes]`. The class biases. |
| `labels` | A `Tensor` of type `int64` and shape `[batch_size, num_true]`. The target classes. |
| `inputs` | A `Tensor` of shape `[batch_size, dim]`. The forward activations of the input network. |
| `num_sampled` | An `int`. The number of negative classes to randomly sample per batch. This single sample of negative classes is evaluated for each element in the batch. |
| `num_classes` | An `int`. The number of possible classes. |
| `num_true` | An `int`. The number of target classes per training example. |
| `sampled_values` | a tuple of (`sampled_candidates`, `true_expected_count`, `sampled_expected_count`) returned by a `*_candidate_sampler` function. (if None, we default to `log_uniform_candidate_sampler`) |
| `remove_accidental_hits` | A `bool`. Whether to remove "accidental hits" where a sampled class equals one of the target classes. If set to `True`, this is a "Sampled Logistic" loss instead of NCE, and we are learning to generate log-odds instead of log probabilities. See our Candidate Sampling Algorithms Reference ([pdf](https://www.tensorflow.org/extras/candidate_sampling.pdf)). Default is False. |
| `partition_strategy` | A string specifying the partitioning strategy, relevant if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported. Default is `"mod"`. See `tf.nn.embedding_lookup` for more details. |
| `name` | A name for the operation (optional). |
| Returns |
| A `batch_size` 1-D tensor of per-example NCE losses. |
#### References:
Noise-contrastive estimation - A new estimation principle for unnormalized statistical models: [Gutmann et al., 2010](http://proceedings.mlr.press/v9/gutmann10a) ([pdf](http://proceedings.mlr.press/v9/gutmann10a/gutmann10a.pdf))
tensorflow tf.compat.v1.nn.separable_conv2d tf.compat.v1.nn.separable\_conv2d
=================================
2-D convolution with separable filters.
```
tf.compat.v1.nn.separable_conv2d(
input,
depthwise_filter,
pointwise_filter,
strides,
padding,
rate=None,
name=None,
data_format=None,
dilations=None
)
```
Performs a depthwise convolution that acts separately on channels followed by a pointwise convolution that mixes channels. Note that this is separability between dimensions `[1, 2]` and `3`, not spatial separability between dimensions `1` and `2`.
In detail, with the default NHWC format,
```
output[b, i, j, k] = sum_{di, dj, q, r}
input[b, strides[1] * i + di, strides[2] * j + dj, q] *
depthwise_filter[di, dj, q, r] *
pointwise_filter[0, 0, q * channel_multiplier + r, k]
```
`strides` controls the strides for the depthwise convolution only, since the pointwise convolution has implicit strides of `[1, 1, 1, 1]`. Must have `strides[0] = strides[3] = 1`. For the most common case of the same horizontal and vertical strides, `strides = [1, stride, stride, 1]`. If any value in `rate` is greater than 1, we perform atrous depthwise convolution, in which case all values in the `strides` tensor must be equal to 1.
| Args |
| `input` | 4-D `Tensor` with shape according to `data_format`. |
| `depthwise_filter` | 4-D `Tensor` with shape `[filter_height, filter_width, in_channels, channel_multiplier]`. Contains `in_channels` convolutional filters of depth 1. |
| `pointwise_filter` | 4-D `Tensor` with shape `[1, 1, channel_multiplier * in_channels, out_channels]`. Pointwise filter to mix channels after `depthwise_filter` has convolved spatially. |
| `strides` | 1-D of size 4. The strides for the depthwise convolution for each dimension of `input`. |
| `padding` | Controls how to pad the image before applying the depthwise convolution. Can be the string `"SAME"` or `"VALID"` indicating the type of padding algorithm to use, or a Python list indicating the explicit paddings at the start and end of each dimension. When explicit padding is used and data\_format is `"NHWC"`, this should be in the form `[[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]`. When explicit padding used and data\_format is `"NCHW"`, this should be in the form `[[0, 0], [0, 0], [pad_top, pad_bottom], [pad_left, pad_right]]`. |
| `rate` | 1-D of size 2. The dilation rate in which we sample input values across the `height` and `width` dimensions in atrous convolution. If it is greater than 1, then all values of strides must be 1. |
| `name` | A name for this operation (optional). |
| `data_format` | The data format for input. Either "NHWC" (default) or "NCHW". |
| `dilations` | Alias of rate. |
| Returns |
| A 4-D `Tensor` with shape according to 'data\_format'. For example, with data\_format="NHWC", shape is [batch, out\_height, out\_width, out\_channels]. |
tensorflow tf.compat.v1.nn.dropout tf.compat.v1.nn.dropout
=======================
Computes dropout. (deprecated arguments)
```
tf.compat.v1.nn.dropout(
x, keep_prob=None, noise_shape=None, seed=None, name=None, rate=None
)
```
For each element of `x`, with probability `rate`, outputs `0`, and otherwise scales up the input by `1 / (1-rate)`. The scaling is such that the expected sum is unchanged.
By default, each element is kept or dropped independently. If `noise_shape` is specified, it must be [broadcastable](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html) to the shape of `x`, and only dimensions with `noise_shape[i] == shape(x)[i]` will make independent decisions. For example, if `shape(x) = [k, l, m, n]` and `noise_shape = [k, 1, 1, n]`, each batch and channel component will be kept independently and each row and column will be kept or not kept together.
| Args |
| `x` | A floating point tensor. |
| `keep_prob` | (deprecated) A deprecated alias for `(1-rate)`. |
| `noise_shape` | A 1-D integer `Tensor`, representing the shape for randomly generated keep/drop flags. |
| `seed` | A Python integer. Used to create random seeds. See [`tf.random.set_seed`](../../../random/set_seed) for behavior. |
| `name` | A name for this operation (optional). |
| `rate` | A scalar `Tensor` with the same type as `x`. The probability that each element of `x` is discarded. |
| Returns |
| A Tensor of the same shape of `x`. |
| Raises |
| `ValueError` | If `rate` is not in `[0, 1)` or if `x` is not a floating point tensor. |
tensorflow tf.compat.v1.nn.raw_rnn tf.compat.v1.nn.raw\_rnn
========================
Creates an `RNN` specified by RNNCell `cell` and loop function `loop_fn`.
```
tf.compat.v1.nn.raw_rnn(
cell, loop_fn, parallel_iterations=None, swap_memory=False, scope=None
)
```
>
> **Note:** This method is still in testing, and the API may change.\*\*
>
This function is a more primitive version of `dynamic_rnn` that provides more direct access to the inputs each iteration. It also provides more control over when to start and finish reading the sequence, and what to emit for the output.
For example, it can be used to implement the dynamic decoder of a seq2seq model.
Instead of working with `Tensor` objects, most operations work with `TensorArray` objects directly.
The operation of `raw_rnn`, in pseudo-code, is basically the following:
```
time = tf.constant(0, dtype=tf.int32)
(finished, next_input, initial_state, emit_structure, loop_state) = loop_fn(
time=time, cell_output=None, cell_state=None, loop_state=None)
emit_ta = TensorArray(dynamic_size=True, dtype=initial_state.dtype)
state = initial_state
while not all(finished):
(output, cell_state) = cell(next_input, state)
(next_finished, next_input, next_state, emit, loop_state) = loop_fn(
time=time + 1, cell_output=output, cell_state=cell_state,
loop_state=loop_state)
# Emit zeros and copy forward state for minibatch entries that are finished.
state = tf.where(finished, state, next_state)
emit = tf.where(finished, tf.zeros_like(emit_structure), emit)
emit_ta = emit_ta.write(time, emit)
# If any new minibatch entries are marked as finished, mark these.
finished = tf.logical_or(finished, next_finished)
time += 1
return (emit_ta, state, loop_state)
```
with the additional properties that output and state may be (possibly nested) tuples, as determined by `cell.output_size` and `cell.state_size`, and as a result the final `state` and `emit_ta` may themselves be tuples.
A simple implementation of `dynamic_rnn` via `raw_rnn` looks like this:
```
inputs = tf.compat.v1.placeholder(shape=(max_time, batch_size, input_depth),
dtype=tf.float32)
sequence_length = tf.compat.v1.placeholder(shape=(batch_size,),
dtype=tf.int32)
inputs_ta = tf.TensorArray(dtype=tf.float32, size=max_time)
inputs_ta = inputs_ta.unstack(inputs)
cell = tf.compat.v1.nn.rnn_cell.LSTMCell(num_units)
def loop_fn(time, cell_output, cell_state, loop_state):
emit_output = cell_output # == None for time == 0
if cell_output is None: # time == 0
next_cell_state = cell.zero_state(batch_size, tf.float32)
else:
next_cell_state = cell_state
elements_finished = (time >= sequence_length)
finished = tf.reduce_all(elements_finished)
next_input = tf.cond(
finished,
lambda: tf.zeros([batch_size, input_depth], dtype=tf.float32),
lambda: inputs_ta.read(time))
next_loop_state = None
return (elements_finished, next_input, next_cell_state,
emit_output, next_loop_state)
outputs_ta, final_state, _ = raw_rnn(cell, loop_fn)
outputs = outputs_ta.stack()
```
| Args |
| `cell` | An instance of RNNCell. |
| `loop_fn` | A callable that takes inputs `(time, cell_output, cell_state, loop_state)` and returns the tuple `(finished, next_input, next_cell_state, emit_output, next_loop_state)`. Here `time` is an int32 scalar `Tensor`, `cell_output` is a `Tensor` or (possibly nested) tuple of tensors as determined by `cell.output_size`, and `cell_state` is a `Tensor` or (possibly nested) tuple of tensors, as determined by the `loop_fn` on its first call (and should match `cell.state_size`). The outputs are: `finished`, a boolean `Tensor` of shape `[batch_size]`, `next_input`: the next input to feed to `cell`, `next_cell_state`: the next state to feed to `cell`, and `emit_output`: the output to store for this iteration. Note that `emit_output` should be a `Tensor` or (possibly nested) tuple of tensors which is aggregated in the `emit_ta` inside the `while_loop`. For the first call to `loop_fn`, the `emit_output` corresponds to the `emit_structure` which is then used to determine the size of the `zero_tensor` for the `emit_ta` (defaults to `cell.output_size`). For the subsequent calls to the `loop_fn`, the `emit_output` corresponds to the actual output tensor that is to be aggregated in the `emit_ta`. The parameter `cell_state` and output `next_cell_state` may be either a single or (possibly nested) tuple of tensors. The parameter `loop_state` and output `next_loop_state` may be either a single or (possibly nested) tuple of `Tensor` and `TensorArray` objects. This last parameter may be ignored by `loop_fn` and the return value may be `None`. If it is not `None`, then the `loop_state` will be propagated through the RNN loop, for use purely by `loop_fn` to keep track of its own state. The `next_loop_state` parameter returned may be `None`. The first call to `loop_fn` will be `time = 0`, `cell_output = None`, `cell_state = None`, and `loop_state = None`. For this call: The `next_cell_state` value should be the value with which to initialize the cell's state. It may be a final state from a previous RNN or it may be the output of `cell.zero_state()`. It should be a (possibly nested) tuple structure of tensors. If `cell.state_size` is an integer, this must be a `Tensor` of appropriate type and shape `[batch_size, cell.state_size]`. If `cell.state_size` is a `TensorShape`, this must be a `Tensor` of appropriate type and shape `[batch_size] + cell.state_size`. If `cell.state_size` is a (possibly nested) tuple of ints or `TensorShape`, this will be a tuple having the corresponding shapes. The `emit_output` value may be either `None` or a (possibly nested) tuple structure of tensors, e.g., `(tf.zeros(shape_0, dtype=dtype_0), tf.zeros(shape_1, dtype=dtype_1))`. If this first `emit_output` return value is `None`, then the `emit_ta` result of `raw_rnn` will have the same structure and dtypes as `cell.output_size`. Otherwise `emit_ta` will have the same structure, shapes (prepended with a `batch_size` dimension), and dtypes as `emit_output`. The actual values returned for `emit_output` at this initializing call are ignored. Note, this emit structure must be consistent across all time steps. |
| `parallel_iterations` | (Default: 32). The number of iterations to run in parallel. Those operations which do not have any temporal dependency and can be run in parallel, will be. This parameter trades off time for space. Values >> 1 use more memory but take less time, while smaller values use less memory but computations take longer. |
| `swap_memory` | Transparently swap the tensors produced in forward inference but needed for back prop from GPU to CPU. This allows training RNNs which would typically not fit on a single GPU, with very minimal (or no) performance penalty. |
| `scope` | VariableScope for the created subgraph; defaults to "rnn". |
| Returns |
| A tuple `(emit_ta, final_state, final_loop_state)` where: `emit_ta`: The RNN output `TensorArray`. If `loop_fn` returns a (possibly nested) set of Tensors for `emit_output` during initialization, (inputs `time = 0`, `cell_output = None`, and `loop_state = None`), then `emit_ta` will have the same structure, dtypes, and shapes as `emit_output` instead. If `loop_fn` returns `emit_output = None` during this call, the structure of `cell.output_size` is used: If `cell.output_size` is a (possibly nested) tuple of integers or `TensorShape` objects, then `emit_ta` will be a tuple having the same structure as `cell.output_size`, containing TensorArrays whose elements' shapes correspond to the shape data in `cell.output_size`. `final_state`: The final cell state. If `cell.state_size` is an int, this will be shaped `[batch_size, cell.state_size]`. If it is a `TensorShape`, this will be shaped `[batch_size] + cell.state_size`. If it is a (possibly nested) tuple of ints or `TensorShape`, this will be a tuple having the corresponding shapes. `final_loop_state`: The final loop state as returned by `loop_fn`. |
| Raises |
| `TypeError` | If `cell` is not an instance of RNNCell, or `loop_fn` is not a `callable`. |
| programming_docs |
tensorflow tf.compat.v1.nn.rnn_cell.GRUCell tf.compat.v1.nn.rnn\_cell.GRUCell
=================================
Gated Recurrent Unit cell.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.GRUCell(
num_units,
activation=None,
reuse=None,
kernel_initializer=None,
bias_initializer=None,
name=None,
dtype=None,
**kwargs
)
```
Note that this cell is not optimized for performance. Please use `tf.contrib.cudnn_rnn.CudnnGRU` for better performance on GPU, or `tf.contrib.rnn.GRUBlockCellV2` for better performance on CPU.
| Args |
| `num_units` | int, The number of units in the GRU cell. |
| `activation` | Nonlinearity to use. Default: `tanh`. |
| `reuse` | (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. |
| `kernel_initializer` | (optional) The initializer to use for the weight and projection matrices. |
| `bias_initializer` | (optional) The initializer to use for the bias. |
| `name` | String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. |
| `dtype` | Default dtype of the layer (default of `None` means use the type of the first input). Required when `build` is called before `call`. |
| `**kwargs` | Dict, keyword named properties for common layer attributes, like `trainable` etc when constructing the cell from configs of get\_config(). References: Learning Phrase Representations using RNN Encoder Decoder for Statistical Machine Translation: [Cho et al., 2014](https://aclanthology.coli.uni-saarland.de/papers/D14-1179/d14-1179) ([pdf](http://emnlp2014.org/papers/pdf/EMNLP2014179.pdf)) |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L268-L297)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.LSTMStateTuple tf.compat.v1.nn.rnn\_cell.LSTMStateTuple
========================================
Tuple used by LSTM Cells for `state_size`, `zero_state`, and output state.
```
tf.compat.v1.nn.rnn_cell.LSTMStateTuple(
c, h
)
```
Stores two elements: `(c, h)`, in that order. Where `c` is the hidden state and `h` is the output.
Only used when `state_is_tuple=True`.
| Attributes |
| `c` | A `namedtuple` alias for field number 0 |
| `h` | A `namedtuple` alias for field number 1 |
| `dtype` | |
tensorflow tf.compat.v1.nn.rnn_cell.DropoutWrapper tf.compat.v1.nn.rnn\_cell.DropoutWrapper
========================================
Operator adding dropout to inputs and outputs of the given cell.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.DropoutWrapper(
cell,
input_keep_prob=1.0,
output_keep_prob=1.0,
state_keep_prob=1.0,
variational_recurrent=False,
input_size=None,
dtype=None,
seed=None,
dropout_state_filter_visitor=None,
**kwargs
)
```
| Args |
| `cell` | an RNNCell, a projection to output\_size is added to it. |
| `input_keep_prob` | unit Tensor or float between 0 and 1, input keep probability; if it is constant and 1, no input dropout will be added. |
| `output_keep_prob` | unit Tensor or float between 0 and 1, output keep probability; if it is constant and 1, no output dropout will be added. |
| `state_keep_prob` | unit Tensor or float between 0 and 1, output keep probability; if it is constant and 1, no output dropout will be added. State dropout is performed on the outgoing states of the cell. **Note** the state components to which dropout is applied when `state_keep_prob` is in `(0, 1)` are also determined by the argument `dropout_state_filter_visitor` (e.g. by default dropout is never applied to the `c` component of an `LSTMStateTuple`). |
| `variational_recurrent` | Python bool. If `True`, then the same dropout pattern is applied across all time steps per run call. If this parameter is set, `input_size` **must** be provided. |
| `input_size` | (optional) (possibly nested tuple of) `TensorShape` objects containing the depth(s) of the input tensors expected to be passed in to the `DropoutWrapper`. Required and used **iff** `variational_recurrent = True` and `input_keep_prob < 1`. |
| `dtype` | (optional) The `dtype` of the input, state, and output tensors. Required and used **iff** `variational_recurrent = True`. |
| `seed` | (optional) integer, the randomness seed. |
| `dropout_state_filter_visitor` | (optional), default: (see below). Function that takes any hierarchical level of the state and returns a scalar or depth=1 structure of Python booleans describing which terms in the state should be dropped out. In addition, if the function returns `True`, dropout is applied across this sublevel. If the function returns `False`, dropout is not applied across this entire sublevel. Default behavior: perform dropout on all terms except the memory (`c`) state of `LSTMCellState` objects, and don't try to apply dropout to `TensorArray` objects: `def dropout_state_filter_visitor(s): if isinstance(s, LSTMCellState): # Never perform dropout on the c state. return LSTMCellState(c=False, h=True) elif isinstance(s, TensorArray): return False return True` |
| `**kwargs` | dict of keyword arguments for base layer. |
| Raises |
| `TypeError` | if `cell` is not an `RNNCell`, or `keep_state_fn` is provided but not `callable`. |
| `ValueError` | if any of the keep\_probs are not between 0 and 1. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
| `wrapped_cell` | |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cell_wrappers.py#L148-L150)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.ResidualWrapper tf.compat.v1.nn.rnn\_cell.ResidualWrapper
=========================================
RNNCell wrapper that ensures cell inputs are added to the outputs.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.ResidualWrapper(
cell, residual_fn=None, **kwargs
)
```
| Args |
| `cell` | An instance of `RNNCell`. |
| `residual_fn` | (Optional) The function to map raw cell inputs and raw cell outputs to the actual cell outputs of the residual network. Defaults to calling nest.map\_structure on (lambda i, o: i + o), inputs and outputs. |
| `**kwargs` | dict of keyword arguments for base layer. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cell_wrappers.py#L148-L150)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.DeviceWrapper tf.compat.v1.nn.rnn\_cell.DeviceWrapper
=======================================
Operator that ensures an RNNCell runs on a particular device.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.DeviceWrapper(
cell, device, **kwargs
)
```
| Args |
| `cell` | An instance of `RNNCell`. |
| `device` | A device string or function, for passing to [`tf.device`](../../../../device). |
| `**kwargs` | dict of keyword arguments for base layer. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cell_wrappers.py#L548-L551)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.RNNCell tf.compat.v1.nn.rnn\_cell.RNNCell
=================================
Abstract object representing an RNN cell.
Inherits From: [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.RNNCell(
trainable=True, name=None, dtype=None, **kwargs
)
```
Every `RNNCell` must have the properties below and implement `call` with the signature `(output, next_state) = call(input, state)`. The optional third input argument, `scope`, is allowed for backwards compatibility purposes; but should be left off for new subclasses.
This definition of cell differs from the definition used in the literature. In the literature, 'cell' refers to an object with a single scalar output. This definition refers to a horizontal array of such units.
An RNN cell, in the most abstract setting, is anything that has a state and performs some operation that takes a matrix of inputs. This operation results in an output matrix with `self.output_size` columns. If `self.state_size` is an integer, this operation also results in a new state matrix with `self.state_size` columns. If `self.state_size` is a (possibly nested tuple of) TensorShape object(s), then it should return a matching structure of Tensors having shape `[batch_size].concatenate(s)` for each `s` in `self.batch_size`.
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L268-L297)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.MultiRNNCell tf.compat.v1.nn.rnn\_cell.MultiRNNCell
======================================
RNN cell composed sequentially of multiple simple cells.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.MultiRNNCell(
cells, state_is_tuple=True
)
```
#### Example:
```
num_units = [128, 64]
cells = [BasicLSTMCell(num_units=n) for n in num_units]
stacked_rnn_cell = MultiRNNCell(cells)
```
| Args |
| `cells` | list of RNNCells that will be composed in this order. |
| `state_is_tuple` | If True, accepted and returned states are n-tuples, where `n = len(cells)`. If False, the states are all concatenated along the column axis. This latter behavior will soon be deprecated. |
| Raises |
| `ValueError` | if cells is empty (not allowed), or at least one of the cells returns a state tuple but the flag `state_is_tuple` is `False`. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L1149-L1156)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
| programming_docs |
tensorflow tf.compat.v1.nn.rnn_cell.BasicRNNCell tf.compat.v1.nn.rnn\_cell.BasicRNNCell
======================================
The most basic RNN cell.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.BasicRNNCell(
num_units, activation=None, reuse=None, name=None, dtype=None, **kwargs
)
```
Note that this cell is not optimized for performance. Please use `tf.contrib.cudnn_rnn.CudnnRNNTanh` for better performance on GPU.
| Args |
| `num_units` | int, The number of units in the RNN cell. |
| `activation` | Nonlinearity to use. Default: `tanh`. It could also be string that is within Keras activation function names. |
| `reuse` | (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. |
| `name` | String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. |
| `dtype` | Default dtype of the layer (default of `None` means use the type of the first input). Required when `build` is called before `call`. |
| `**kwargs` | Dict, keyword named properties for common layer attributes, like `trainable` etc when constructing the cell from configs of get\_config(). |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L268-L297)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.LSTMCell tf.compat.v1.nn.rnn\_cell.LSTMCell
==================================
Long short-term memory unit (LSTM) recurrent network cell.
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.LSTMCell(
num_units,
use_peepholes=False,
cell_clip=None,
initializer=None,
num_proj=None,
proj_clip=None,
num_unit_shards=None,
num_proj_shards=None,
forget_bias=1.0,
state_is_tuple=True,
activation=None,
reuse=None,
name=None,
dtype=None,
**kwargs
)
```
The default non-peephole implementation is based on (Gers et al., 1999). The peephole implementation is based on (Sak et al., 2014).
The class uses optional peep-hole connections, optional cell clipping, and an optional projection layer.
Note that this cell is not optimized for performance. Please use `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for better performance on CPU. References: Long short-term memory recurrent neural network architectures for large scale acoustic modeling: [Sak et al., 2014](https://www.isca-speech.org/archive/interspeech_2014/i14_0338.html) ([pdf](https://www.isca-speech.org/archive/archive_papers/interspeech_2014/i14_0338.pdf)) Learning to forget: [Gers et al., 1999](http://digital-library.theiet.org/content/conferences/10.1049/cp_19991218) ([pdf](https://arxiv.org/pdf/1409.2329.pdf)) Long Short-Term Memory: [Hochreiter et al., 1997](https://www.mitpressjournals.org/doi/abs/10.1162/neco.1997.9.8.1735) ([pdf](http://ml.jku.at/publications/older/3504.pdf))
| Args |
| `num_units` | int, The number of units in the LSTM cell. |
| `use_peepholes` | bool, set True to enable diagonal/peephole connections. |
| `cell_clip` | (optional) A float value, if provided the cell state is clipped by this value prior to the cell output activation. |
| `initializer` | (optional) The initializer to use for the weight and projection matrices. |
| `num_proj` | (optional) int, The output dimensionality for the projection matrices. If None, no projection is performed. |
| `proj_clip` | (optional) A float value. If `num_proj > 0` and `proj_clip` is provided, then the projected values are clipped elementwise to within `[-proj_clip, proj_clip]`. |
| `num_unit_shards` | Deprecated, will be removed by Jan. 2017. Use a variable\_scope partitioner instead. |
| `num_proj_shards` | Deprecated, will be removed by Jan. 2017. Use a variable\_scope partitioner instead. |
| `forget_bias` | Biases of the forget gate are initialized by default to 1 in order to reduce the scale of forgetting at the beginning of the training. Must set it manually to `0.0` when restoring from CudnnLSTM trained checkpoints. |
| `state_is_tuple` | If True, accepted and returned states are 2-tuples of the `c_state` and `m_state`. If False, they are concatenated along the column axis. This latter behavior will soon be deprecated. |
| `activation` | Activation function of the inner states. Default: `tanh`. It could also be string that is within Keras activation function names. |
| `reuse` | (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. |
| `name` | String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. |
| `dtype` | Default dtype of the layer (default of `None` means use the type of the first input). Required when `build` is called before `call`. |
| `**kwargs` | Dict, keyword named properties for common layer attributes, like `trainable` etc when constructing the cell from configs of get\_config(). When restoring from CudnnLSTM-trained checkpoints, use `CudnnCompatibleLSTMCell` instead. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L268-L297)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.nn.rnn_cell.BasicLSTMCell tf.compat.v1.nn.rnn\_cell.BasicLSTMCell
=======================================
Inherits From: [`RNNCell`](rnncell), [`Layer`](../../layers/layer), [`Layer`](../../../../keras/layers/layer), [`Module`](../../../../module)
```
tf.compat.v1.nn.rnn_cell.BasicLSTMCell(
num_units,
forget_bias=1.0,
state_is_tuple=True,
activation=None,
reuse=None,
name=None,
dtype=None,
**kwargs
)
```
Basic LSTM recurrent network cell.
The implementation is based on
We add forget\_bias (default: 1) to the biases of the forget gate in order to reduce the scale of forgetting in the beginning of the training.
It does not allow cell clipping, a projection layer, and does not use peep-hole connections: it is the basic baseline.
For advanced models, please use the full [`tf.compat.v1.nn.rnn_cell.LSTMCell`](lstmcell) that follows.
Note that this cell is not optimized for performance. Please use `tf.contrib.cudnn_rnn.CudnnLSTM` for better performance on GPU, or `tf.contrib.rnn.LSTMBlockCell` and `tf.contrib.rnn.LSTMBlockFusedCell` for better performance on CPU.
| Args |
| `num_units` | int, The number of units in the LSTM cell. |
| `forget_bias` | float, The bias added to forget gates (see above). Must set to `0.0` manually when restoring from CudnnLSTM-trained checkpoints. |
| `state_is_tuple` | If True, accepted and returned states are 2-tuples of the `c_state` and `m_state`. If False, they are concatenated along the column axis. The latter behavior will soon be deprecated. |
| `activation` | Activation function of the inner states. Default: `tanh`. It could also be string that is within Keras activation function names. |
| `reuse` | (optional) Python boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. |
| `name` | String, the name of the layer. Layers with the same name will share weights, but to avoid mistakes we require reuse=True in such cases. |
| `dtype` | Default dtype of the layer (default of `None` means use the type of the first input). Required when `build` is called before `call`. |
| `**kwargs` | Dict, keyword named properties for common layer attributes, like `trainable` etc when constructing the cell from configs of get\_config(). When restoring from CudnnLSTM-trained checkpoints, must use `CudnnCompatibleLSTMCell` instead. |
| Attributes |
| `graph` | |
| `output_size` | Integer or TensorShape: size of outputs produced by this cell. |
| `scope_name` | |
| `state_size` | size(s) of state(s) used by this cell. It can be represented by an Integer, a TensorShape or a tuple of Integers or TensorShapes. |
Methods
-------
### `apply`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/legacy_tf_layers/base.py#L239-L240)
```
apply(
*args, **kwargs
)
```
### `get_initial_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L239-L266)
```
get_initial_state(
inputs=None, batch_size=None, dtype=None
)
```
### `get_losses_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1341-L1358)
```
get_losses_for(
inputs
)
```
Retrieves losses relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of loss tensors of the layer that depend on `inputs`. |
### `get_updates_for`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/engine/base_layer_v1.py#L1322-L1339)
```
get_updates_for(
inputs
)
```
Retrieves updates relevant to a specific set of inputs.
| Args |
| `inputs` | Input tensor or list/tuple of input tensors. |
| Returns |
| List of update ops of the layer that depend on `inputs`. |
### `zero_state`
[View source](https://github.com/keras-team/keras/tree/v2.9.0/keras/layers/rnn/legacy_cells.py#L268-L297)
```
zero_state(
batch_size, dtype
)
```
Return zero-filled state tensor(s).
| Args |
| `batch_size` | int, float, or unit Tensor representing the batch size. |
| `dtype` | the data type to use for the state. |
| Returns |
| If `state_size` is an int or TensorShape, then the return value is a `N-D` tensor of shape `[batch_size, state_size]` filled with zeros. If `state_size` is a nested list or tuple, then the return value is a nested list or tuple (of the same structure) of `2-D` tensors with the shapes `[batch_size, s]` for each s in `state_size`. |
tensorflow tf.compat.v1.ragged.constant_value tf.compat.v1.ragged.constant\_value
===================================
Constructs a RaggedTensorValue from a nested Python list.
```
tf.compat.v1.ragged.constant_value(
pylist,
dtype=None,
ragged_rank=None,
inner_shape=None,
row_splits_dtype='int64'
)
```
#### Example:
```
tf.compat.v1.ragged.constant_value([[1, 2], [3], [4, 5, 6]])
tf.RaggedTensorValue(values=array([1, 2, 3, 4, 5, 6]),
row_splits=array([0, 2, 3, 6]))
```
All scalar values in `pylist` must have the same nesting depth `K`, and the returned `RaggedTensorValue` will have rank `K`. If `pylist` contains no scalar values, then `K` is one greater than the maximum depth of empty lists in `pylist`. All scalar values in `pylist` must be compatible with `dtype`.
| Args |
| `pylist` | A nested `list`, `tuple` or `np.ndarray`. Any nested element that is not a `list` or `tuple` must be a scalar value compatible with `dtype`. |
| `dtype` | `numpy.dtype`. The type of elements for the returned `RaggedTensor`. If not specified, then a default is chosen based on the scalar values in `pylist`. |
| `ragged_rank` | An integer specifying the ragged rank of the returned `RaggedTensorValue`. Must be nonnegative and less than `K`. Defaults to `max(0, K - 1)` if `inner_shape` is not specified. Defaults to `max(0, K * 1 - len(inner\_shape))`if`inner\_shape`is specified. </td> </tr><tr> <td>`inner\_shape`</td> <td> A tuple of integers specifying the shape for individual inner values in the returned`RaggedTensorValue`. Defaults to`()`if`ragged\_rank`is not specified. If`ragged\_rank`is specified, then a default is chosen based on the contents of`pylist`. </td> </tr><tr> <td>`row\_splits\_dtype`</td> <td> data type for the constructed`RaggedTensorValue`'s row_splits. One of`numpy.int32`or`numpy.int64`.
|
| Returns |
| A `tf.RaggedTensorValue` or `numpy.array` with rank `K` and the specified `ragged_rank`, containing the values from `pylist`. |
| Raises |
| `ValueError` | If the scalar values in `pylist` have inconsistent nesting depth; or if ragged\_rank or inner\_shape are incompatible with `pylist`. |
tensorflow tf.compat.v1.ragged.RaggedTensorValue tf.compat.v1.ragged.RaggedTensorValue
=====================================
Represents the value of a `RaggedTensor`.
```
tf.compat.v1.ragged.RaggedTensorValue(
values, row_splits
)
```
See [`tf.RaggedTensor`](../../../raggedtensor) for a description of ragged tensors.
| Args |
| `values` | A numpy array of any type and shape; or a RaggedTensorValue. |
| `row_splits` | A 1-D int32 or int64 numpy array. |
| Attributes |
| `dtype` | The numpy dtype of values in this tensor. |
| `flat_values` | The innermost `values` array for this ragged tensor value. |
| `nested_row_splits` | The row\_splits for all ragged dimensions in this ragged tensor value. |
| `ragged_rank` | The number of ragged dimensions in this ragged tensor value. |
| `row_splits` | The split indices for the ragged tensor value. |
| `shape` | A tuple indicating the shape of this RaggedTensorValue. |
| `values` | The concatenated values for all rows in this tensor. |
Methods
-------
### `to_list`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/ragged/ragged_tensor_value.py#L105-L114)
```
to_list()
```
Returns this ragged tensor value as a nested Python list.
tensorflow tf.ragged.constant tf.ragged.constant
==================
[View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/ragged/ragged_factory_ops.py#L33-L83) |
Constructs a constant RaggedTensor from a nested Python list.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.ragged.constant`](https://www.tensorflow.org/api_docs/python/tf/ragged/constant)
```
tf.ragged.constant(
pylist,
dtype=None,
ragged_rank=None,
inner_shape=None,
name=None,
row_splits_dtype=tf.dtypes.int64
)
```
#### Example:
```
tf.ragged.constant([[1, 2], [3], [4, 5, 6]])
<tf.RaggedTensor [[1, 2], [3], [4, 5, 6]]>
```
All scalar values in `pylist` must have the same nesting depth `K`, and the returned `RaggedTensor` will have rank `K`. If `pylist` contains no scalar values, then `K` is one greater than the maximum depth of empty lists in `pylist`. All scalar values in `pylist` must be compatible with `dtype`.
| Args |
| `pylist` | A nested `list`, `tuple` or `np.ndarray`. Any nested element that is not a `list`, `tuple` or `np.ndarray` must be a scalar value compatible with `dtype`. |
| `dtype` | The type of elements for the returned `RaggedTensor`. If not specified, then a default is chosen based on the scalar values in `pylist`. |
| `ragged_rank` | An integer specifying the ragged rank of the returned `RaggedTensor`. Must be nonnegative and less than `K`. Defaults to `max(0, K - 1)` if `inner_shape` is not specified. Defaults to `max(0, K - 1 - len(inner_shape))` if `inner_shape` is specified. |
| `inner_shape` | A tuple of integers specifying the shape for individual inner values in the returned `RaggedTensor`. Defaults to `()` if `ragged_rank` is not specified. If `ragged_rank` is specified, then a default is chosen based on the contents of `pylist`. |
| `name` | A name prefix for the returned tensor (optional). |
| `row_splits_dtype` | data type for the constructed `RaggedTensor`'s row\_splits. One of [`tf.int32`](../../../../tf#int32) or [`tf.int64`](../../../../tf#int64). |
| Returns |
| A potentially ragged tensor with rank `K` and the specified `ragged_rank`, containing the values from `pylist`. |
| Raises |
| `ValueError` | If the scalar values in `pylist` have inconsistent nesting depth; or if ragged\_rank or inner\_shape are incompatible with `pylist`. |
| programming_docs |
tensorflow tf.compat.v1.ragged.placeholder tf.compat.v1.ragged.placeholder
===============================
Creates a placeholder for a [`tf.RaggedTensor`](../../../raggedtensor) that will always be fed.
```
tf.compat.v1.ragged.placeholder(
dtype, ragged_rank, value_shape=None, name=None
)
```
@compatibility{eager} Placeholders are not compatible with eager execution.
| Args |
| `dtype` | The data type for the `RaggedTensor`. |
| `ragged_rank` | The ragged rank for the `RaggedTensor` |
| `value_shape` | The shape for individual flat values in the `RaggedTensor`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `RaggedTensor` that may be used as a handle for feeding a value, but not evaluated directly. |
| Raises |
| `RuntimeError` | if eager execution is enabled |
tensorflow tf.compat.v1.test.StubOutForTesting tf.compat.v1.test.StubOutForTesting
===================================
Support class for stubbing methods out for unit testing.
```
tf.compat.v1.test.StubOutForTesting()
```
#### Sample Usage:
You want os.path.exists() to always return true during testing.
stubs = StubOutForTesting() stubs.Set(os.path, 'exists', lambda x: 1) ... stubs.CleanUp()
The above changes os.path.exists into a lambda that returns 1. Once the ... part of the code finishes, the CleanUp() looks up the old value of os.path.exists and restores it.
Methods
-------
### `CleanUp`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L148-L151)
```
CleanUp()
```
Undoes all SmartSet() & Set() calls, restoring original definitions.
### `Set`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L230-L254)
```
Set(
parent, child_name, new_child
)
```
In parent, replace child\_name's old definition with new\_child.
The parent could be a module when the child is a function at module scope. Or the parent could be a class when a class' method is being replaced. The named child is set to new\_child, while the prior definition is saved away for later, when UnsetAll() is called.
This method supports the case where child\_name is a staticmethod or a classmethod of parent.
| Args |
| `parent` | The context in which the attribute child\_name is to be changed. |
| `child_name` | The name of the attribute to change. |
| `new_child` | The new value of the attribute. |
### `SmartSet`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L153-L214)
```
SmartSet(
obj, attr_name, new_attr
)
```
Replace obj.attr\_name with new\_attr.
This method is smart and works at the module, class, and instance level while preserving proper inheritance. It will not stub out C types however unless that has been explicitly allowed by the type.
This method supports the case where attr\_name is a staticmethod or a classmethod of obj.
#### Notes:
* If obj is an instance, then it is its class that will actually be stubbed. Note that the method Set() does not do that: if obj is an instance, it (and not its class) will be stubbed.
* The stubbing is using the builtin getattr and setattr. So, the **get** and **set** will be called when stubbing ( probably be to manipulate obj.**dict** instead of getattr() and setattr()).
| Args |
| `obj` | The object whose attributes we want to modify. |
| `attr_name` | The name of the attribute to modify. |
| `new_attr` | The new value for the attribute. |
| Raises |
| `AttributeError` | If the attribute cannot be found. |
### `SmartUnsetAll`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L216-L228)
```
SmartUnsetAll()
```
Reverses SmartSet() calls, restoring things to original definitions.
This method is automatically called when the StubOutForTesting() object is deleted; there is no need to call it explicitly.
It is okay to call SmartUnsetAll() repeatedly, as later calls have no effect if no SmartSet() calls have been made.
### `UnsetAll`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L256-L269)
```
UnsetAll()
```
Reverses Set() calls, restoring things to their original definitions.
This method is automatically called when the StubOutForTesting() object is deleted; there is no need to call it explicitly.
It is okay to call UnsetAll() repeatedly, as later calls have no effect if no Set() calls have been made.
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L142-L143)
```
__enter__()
```
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/platform/googletest.py#L145-L146)
```
__exit__(
unused_exc_type, unused_exc_value, unused_tb
)
```
tensorflow tf.compat.v1.test.test_src_dir_path tf.compat.v1.test.test\_src\_dir\_path
======================================
Creates an absolute test srcdir path given a relative path.
```
tf.compat.v1.test.test_src_dir_path(
relative_path
)
```
| Args |
| `relative_path` | a path relative to tensorflow root. e.g. "core/platform". |
| Returns |
| An absolute path to the linked in runfiles. |
tensorflow tf.compat.v1.test.compute_gradient_error tf.compat.v1.test.compute\_gradient\_error
==========================================
Computes the gradient error. (deprecated)
```
tf.compat.v1.test.compute_gradient_error(
x,
x_shape,
y,
y_shape,
x_init_value=None,
delta=0.001,
init_targets=None,
extra_feed_dict=None
)
```
Computes the maximum error for dy/dx between the computed Jacobian and the numerically estimated Jacobian.
This function will modify the tensors passed in as it adds more operations and hence changing the consumers of the operations of the input tensors.
This function adds operations to the current session. To compute the error using a particular device, such as a GPU, use the standard methods for setting a device (e.g. using with sess.graph.device() or setting a device function in the session constructor).
| Args |
| `x` | a tensor or list of tensors |
| `x_shape` | the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. |
| `y` | a tensor |
| `y_shape` | the dimensions of y as a tuple or an array of ints. |
| `x_init_value` | (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. |
| `delta` | (optional) the amount of perturbation. |
| `init_targets` | list of targets to run to initialize model params. |
| `extra_feed_dict` | dict that allows fixing specified tensor values during the Jacobian calculation. |
| Returns |
| The maximum error in between the two Jacobians. |
tensorflow tf.compat.v1.test.assert_equal_graph_def tf.compat.v1.test.assert\_equal\_graph\_def
===========================================
Asserts that two `GraphDef`s are (mostly) the same.
```
tf.compat.v1.test.assert_equal_graph_def(
actual, expected, checkpoint_v2=False, hash_table_shared_name=False
)
```
Compares two `GraphDef` protos for equality, ignoring versions and ordering of nodes, attrs, and control inputs. Node names are used to match up nodes between the graphs, so the naming of nodes must be consistent.
| Args |
| `actual` | The `GraphDef` we have. |
| `expected` | The `GraphDef` we expected. |
| `checkpoint_v2` | boolean determining whether to ignore randomized attribute values that appear in V2 checkpoints. |
| `hash_table_shared_name` | boolean determining whether to ignore randomized shared\_names that appear in HashTableV2 op defs. |
| Raises |
| `AssertionError` | If the `GraphDef`s do not match. |
| `TypeError` | If either argument is not a `GraphDef`. |
tensorflow tf.compat.v1.test.compute_gradient tf.compat.v1.test.compute\_gradient
===================================
Computes and returns the theoretical and numerical Jacobian. (deprecated)
```
tf.compat.v1.test.compute_gradient(
x,
x_shape,
y,
y_shape,
x_init_value=None,
delta=0.001,
init_targets=None,
extra_feed_dict=None
)
```
If `x` or `y` is complex, the Jacobian will still be real but the corresponding Jacobian dimension(s) will be twice as large. This is required even if both input and output is complex since TensorFlow graphs are not necessarily holomorphic, and may have gradients not expressible as complex numbers. For example, if `x` is complex with shape `[m]` and `y` is complex with shape `[n]`, each Jacobian `J` will have shape `[m * 2, n * 2]` with
```
J[:m, :n] = d(Re y)/d(Re x)
J[:m, n:] = d(Im y)/d(Re x)
J[m:, :n] = d(Re y)/d(Im x)
J[m:, n:] = d(Im y)/d(Im x)
```
| Args |
| `x` | a tensor or list of tensors |
| `x_shape` | the dimensions of x as a tuple or an array of ints. If x is a list, then this is the list of shapes. |
| `y` | a tensor |
| `y_shape` | the dimensions of y as a tuple or an array of ints. |
| `x_init_value` | (optional) a numpy array of the same shape as "x" representing the initial value of x. If x is a list, this should be a list of numpy arrays. If this is none, the function will pick a random tensor as the initial value. |
| `delta` | (optional) the amount of perturbation. |
| `init_targets` | list of targets to run to initialize model params. |
| `extra_feed_dict` | dict that allows fixing specified tensor values during the Jacobian calculation. |
| Returns |
| Two 2-d numpy arrays representing the theoretical and numerical Jacobian for dy/dx. Each has "x\_size" rows and "y\_size" columns where "x\_size" is the number of elements in x and "y\_size" is the number of elements in y. If x is a list, returns a list of two numpy arrays. |
tensorflow tf.compat.v1.test.get_temp_dir tf.compat.v1.test.get\_temp\_dir
================================
Returns a temporary directory for use during tests.
```
tf.compat.v1.test.get_temp_dir()
```
Migrate to TF2
--------------
This function is removed in TF2. Please use [`TestCase.get_temp_dir`](https://www.tensorflow.org/agents/api_docs/python/tf_agents/utils/test_utils/TestCase#get_temp_dir) instead in a test case. Outside of a unit test, obtain a temporary directory through Python's `tempfile` module.
Description
-----------
There is no need to delete the directory after the test.
| Returns |
| The temporary directory. |
tensorflow Module: tf.compat.v1.config.optimizer Module: tf.compat.v1.config.optimizer
=====================================
Public API for tf.config.optimizer namespace.
Functions
---------
[`get_experimental_options(...)`](../../../config/optimizer/get_experimental_options): Get experimental optimizer options.
[`get_jit(...)`](../../../config/optimizer/get_jit): Returns JIT compilation configuration for code inside [`tf.function`](../../../function).
[`set_experimental_options(...)`](../../../config/optimizer/set_experimental_options): Set experimental optimizer options.
[`set_jit(...)`](../../../config/optimizer/set_jit): Configure JIT compilation. (deprecated argument values)
tensorflow Module: tf.compat.v1.config.threading Module: tf.compat.v1.config.threading
=====================================
Public API for tf.config.threading namespace.
Functions
---------
[`get_inter_op_parallelism_threads(...)`](../../../config/threading/get_inter_op_parallelism_threads): Get number of threads used for parallelism between independent operations.
[`get_intra_op_parallelism_threads(...)`](../../../config/threading/get_intra_op_parallelism_threads): Get number of threads used within an individual op for parallelism.
[`set_inter_op_parallelism_threads(...)`](../../../config/threading/set_inter_op_parallelism_threads): Set number of threads used for parallelism between independent operations.
[`set_intra_op_parallelism_threads(...)`](../../../config/threading/set_intra_op_parallelism_threads): Set number of threads used within an individual op for parallelism.
tensorflow Module: tf.compat.v1.config.experimental Module: tf.compat.v1.config.experimental
========================================
Public API for tf.config.experimental namespace.
Classes
-------
[`class ClusterDeviceFilters`](../../../config/experimental/clusterdevicefilters): Represent a collection of device filters for the remote workers in cluster.
[`class VirtualDeviceConfiguration`](../../../config/logicaldeviceconfiguration): Configuration class for a logical devices.
Functions
---------
[`disable_mlir_bridge(...)`](../../../config/experimental/disable_mlir_bridge): Disables experimental MLIR-Based TensorFlow Compiler Bridge.
[`disable_mlir_graph_optimization(...)`](../../../config/experimental/disable_mlir_graph_optimization): Disables experimental MLIR-Based TensorFlow Compiler Optimizations.
[`enable_mlir_bridge(...)`](../../../config/experimental/enable_mlir_bridge): Enables experimental MLIR-Based TensorFlow Compiler Bridge.
[`enable_mlir_graph_optimization(...)`](../../../config/experimental/enable_mlir_graph_optimization): Enables experimental MLIR-Based TensorFlow Compiler Optimizations.
[`enable_tensor_float_32_execution(...)`](../../../config/experimental/enable_tensor_float_32_execution): Enable or disable the use of TensorFloat-32 on supported hardware.
[`get_device_details(...)`](../../../config/experimental/get_device_details): Returns details about a physical devices.
[`get_device_policy(...)`](../../../config/experimental/get_device_policy): Gets the current device policy.
[`get_memory_growth(...)`](../../../config/experimental/get_memory_growth): Get if memory growth is enabled for a `PhysicalDevice`.
[`get_memory_info(...)`](../../../config/experimental/get_memory_info): Get memory info for the chosen device, as a dict.
[`get_memory_usage(...)`](../../../config/experimental/get_memory_usage): Get the current memory usage, in bytes, for the chosen device. (deprecated)
[`get_synchronous_execution(...)`](../../../config/experimental/get_synchronous_execution): Gets whether operations are executed synchronously or asynchronously.
[`get_virtual_device_configuration(...)`](../../../config/get_logical_device_configuration): Get the virtual device configuration for a [`tf.config.PhysicalDevice`](../../../config/physicaldevice).
[`get_visible_devices(...)`](../../../config/get_visible_devices): Get the list of visible physical devices.
[`list_logical_devices(...)`](../../../config/list_logical_devices): Return a list of logical devices created by runtime.
[`list_physical_devices(...)`](../../../config/list_physical_devices): Return a list of physical devices visible to the host runtime.
[`reset_memory_stats(...)`](../../../config/experimental/reset_memory_stats): Resets the tracked memory stats for the chosen device.
[`set_device_policy(...)`](../../../config/experimental/set_device_policy): Sets the current thread device policy.
[`set_memory_growth(...)`](../../../config/experimental/set_memory_growth): Set if memory growth should be enabled for a `PhysicalDevice`.
[`set_synchronous_execution(...)`](../../../config/experimental/set_synchronous_execution): Specifies whether operations are executed synchronously or asynchronously.
[`set_virtual_device_configuration(...)`](../../../config/set_logical_device_configuration): Set the logical device configuration for a [`tf.config.PhysicalDevice`](../../../config/physicaldevice).
[`set_visible_devices(...)`](../../../config/set_visible_devices): Set the list of visible devices.
[`tensor_float_32_execution_enabled(...)`](../../../config/experimental/tensor_float_32_execution_enabled): Returns whether TensorFloat-32 is enabled.
tensorflow tf.compat.v1.lite.toco_convert tf.compat.v1.lite.toco\_convert
===============================
Convert a TensorFlow GraphDef to TFLite. (deprecated)
```
tf.compat.v1.lite.toco_convert(
input_data, input_tensors, output_tensors, *args, **kwargs
)
```
This function is deprecated. Please use [`tf.lite.TFLiteConverter`](../../../lite/tfliteconverter) API instead. Conversion can be customized by providing arguments that are forwarded to `build_model_flags` and `build_conversion_flags` (see documentation for details). Args: input\_data: Input data (i.e. often `sess.graph_def`). input\_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output\_tensors: List of output tensors (only .name is used from this). \*args: See `build_model_flags` and `build_conversion_flags`. \*\*kwargs: See `build_model_flags` and `build_conversion_flags`.
| Returns |
| The converted TensorFlow Lite model in a bytes array. |
| Raises |
| Defined in `convert`. |
tensorflow tf.compat.v1.lite.TocoConverter tf.compat.v1.lite.TocoConverter
===============================
Convert a TensorFlow model into `output_format`.
This class has been deprecated. Please use [`lite.TFLiteConverter`](https://www.tensorflow.org/lite/api_docs/python/tf/lite/TFLiteConverter) instead.
Methods
-------
### `from_frozen_graph`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2822-L2832)
```
@classmethod
from_frozen_graph(
graph_def_file, input_arrays, output_arrays, input_shapes=None
)
```
Creates a TocoConverter class from a file containing a frozen graph. (deprecated)
### `from_keras_model_file`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2849-L2859)
```
@classmethod
from_keras_model_file(
model_file, input_arrays=None, input_shapes=None, output_arrays=None
)
```
Creates a TocoConverter class from a tf.keras model file. (deprecated)
### `from_saved_model`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2834-L2847)
```
@classmethod
from_saved_model(
saved_model_dir,
input_arrays=None,
input_shapes=None,
output_arrays=None,
tag_set=None,
signature_key=None
)
```
Creates a TocoConverter class from a SavedModel. (deprecated)
### `from_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2815-L2820)
```
@classmethod
from_session(
sess, input_tensors, output_tensors
)
```
Creates a TocoConverter class from a TensorFlow Session. (deprecated)
tensorflow tf.compat.v1.lite.TFLiteConverter tf.compat.v1.lite.TFLiteConverter
=================================
Convert a TensorFlow model into `output_format`.
```
tf.compat.v1.lite.TFLiteConverter(
graph_def,
input_tensors,
output_tensors,
input_arrays_with_shape=None,
output_arrays=None,
experimental_debug_info_func=None
)
```
This is used to convert from a TensorFlow GraphDef, SavedModel or tf.keras model into either a TFLite FlatBuffer or graph visualization.
#### Example usage:
```
# Converting a GraphDef from session.
converter = tf.compat.v1.lite.TFLiteConverter.from_session(
sess, in_tensors, out_tensors)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
# Converting a GraphDef from file.
converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph(
graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
# Converting a SavedModel.
converter = tf.compat.v1.lite.TFLiteConverter.from_saved_model(
saved_model_dir)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
# Converting a tf.keras model.
converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file(
keras_model)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)
```
| Args |
| `graph_def` | Frozen TensorFlow GraphDef. |
| `input_tensors` | List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. |
| `output_tensors` | List of output tensors (only .name is used from this). |
| `input_arrays_with_shape` | Tuple of strings representing input tensor names and list of integers representing input shapes (e.g., [("foo" : [1, 16, 16, 3])]). Use only when graph cannot be loaded into TensorFlow and when `input_tensors` and `output_tensors` are None. (default None) |
| `output_arrays` | List of output tensors to freeze graph with. Use only when graph cannot be loaded into TensorFlow and when `input_tensors` and `output_tensors` are None. (default None) |
| `experimental_debug_info_func` | An experimental function to retrieve the graph debug info for a set of nodes from the `graph_def`. |
| Raises |
| `ValueError` | Invalid arguments. |
| Attributes |
| `optimizations` | Experimental flag, subject to change. Set of optimizations to apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a set of values of type [`tf.lite.Optimize`](../../../lite/optimize)) |
| `representative_dataset` | A generator function used for integer quantization where each generated sample has the same order, type and shape as the inputs to the model. Usually, this is a small subset of a few hundred samples randomly chosen, in no particular order, from the training or evaluation dataset. This is an optional attribute, but required for full integer quantization, i.e, if [`tf.int8`](../../../../tf#int8) is the only supported type in `target_spec.supported_types`. Refer to [`tf.lite.RepresentativeDataset`](../../../lite/representativedataset). (default None) |
| `target_spec` | Experimental flag, subject to change. Specifications of target device, including supported ops set, supported types and a set of user's defined TensorFlow operators required in the TensorFlow Lite runtime. Refer to [`tf.lite.TargetSpec`](../../../lite/targetspec). |
| `inference_type` | Data type of numeric arrays, excluding the input layer. (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8}) |
| `inference_input_type` | Data type of the numeric arrays in the input layer. If `inference_input_type` is in {tf.int8, tf.uint8}, then `quantized_input_stats` must be provided. (default is the value assigned to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) |
| `inference_output_type` | Data type of the numeric arrays in the output layer. (default is the value assigned to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) |
| `quantized_input_stats` | Map of input tensor names to a tuple of floats representing the mean and standard deviation of the training data. (e.g., {"foo" : (0., 1.)}). Required if `inference_input_type` is tf.int8 or tf.uint8. (default None) |
| `default_ranges_stats` | Tuple of integers (min, max) representing range values for all numeric arrays without a specified range. Intended for experimenting with quantization via "dummy quantization". (default None) |
| `allow_custom_ops` | Boolean indicating whether to allow custom operations. When False any unknown operation is an error. When True, custom ops are created for any op that is unknown. The developer will need to provide these to the TensorFlow Lite runtime with a custom resolver. (default False) |
| `drop_control_dependency` | Boolean indicating whether to drop control dependencies silently. This is due to TFLite not supporting control dependencies. (default True) |
| `reorder_across_fake_quant` | Boolean indicating whether to reorder FakeQuant nodes in unexpected locations. Used when the location of the FakeQuant nodes is preventing graph transformations necessary to convert the graph. Results in a graph that differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) |
| `change_concat_input_ranges` | Boolean to change behavior of min/max ranges for inputs and outputs of the concat operator for quantized models. Changes the ranges of concat operator overlap when true. (default False) |
| `output_format` | Output file format. (default tf.compat.v1.lite.constants.TFLITE, must be in {tf.compat.v1.lite.constants.TFLITE, tf.compat.v1.lite.constants.GRAPHVIZ\_DOT}) |
| `dump_graphviz_dir` | Full filepath of folder to dump the graphs at various stages of processing GraphViz .dot files. Preferred over `output_format=tf.compat.v1.lite.constants.GRAPHVIZ_DOT` in order to keep the requirements of the output file. (default None) |
| `dump_graphviz_video` | Boolean indicating whether to dump the GraphViz .dot files after every graph transformation. Requires the `dump_graphviz_dir` flag to be specified. (default False) |
| `conversion_summary_dir` | Full path of the directory to store conversion logs. (default None) |
| `exclude_conversion_metadata` | Whether not to embed the conversion metadata into the converted model. (default False) |
| `target_ops` | Deprecated. Please use `target_spec.supported_ops` instead. |
| `post_training_quantize` | Deprecated. Please use `optimizations` instead and set it to `{tf.lite.Optimize.DEFAULT}`. (default False) |
| `experimental_new_converter` | Experimental flag, subject to change. Enables MLIR-based conversion. (default True) |
| `experimental_new_quantizer` | Experimental flag, subject to change. Enables MLIR-based quantization conversion instead of Flatbuffer-based conversion. (default True) |
Methods
-------
### `convert`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2793-L2805)
```
convert()
```
Converts a TensorFlow GraphDef based on instance variables.
| Returns |
| The converted data in serialized format. Either a TFLite Flatbuffer or a Graphviz graph depending on value in `output_format`. |
| Raises |
| `ValueError` | Input shape is not specified. None value for dimension in input\_tensor. |
### `from_frozen_graph`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2611-L2706)
```
@classmethod
from_frozen_graph(
graph_def_file, input_arrays, output_arrays, input_shapes=None
)
```
Creates a TFLiteConverter class from a file containing a frozen GraphDef.
| Args |
| `graph_def_file` | Full filepath of file containing frozen GraphDef. |
| `input_arrays` | List of input tensors to freeze graph with. |
| `output_arrays` | List of output tensors to freeze graph with. |
| `input_shapes` | Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) |
| Returns |
| TFLiteConverter class. |
| Raises |
| `IOError` | File not found. Unable to parse input file. |
| `ValueError` | The graph is not frozen. input\_arrays or output\_arrays contains an invalid tensor name. input\_shapes is not correctly defined when required |
### `from_keras_model_file`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2760-L2790)
```
@classmethod
from_keras_model_file(
model_file,
input_arrays=None,
input_shapes=None,
output_arrays=None,
custom_objects=None
)
```
Creates a TFLiteConverter class from a tf.keras model file.
| Args |
| `model_file` | Full filepath of HDF5 file containing the tf.keras model. |
| `input_arrays` | List of input tensors to freeze graph with. Uses input arrays from SignatureDef when none are provided. (default None) |
| `input_shapes` | Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) |
| `output_arrays` | List of output tensors to freeze graph with. Uses output arrays from SignatureDef when none are provided. (default None) |
| `custom_objects` | Dict mapping names (strings) to custom classes or functions to be considered during model deserialization. (default None) |
| Returns |
| TFLiteConverter class. |
### `from_saved_model`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2708-L2758)
```
@classmethod
from_saved_model(
saved_model_dir,
input_arrays=None,
input_shapes=None,
output_arrays=None,
tag_set=None,
signature_key=None
)
```
Creates a TFLiteConverter class from a SavedModel.
| Args |
| `saved_model_dir` | SavedModel directory to convert. |
| `input_arrays` | List of input tensors to freeze graph with. Uses input arrays from SignatureDef when none are provided. (default None) |
| `input_shapes` | Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) |
| `output_arrays` | List of output tensors to freeze graph with. Uses output arrays from SignatureDef when none are provided. (default None) |
| `tag_set` | Set of tags identifying the MetaGraphDef within the SavedModel to analyze. All tags in the tag set must be present. (default {tf.saved\_model.SERVING}) |
| `signature_key` | Key identifying SignatureDef containing inputs and outputs. (default tf.saved\_model.DEFAULT\_SERVING\_SIGNATURE\_DEF\_KEY) |
| Returns |
| TFLiteConverter class. |
### `from_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2587-L2609)
```
@classmethod
from_session(
sess, input_tensors, output_tensors
)
```
Creates a TFLiteConverter class from a TensorFlow Session.
| Args |
| `sess` | TensorFlow Session. |
| `input_tensors` | List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. |
| `output_tensors` | List of output tensors (only .name is used from this). |
| Returns |
| TFLiteConverter class. |
### `get_input_arrays`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/lite.py#L2095-L2104)
```
get_input_arrays()
```
Returns a list of the names of the input tensors.
| Returns |
| List of strings. |
| programming_docs |
tensorflow Module: tf.compat.v1.lite.experimental Module: tf.compat.v1.lite.experimental
======================================
Public API for tf.lite.experimental namespace.
Modules
-------
[`authoring`](experimental/authoring) module: Public API for tf.lite.experimental.authoring namespace.
Classes
-------
[`class Analyzer`](../../../lite/experimental/analyzer): Provides a collection of TFLite model analyzer tools.
[`class OpResolverType`](../../../lite/experimental/opresolvertype): Different types of op resolvers for Tensorflow Lite.
[`class QuantizationDebugOptions`](../../../lite/experimental/quantizationdebugoptions): Debug options to set up a given QuantizationDebugger.
[`class QuantizationDebugger`](../../../lite/experimental/quantizationdebugger): Debugger for Quantized TensorFlow Lite debug mode models.
Functions
---------
[`convert_op_hints_to_stubs(...)`](experimental/convert_op_hints_to_stubs): Converts a graphdef with LiteOp hints into stub operations. (deprecated)
[`load_delegate(...)`](../../../lite/experimental/load_delegate): Returns loaded Delegate object.
tensorflow tf.compat.v1.lite.OpHint tf.compat.v1.lite.OpHint
========================
A class that helps build tflite function invocations. (deprecated)
```
tf.compat.v1.lite.OpHint(
function_name, level=1, children_inputs_mappings=None, **kwargs
)
```
It allows you to take a bunch of TensorFlow ops and annotate the construction such that toco knows how to convert it to tflite. This embeds a pseudo function in a TensorFlow graph. This allows embedding high-level API usage information in a lower level TensorFlow implementation so that an alternative implementation can be substituted later.
Essentially, any "input" into this pseudo op is fed into an identity, and attributes are added to that input before being used by the constituent ops that make up the pseudo op. A similar process is done to any output that is to be exported from the current op.
| Args |
| `function_name` | Name of the function (the custom op name in tflite) |
| `level` | OpHint level. |
| `children_inputs_mappings` | Children OpHint inputs/outputs mapping. children\_inputs\_mappings should like below: "parent\_first\_child\_input": [{"parent\_input\_index": num, "child\_input\_index": num}, ...] "parent\_last\_child\_output": [{"parent\_output\_index": num, "child\_output\_index": num}, ...] "internal\_children\_input\_output": [{"child\_input\_index": num, "child\_output\_index": num}, ...] |
| `**kwargs` | Keyword arguments of any constant attributes for the function. |
Child Classes
-------------
[`class OpHintArgumentTracker`](ophint/ophintargumenttracker)
Methods
-------
### `add_input`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/op_hint.py#L384-L404)
```
add_input(
*args, **kwargs
)
```
Add a wrapped input argument to the hint.
| Args |
| `*args` | The input tensor. |
| `**kwargs` | "name" label "tag" a tag to group multiple arguments that will be aggregated. I.e. a string like 'cool\_input'. Basically multiple inputs can be added to the same hint for parallel operations that will eventually be combined. An example would be static\_rnn which creates multiple copies of state or inputs. "aggregate" aggregation strategy that is valid only for tag non None. Acceptable values are OpHint.AGGREGATE\_FIRST, OpHint.AGGREGATE\_LAST, and OpHint.AGGREGATE\_STACK. "index\_override" The global index to use. This corresponds to the argument order in the final stub that will be generated. |
| Returns |
| The wrapped input tensor. |
### `add_inputs`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/op_hint.py#L428-L445)
```
add_inputs(
*args, **kwargs
)
```
Add a sequence of inputs to the function invocation.
| Args |
| `*args` | List of inputs to be converted (should be Tf.Tensor). |
| `**kwargs` | This allows 'names' which should be a list of names. |
| Returns |
| Wrapped inputs (identity standins that have additional metadata). These are also are also tf.Tensor's. |
### `add_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/op_hint.py#L406-L426)
```
add_output(
*args, **kwargs
)
```
Add a wrapped output argument to the hint.
| Args |
| `*args` | The output tensor. |
| `**kwargs` | "name" label "tag" a tag to group multiple arguments that will be aggregated. I.e. a string like 'cool\_input'. Basically multiple inputs can be added to the same hint for parallel operations that will eventually be combined. An example would be static\_rnn which creates multiple copies of state or inputs. "aggregate" aggregation strategy that is valid only for tag non None. Acceptable values are OpHint.AGGREGATE\_FIRST, OpHint.AGGREGATE\_LAST, and OpHint.AGGREGATE\_STACK. "index\_override" The global index to use. This corresponds to the argument order in the final stub that will be generated. |
| Returns |
| The wrapped output tensor. |
### `add_outputs`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/op_hint.py#L447-L464)
```
add_outputs(
*args, **kwargs
)
```
Add a sequence of outputs to the function invocation.
| Args |
| `*args` | List of outputs to be converted (should be tf.Tensor). |
| `**kwargs` | See |
| Returns |
| Wrapped outputs (identity standins that have additional metadata). These are also tf.Tensor's. |
| Class Variables |
| AGGREGATE\_FIRST | `'first'` |
| AGGREGATE\_LAST | `'last'` |
| AGGREGATE\_STACK | `'stack'` |
| CHILDREN\_INPUTS\_MAPPINGS | `'_tflite_children_ophint_inputs_mapping'` |
| FUNCTION\_AGGREGATE\_ATTR | `'_tflite_function_aggregate'` |
| FUNCTION\_INPUT\_INDEX\_ATTR | `'_tflite_function_input_index'` |
| FUNCTION\_LEVEL\_ATTR | `'_tflite_ophint_level'` |
| FUNCTION\_NAME\_ATTR | `'_tflite_function_name'` |
| FUNCTION\_OUTPUT\_INDEX\_ATTR | `'_tflite_function_output_index'` |
| FUNCTION\_SORT\_INDEX\_ATTR | `'_tflite_function_sort_index'` |
| FUNCTION\_UUID\_ATTR | `'_tflite_function_uuid'` |
| TFLITE\_INPUT\_INDICES | `'_tflite_input_indices'` |
tensorflow Module: tf.compat.v1.lite.constants Module: tf.compat.v1.lite.constants
===================================
Public API for tf.lite.constants namespace.
| Other Members |
| FLOAT | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) 32-bit (single precision) floating-point. |
| FLOAT16 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) 16-bit (half precision) floating-point. |
| GRAPHVIZ\_DOT | `3` |
| INT16 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Signed 16-bit integer. |
| INT32 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Signed 32-bit integer. |
| INT64 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Signed 64-bit integer. |
| INT8 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Signed 8-bit integer. |
| QUANTIZED\_UINT8 | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Unsigned 8-bit (byte) integer. |
| STRING | Instance of [`tf.dtypes.DType`](../../../dtypes/dtype) Variable-length string, represented as byte array. |
| TFLITE | `2` |
tensorflow Module: tf.compat.v1.lite.experimental.authoring Module: tf.compat.v1.lite.experimental.authoring
================================================
Public API for tf.lite.experimental.authoring namespace.
Functions
---------
[`compatible(...)`](../../../../lite/experimental/authoring/compatible): Wraps [`tf.function`](../../../../function) into a callable function with TFLite compatibility checking.
tensorflow tf.compat.v1.lite.experimental.convert_op_hints_to_stubs tf.compat.v1.lite.experimental.convert\_op\_hints\_to\_stubs
============================================================
Converts a graphdef with LiteOp hints into stub operations. (deprecated)
```
tf.compat.v1.lite.experimental.convert_op_hints_to_stubs(
session=None,
graph_def=None,
write_callback=(lambda graph_def, comments: None)
)
```
This is used to prepare for toco conversion of complex intrinsic usages. Note: only one of session or graph\_def should be used, not both.
| Args |
| `session` | A TensorFlow session that contains the graph to convert. |
| `graph_def` | A graph def that we should convert. |
| `write_callback` | A function pointer that can be used to write intermediate steps of graph transformation (optional). |
| Returns |
| A new graphdef with all ops contained in OpHints being replaced by a single op call with the right parameters. |
| Raises |
| `ValueError` | If both session and graph\_def are provided. |
tensorflow tf.compat.v1.lite.OpHint.OpHintArgumentTracker tf.compat.v1.lite.OpHint.OpHintArgumentTracker
==============================================
Conceptually tracks indices of arguments of "OpHint functions".
```
tf.compat.v1.lite.OpHint.OpHintArgumentTracker(
function_name,
unique_function_id,
node_name_prefix,
attr_name,
level=1,
children_inputs_mappings=None
)
```
The inputs and arguments of these functions both use an instance of the class so they can have independent numbering.
| Args |
| `function_name` | Name of the function that this tracks arguments for. |
| `unique_function_id` | UUID of function that this tracks arguments for. |
| `node_name_prefix` | How identities that are created are named. |
| `attr_name` | Name of attribute to use to store the index for this hint. i.e. FUNCTION\_INPUT\_INDEX or FUNCTION\_OUTPUT\_INDEX |
| `level` | Hierarchical level of the Ophint node, a number. |
| `children_inputs_mappings` | Inputs/Outputs mapping for children hints. |
Methods
-------
### `add`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/lite/python/op_hint.py#L225-L306)
```
add(
arg, tag=None, name=None, aggregate=None, index_override=None
)
```
Return a wrapped tensor of an input tensor as an argument.
| Args |
| `arg` | A TensorFlow tensor that should be considered an argument. |
| `tag` | String tag to identify arguments that should be packed. |
| `name` | Name of argument. This is included in the Identity hint op names. |
| `aggregate` | Strategy to aggregate. Acceptable values are OpHint.AGGREGATE\_FIRST, OpHint.AGGREGATE\_LAST, and OpHint.AGGREGATE\_STACK. Note, aggregate is only valid if tag is specified. |
| `index_override` | Specify what input/output index should this be in the final stub. i.e. add(arg0, index=1); add(arg1, index=0) will make the final stub be as stub\_func(inputs[arg1, arg0], outputs=[]) rather than the default call order based ordering. |
| Returns |
| A tensor representing the wrapped argument. |
| Raises |
| `ValueError` | When indices are not consistent. |
tensorflow tf.compat.v1.feature_column.input_layer tf.compat.v1.feature\_column.input\_layer
=========================================
Returns a dense `Tensor` as input layer based on given `feature_columns`.
```
tf.compat.v1.feature_column.input_layer(
features,
feature_columns,
weight_collections=None,
trainable=True,
cols_to_vars=None,
cols_to_output_tensors=None
)
```
Generally a single example in training data is described with FeatureColumns. At the first layer of the model, this column oriented data should be converted to a single `Tensor`.
#### Example:
```
price = numeric_column('price')
keywords_embedded = embedding_column(
categorical_column_with_hash_bucket("keywords", 10K), dimensions=16)
columns = [price, keywords_embedded, ...]
features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
dense_tensor = input_layer(features, columns)
for units in [128, 64, 32]:
dense_tensor = tf.compat.v1.layers.dense(dense_tensor, units, tf.nn.relu)
prediction = tf.compat.v1.layers.dense(dense_tensor, 1)
```
| Args |
| `features` | A mapping from key to tensors. `_FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values can be a `SparseTensor` or a `Tensor` depends on corresponding `_FeatureColumn`. |
| `feature_columns` | An iterable containing the FeatureColumns to use as inputs to your model. All items should be instances of classes derived from `_DenseColumn` such as `numeric_column`, `embedding_column`, `bucketized_column`, `indicator_column`. If you have categorical features, you can wrap them with an `embedding_column` or `indicator_column`. |
| `weight_collections` | A list of collection names to which the Variable will be added. Note that variables will also be added to collections `tf.GraphKeys.GLOBAL_VARIABLES` and `ops.GraphKeys.MODEL_VARIABLES`. |
| `trainable` | If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `cols_to_vars` | If not `None`, must be a dictionary that will be filled with a mapping from `_FeatureColumn` to list of `Variable`s. For example, after the call, we might have cols\_to\_vars = {\_EmbeddingColumn( categorical\_column=\_HashedCategoricalColumn( key='sparse\_feature', hash\_bucket\_size=5, dtype=tf.string), dimension=10): [ |
| `cols_to_output_tensors` | If not `None`, must be a dictionary that will be filled with a mapping from '\_FeatureColumn' to the associated output `Tensor`s. |
| Returns |
| A `Tensor` which represents input layer of a model. Its shape is (batch\_size, first\_layer\_dimension) and its dtype is `float32`. first\_layer\_dimension is determined based on given `feature_columns`. |
| Raises |
| `ValueError` | if an item in `feature_columns` is not a `_DenseColumn`. |
tensorflow tf.compat.v1.feature_column.make_parse_example_spec tf.compat.v1.feature\_column.make\_parse\_example\_spec
=======================================================
Creates parsing spec dictionary from input feature\_columns.
```
tf.compat.v1.feature_column.make_parse_example_spec(
feature_columns
)
```
The returned dictionary can be used as arg 'features' in [`tf.io.parse_example`](../../../io/parse_example).
#### Typical usage example:
```
# Define features and transformations
feature_a = categorical_column_with_vocabulary_file(...)
feature_b = numeric_column(...)
feature_c_bucketized = bucketized_column(numeric_column("feature_c"), ...)
feature_a_x_feature_c = crossed_column(
columns=["feature_a", feature_c_bucketized], ...)
feature_columns = set(
[feature_b, feature_c_bucketized, feature_a_x_feature_c])
features = tf.io.parse_example(
serialized=serialized_examples,
features=make_parse_example_spec(feature_columns))
```
For the above example, make\_parse\_example\_spec would return the dict:
```
{
"feature_a": parsing_ops.VarLenFeature(tf.string),
"feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32),
"feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32)
}
```
| Args |
| `feature_columns` | An iterable containing all feature columns. All items should be instances of classes derived from `_FeatureColumn`. |
| Returns |
| A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` value. |
| Raises |
| `ValueError` | If any of the given `feature_columns` is not a `_FeatureColumn` instance. |
tensorflow tf.compat.v1.feature_column.shared_embedding_columns tf.compat.v1.feature\_column.shared\_embedding\_columns
=======================================================
List of dense columns that convert from sparse, categorical input.
```
tf.compat.v1.feature_column.shared_embedding_columns(
categorical_columns,
dimension,
combiner='mean',
initializer=None,
shared_embedding_collection_name=None,
ckpt_to_load_from=None,
tensor_name_in_ckpt=None,
max_norm=None,
trainable=True,
use_safe_embedding_lookup=True
)
```
This is similar to `embedding_column`, except that it produces a list of embedding columns that share the same embedding weights.
Use this when your inputs are sparse and of the same type (e.g. watched and impression video IDs that share the same vocabulary), and you want to convert them to a dense representation (e.g., to feed to a DNN).
Inputs must be a list of categorical columns created by any of the `categorical_column_*` function. They must all be of the same type and have the same arguments except `key`. E.g. they can be categorical\_column\_with\_vocabulary\_file with the same vocabulary\_file. Some or all columns could also be weighted\_categorical\_column.
Here is an example embedding of two features for a DNNClassifier model:
```
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
estimator = tf.estimator.DNNClassifier(feature_columns=columns, ...)
label_column = ...
def input_fn():
features = tf.io.parse_example(
..., features=make_parse_example_spec(columns + [label_column]))
labels = features.pop(label_column.name)
return features, labels
estimator.train(input_fn=input_fn, steps=100)
```
Here is an example using `shared_embedding_columns` with model\_fn:
```
def model_fn(features, ...):
watched_video_id = categorical_column_with_vocabulary_file(
'watched_video_id', video_vocabulary_file, video_vocabulary_size)
impression_video_id = categorical_column_with_vocabulary_file(
'impression_video_id', video_vocabulary_file, video_vocabulary_size)
columns = shared_embedding_columns(
[watched_video_id, impression_video_id], dimension=10)
dense_tensor = input_layer(features, columns)
# Form DNN layers, calculate loss, and return EstimatorSpec.
...
```
| Args |
| `categorical_columns` | List of categorical columns created by a `categorical_column_with_*` function. These columns produce the sparse IDs that are inputs to the embedding lookup. All columns must be of the same type and have the same arguments except `key`. E.g. they can be categorical\_column\_with\_vocabulary\_file with the same vocabulary\_file. Some or all columns could also be weighted\_categorical\_column. |
| `dimension` | An integer specifying dimension of the embedding, must be > 0. |
| `combiner` | A string specifying how to reduce if there are multiple entries in a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with 'mean' the default. 'sqrtn' often achieves good accuracy, in particular with bag-of-words columns. Each of this can be thought as example level normalizations on the column. For more information, see `tf.embedding_lookup_sparse`. |
| `initializer` | A variable initializer function to be used in embedding variable initialization. If not specified, defaults to `truncated_normal_initializer` with mean `0.0` and standard deviation `1/sqrt(dimension)`. |
| `shared_embedding_collection_name` | Optional name of the collection where shared embedding weights are added. If not given, a reasonable name will be chosen based on the names of `categorical_columns`. This is also used in `variable_scope` when creating shared embedding weights. |
| `ckpt_to_load_from` | String representing checkpoint name/pattern from which to restore column weights. Required if `tensor_name_in_ckpt` is not `None`. |
| `tensor_name_in_ckpt` | Name of the `Tensor` in `ckpt_to_load_from` from which to restore the column weights. Required if `ckpt_to_load_from` is not `None`. |
| `max_norm` | If not `None`, each embedding is clipped if its l2-norm is larger than this value, before combining. |
| `trainable` | Whether or not the embedding is trainable. Default is True. |
| `use_safe_embedding_lookup` | If true, uses safe\_embedding\_lookup\_sparse instead of embedding\_lookup\_sparse. safe\_embedding\_lookup\_sparse ensures there are no empty rows and all weights and ids are positive at the expense of extra compute cost. This only applies to rank 2 (NxM) shaped input tensors. Defaults to true, consider turning off if the above checks are not needed. Note that having empty rows will not trigger any error though the output result might be 0 or omitted. |
| Returns |
| A list of dense columns that converts from sparse input. The order of results follows the ordering of `categorical_columns`. |
| Raises |
| `ValueError` | if `dimension` not > 0. |
| `ValueError` | if any of the given `categorical_columns` is of different type or has different arguments than the others. |
| `ValueError` | if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt` is specified. |
| `ValueError` | if `initializer` is specified and is not callable. |
| `RuntimeError` | if eager execution is enabled. |
| programming_docs |
tensorflow tf.compat.v1.feature_column.linear_model tf.compat.v1.feature\_column.linear\_model
==========================================
Returns a linear prediction `Tensor` based on given `feature_columns`.
```
tf.compat.v1.feature_column.linear_model(
features,
feature_columns,
units=1,
sparse_combiner='sum',
weight_collections=None,
trainable=True,
cols_to_vars=None
)
```
This function generates a weighted sum based on output dimension `units`. Weighted sum refers to logits in classification problems. It refers to the prediction itself for linear regression problems.
Note on supported columns: `linear_model` treats categorical columns as `indicator_column`s. To be specific, assume the input as `SparseTensor` looks like:
```
shape = [2, 2]
{
[0, 0]: "a"
[1, 0]: "b"
[1, 1]: "c"
}
```
`linear_model` assigns weights for the presence of "a", "b", "c' implicitly, just like `indicator_column`, while `input_layer` explicitly requires wrapping each of categorical columns with an `embedding_column` or an `indicator_column`.
#### Example of usage:
```
price = numeric_column('price')
price_buckets = bucketized_column(price, boundaries=[0., 10., 100., 1000.])
keywords = categorical_column_with_hash_bucket("keywords", 10K)
keywords_price = crossed_column('keywords', price_buckets, ...)
columns = [price_buckets, keywords, keywords_price ...]
features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
prediction = linear_model(features, columns)
```
The `sparse_combiner` argument works as follows For example, for two features represented as the categorical columns:
```
# Feature 1
shape = [2, 2]
{
[0, 0]: "a"
[0, 1]: "b"
[1, 0]: "c"
}
# Feature 2
shape = [2, 3]
{
[0, 0]: "d"
[1, 0]: "e"
[1, 1]: "f"
[1, 2]: "f"
}
```
with `sparse_combiner` as "mean", the linear model outputs consequently are:
```
y_0 = 1.0 / 2.0 * ( w_a + w_b ) + w_d + b
y_1 = w_c + 1.0 / 3.0 * ( w_e + 2.0 * w_f ) + b
```
where `y_i` is the output, `b` is the bias, and `w_x` is the weight assigned to the presence of `x` in the input features.
| Args |
| `features` | A mapping from key to tensors. `_FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values are `Tensor` or `SparseTensor` depending on corresponding `_FeatureColumn`. |
| `feature_columns` | An iterable containing the FeatureColumns to use as inputs to your model. All items should be instances of classes derived from `_FeatureColumn`s. |
| `units` | An integer, dimensionality of the output space. Default value is 1. |
| `sparse_combiner` | A string specifying how to reduce if a categorical column is multivalent. Except `numeric_column`, almost all columns passed to `linear_model` are considered as categorical columns. It combines each categorical column independently. Currently "mean", "sqrtn" and "sum" are supported, with "sum" the default for linear model. "sqrtn" often achieves good accuracy, in particular with bag-of-words columns. * "sum": do not normalize features in the column
* "mean": do l1 normalization on features in the column
* "sqrtn": do l2 normalization on features in the column
|
| `weight_collections` | A list of collection names to which the Variable will be added. Note that, variables will also be added to collections `tf.GraphKeys.GLOBAL_VARIABLES` and `ops.GraphKeys.MODEL_VARIABLES`. |
| `trainable` | If `True` also add the variable to the graph collection `GraphKeys.TRAINABLE_VARIABLES` (see [`tf.Variable`](../../../variable)). |
| `cols_to_vars` | If not `None`, must be a dictionary that will be filled with a mapping from `_FeatureColumn` to associated list of `Variable`s. For example, after the call, we might have cols\_to\_vars = { \_NumericColumn( key='numeric\_feature1', shape=(1,): [], 'bias': [], \_NumericColumn( key='numeric\_feature2', shape=(2,)): []} If a column creates no variables, its value will be an empty list. Note that cols\_to\_vars will also contain a string key 'bias' that maps to a list of Variables. |
| Returns |
| A `Tensor` which represents predictions/logits of a linear model. Its shape is (batch\_size, units) and its dtype is `float32`. |
| Raises |
| `ValueError` | if an item in `feature_columns` is neither a `_DenseColumn` nor `_CategoricalColumn`. |
tensorflow tf.compat.v1.feature_column.categorical_column_with_vocabulary_file tf.compat.v1.feature\_column.categorical\_column\_with\_vocabulary\_file
========================================================================
A `CategoricalColumn` with a vocabulary file.
```
tf.compat.v1.feature_column.categorical_column_with_vocabulary_file(
key,
vocabulary_file,
vocabulary_size=None,
num_oov_buckets=0,
default_value=None,
dtype=tf.dtypes.string
)
```
Use this when your inputs are in string or integer format, and you have a vocabulary file that maps each value to an integer ID. By default, out-of-vocabulary values are ignored. Use either (but not both) of `num_oov_buckets` and `default_value` to specify how to include out-of-vocabulary values.
For input dictionary `features`, `features[key]` is either `Tensor` or `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int and `''` for string, which will be dropped by this feature column.
Example with `num_oov_buckets`: File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state abbreviation. All inputs with values in that file are assigned an ID 0-49, corresponding to its line number. All other values are hashed and assigned an ID 50-54.
```
import tensorflow as tf
states = tf.feature_column.categorical_column_with_vocabulary_file(
key='states', vocabulary_file='states.txt', vocabulary_size=5,
num_oov_buckets=1)
columns = [states]
features = {'states':tf.constant([['california', 'georgia', 'michigan',
'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
'texas']])}
linear_prediction = tf.compat.v1.feature_column.linear_model(features,
columns)
```
Example with `default_value`: File '/us/states.txt' contains 51 lines - the first line is 'XX', and the other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX' in input, and other values missing from the file, will be assigned ID 0. All others are assigned the corresponding line number 1-50.
```
import tensorflow as tf
states = tf.feature_column.categorical_column_with_vocabulary_file(
key='states', vocabulary_file='states.txt', vocabulary_size=6,
default_value=0)
columns = [states]
features = {'states':tf.constant([['california', 'georgia', 'michigan',
'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
'texas']])}
linear_prediction = tf.compat.v1.feature_column.linear_model(features,
columns)
```
And to make an embedding with either:
```
import tensorflow as tf
states = tf.feature_column.categorical_column_with_vocabulary_file(
key='states', vocabulary_file='states.txt', vocabulary_size=5,
num_oov_buckets=1)
columns = [tf.feature_column.embedding_column(states, 3)]
features = {'states':tf.constant([['california', 'georgia', 'michigan',
'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
'texas']])}
input_layer = tf.keras.layers.DenseFeatures(columns)
dense_tensor = input_layer(features)
```
| Args |
| `key` | A unique string identifying the input feature. It is used as the column name and the dictionary key for feature parsing configs, feature `Tensor` objects, and feature columns. |
| `vocabulary_file` | The vocabulary file name. |
| `vocabulary_size` | Number of the elements in the vocabulary. This must be no greater than length of `vocabulary_file`, if less than length, later values are ignored. If None, it is set to the length of `vocabulary_file`. |
| `num_oov_buckets` | Non-negative integer, the number of out-of-vocabulary buckets. All out-of-vocabulary inputs will be assigned IDs in the range `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of the input value. A positive `num_oov_buckets` can not be specified with `default_value`. |
| `default_value` | The integer ID value to return for out-of-vocabulary feature values, defaults to `-1`. This can not be specified with a positive `num_oov_buckets`. |
| `dtype` | The type of features. Only string and integer types are supported. |
| Returns |
| A `CategoricalColumn` with a vocabulary file. |
| Raises |
| `ValueError` | `vocabulary_file` is missing or cannot be opened. |
| `ValueError` | `vocabulary_size` is missing or < 1. |
| `ValueError` | `num_oov_buckets` is a negative integer. |
| `ValueError` | `num_oov_buckets` and `default_value` are both specified. |
| `ValueError` | `dtype` is neither string nor integer. |
tensorflow tf.compat.v1.debugging.assert_shapes tf.compat.v1.debugging.assert\_shapes
=====================================
Assert tensor shapes and dimension size relationships between tensors.
```
tf.compat.v1.debugging.assert_shapes(
shapes, data=None, summarize=None, message=None, name=None
)
```
This Op checks that a collection of tensors shape relationships satisfies given constraints.
#### Example:
```
n = 10
q = 3
d = 7
x = tf.zeros([n,q])
y = tf.ones([n,d])
param = tf.Variable([1.0, 2.0, 3.0])
scalar = 1.0
tf.debugging.assert_shapes([
(x, ('N', 'Q')),
(y, ('N', 'D')),
(param, ('Q',)),
(scalar, ()),
])
```
```
tf.debugging.assert_shapes([
(x, ('N', 'D')),
(y, ('N', 'D'))
])
Traceback (most recent call last):
ValueError: ...
```
Example of adding a dependency to an operation:
```
with tf.control_dependencies([tf.assert_shapes(shapes)]):
output = tf.matmul(x, y, transpose_a=True)
```
If `x`, `y`, `param` or `scalar` does not have a shape that satisfies all specified constraints, `message`, as well as the first `summarize` entries of the first encountered violating tensor are printed, and `InvalidArgumentError` is raised.
Size entries in the specified shapes are checked against other entries by their **hash**, except:
* a size entry is interpreted as an explicit size if it can be parsed as an integer primitive.
* a size entry is interpreted as *any* size if it is None or '.'.
If the first entry of a shape is `...` (type `Ellipsis`) or '\*' that indicates a variable number of outer dimensions of unspecified size, i.e. the constraint applies to the inner-most dimensions only.
Scalar tensors and specified shapes of length zero (excluding the 'inner-most' prefix) are both treated as having a single dimension of size one.
| Args |
| `shapes` | A list of (`Tensor`, `shape`) tuples, wherein `shape` is the expected shape of `Tensor`. See the example code above. The `shape` must be an iterable. Each element of the iterable can be either a concrete integer value or a string that abstractly represents the dimension. For example, * `('N', 'Q')` specifies a 2D shape wherein the first and second dimensions of shape may or may not be equal.
* `('N', 'N', 'Q')` specifies a 3D shape wherein the first and second dimensions are equal.
* `(1, 'N')` specifies a 2D shape wherein the first dimension is exactly 1 and the second dimension can be any value. Note that the abstract dimension letters take effect across different tuple elements of the list. For example, `tf.debugging.assert_shapes([(x, ('N', 'A')), (y, ('N', 'B'))]` asserts that both `x` and `y` are rank-2 tensors and their first dimensions are equal (`N`). `shape` can also be a [`tf.TensorShape`](../../../tensorshape).
|
| `data` | The tensors to print out if the condition is False. Defaults to error message and first few entries of the violating tensor. |
| `summarize` | Print this many entries of the tensor. |
| `message` | A string to prefix to the default message. |
| `name` | A name for this operation (optional). Defaults to "assert\_shapes". |
| Returns |
| Op raising `InvalidArgumentError` unless all shape constraints are satisfied. If static checks determine all constraints are satisfied, a `no_op` is returned. |
| Raises |
| `ValueError` | If static checks determine any shape constraint is violated. |
tensorflow Module: tf.compat.v1.debugging.experimental Module: tf.compat.v1.debugging.experimental
===========================================
Public API for tf.debugging.experimental namespace.
Functions
---------
[`disable_dump_debug_info(...)`](../../../debugging/experimental/disable_dump_debug_info): Disable the currently-enabled debugging dumping.
[`enable_dump_debug_info(...)`](../../../debugging/experimental/enable_dump_debug_info): Enable dumping debugging information from a TensorFlow program.
tensorflow tf.compat.v1.estimator.BaselineEstimator tf.compat.v1.estimator.BaselineEstimator
========================================
An estimator that can establish a simple baseline.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.BaselineEstimator(
head, model_dir=None, optimizer='Ftrl', config=None
)
```
The estimator uses a user-specified head.
This estimator ignores feature values and will learn to predict the average value of each label. E.g. for single-label classification problems, this will predict the probability distribution of the classes as seen in the labels. For multi-label classification problems, it will predict the ratio of examples that contain each class.
#### Example:
```
# Build baseline multi-label classifier.
estimator = tf.estimator.BaselineEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3))
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
# Fit model.
estimator.train(input_fn=input_fn_train)
# Evaluates cross entropy between the test and train labels.
loss = estimator.evaluate(input_fn=input_fn_eval)["loss"]
# For each class, predicts the ratio of training examples that contain the
# class.
predictions = estimator.predict(new_samples)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is specified in the `head` constructor (and not None) for the head passed to BaselineEstimator's constructor, a feature with `key=weight_column` whose value is a `Tensor`.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
| programming_docs |
tensorflow tf.compat.v1.estimator.DNNLinearCombinedEstimator tf.compat.v1.estimator.DNNLinearCombinedEstimator
=================================================
An estimator for TensorFlow Linear and DNN joined models with custom head.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNLinearCombinedEstimator(
head,
model_dir=None,
linear_feature_columns=None,
linear_optimizer='Ftrl',
dnn_feature_columns=None,
dnn_optimizer='Adagrad',
dnn_hidden_units=None,
dnn_activation_fn=tf.nn.relu,
dnn_dropout=None,
input_layer_partitioner=None,
config=None,
batch_norm=False,
linear_sparse_combiner='sum'
)
```
>
> **Note:** This estimator is also known as wide-n-deep.
>
#### Example:
```
numeric_feature = numeric_column(...)
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
categorical_feature_a_emb = embedding_column(
categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
categorical_column=categorical_feature_b, ...)
estimator = tf.estimator.DNNLinearCombinedEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
# wide settings
linear_feature_columns=[categorical_feature_a_x_categorical_feature_b],
linear_optimizer=tf.keras.optimizers.Ftrl(...),
# deep settings
dnn_feature_columns=[
categorical_feature_a_emb, categorical_feature_b_emb,
numeric_feature],
dnn_hidden_units=[1000, 500, 100],
dnn_optimizer=tf.keras.optimizers.Adagrad(...))
# To apply L1 and L2 regularization, you can set dnn_optimizer to:
tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=0.001)
# To apply learning rate decay, you can set dnn_optimizer to a callable:
lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96)
# It is the same for linear_optimizer.
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train, steps=100)
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* for each `column` in `dnn_feature_columns` + `linear_feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using mean squared error.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.classifier_parse_example_spec tf.compat.v1.estimator.classifier\_parse\_example\_spec
=======================================================
Generates parsing spec for tf.parse\_example to be used with classifiers.
```
tf.compat.v1.estimator.classifier_parse_example_spec(
feature_columns,
label_key,
label_dtype=tf.dtypes.int64,
label_default=None,
weight_column=None
)
```
If users keep data in tf.Example format, they need to call tf.parse\_example with a proper feature spec. There are two main things that this utility helps:
* Users need to combine parsing spec of features with labels and weights (if any) since they are all parsed from same tf.Example instance. This utility combines these specs.
* It is difficult to map expected label by a classifier such as `DNNClassifier` to corresponding tf.parse\_example spec. This utility encodes it by getting related information from users (key, dtype).
Example output of parsing spec:
```
# Define features and transformations
feature_b = tf.feature_column.numeric_column(...)
feature_c_bucketized = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("feature_c"), ...)
feature_a_x_feature_c = tf.feature_column.crossed_column(
columns=["feature_a", feature_c_bucketized], ...)
feature_columns = [feature_b, feature_c_bucketized, feature_a_x_feature_c]
parsing_spec = tf.estimator.classifier_parse_example_spec(
feature_columns, label_key='my-label', label_dtype=tf.string)
# For the above example, classifier_parse_example_spec would return the dict:
assert parsing_spec == {
"feature_a": parsing_ops.VarLenFeature(tf.string),
"feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32),
"feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32)
"my-label" : parsing_ops.FixedLenFeature([1], dtype=tf.string)
}
```
Example usage with a classifier:
```
feature_columns = # define features via tf.feature_column
estimator = DNNClassifier(
n_classes=1000,
feature_columns=feature_columns,
weight_column='example-weight',
label_vocabulary=['photos', 'keep', ...],
hidden_units=[256, 64, 16])
# This label configuration tells the classifier the following:
# * weights are retrieved with key 'example-weight'
# * label is string and can be one of the following ['photos', 'keep', ...]
# * integer id for label 'photos' is 0, 'keep' is 1, ...
# Input builders
def input_fn_train(): # Returns a tuple of features and labels.
features = tf.contrib.learn.read_keyed_batch_features(
file_pattern=train_files,
batch_size=batch_size,
# creates parsing configuration for tf.parse_example
features=tf.estimator.classifier_parse_example_spec(
feature_columns,
label_key='my-label',
label_dtype=tf.string,
weight_column='example-weight'),
reader=tf.RecordIOReader)
labels = features.pop('my-label')
return features, labels
estimator.train(input_fn=input_fn_train)
```
| Args |
| `feature_columns` | An iterable containing all feature columns. All items should be instances of classes derived from `FeatureColumn`. |
| `label_key` | A string identifying the label. It means tf.Example stores labels with this key. |
| `label_dtype` | A `tf.dtype` identifies the type of labels. By default it is [`tf.int64`](../../../../tf#int64). If user defines a `label_vocabulary`, this should be set as [`tf.string`](../../../../tf#string). [`tf.float32`](../../../../tf#float32) labels are only supported for binary classification. |
| `label_default` | used as label if label\_key does not exist in given tf.Example. An example usage: let's say `label_key` is 'clicked' and tf.Example contains clicked data only for positive examples in following format `key:clicked, value:1`. This means that if there is no data with key 'clicked' it should count as negative example by setting `label_deafault=0`. Type of this value should be compatible with `label_dtype`. |
| `weight_column` | A string or a `NumericColumn` created by [`tf.feature_column.numeric_column`](../../../feature_column/numeric_column) defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. If it is a string, it is used as a key to fetch weight tensor from the `features`. If it is a `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then weight\_column.normalizer\_fn is applied on it to get weight tensor. |
| Returns |
| A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` value. |
| Raises |
| `ValueError` | If label is used in `feature_columns`. |
| `ValueError` | If weight\_column is used in `feature_columns`. |
| `ValueError` | If any of the given `feature_columns` is not a `_FeatureColumn` instance. |
| `ValueError` | If `weight_column` is not a `NumericColumn` instance. |
| `ValueError` | if label\_key is None. |
tensorflow tf.compat.v1.estimator.DNNRegressor tf.compat.v1.estimator.DNNRegressor
===================================
A regressor for TensorFlow DNN models.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNRegressor(
hidden_units,
feature_columns,
model_dir=None,
label_dimension=1,
weight_column=None,
optimizer='Adagrad',
activation_fn=tf.nn.relu,
dropout=None,
input_layer_partitioner=None,
config=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
batch_norm=False
)
```
#### Example:
```
categorical_feature_a = categorical_column_with_hash_bucket(...)
categorical_feature_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_emb = embedding_column(
categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
categorical_column=categorical_feature_b, ...)
estimator = tf.estimator.DNNRegressor(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = tf.estimator.DNNRegressor(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.DNNRegressor(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.DNNRegressor(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using mean squared error.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.LinearClassifier tf.compat.v1.estimator.LinearClassifier
=======================================
Linear classifier model.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.LinearClassifier(
feature_columns,
model_dir=None,
n_classes=2,
weight_column=None,
label_vocabulary=None,
optimizer='Ftrl',
config=None,
partitioner=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
sparse_combiner='sum'
)
```
Train a linear model to classify instances into one of multiple possible classes. When number of possible classes is 2, this is binary classification.
#### Example:
```
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
# Estimator using the default optimizer.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b])
# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=tf.keras.optimizers.Ftrl(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=lambda: tf.keras.optimizers.Ftrl(
learning_rate=tf.exponential_decay(
learning_rate=0.1,
global_step=tf.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.LinearClassifier(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using softmax cross entropy.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.DNNLinearCombinedClassifier tf.compat.v1.estimator.DNNLinearCombinedClassifier
==================================================
An estimator for TensorFlow Linear and DNN joined classification models.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNLinearCombinedClassifier(
model_dir=None,
linear_feature_columns=None,
linear_optimizer='Ftrl',
dnn_feature_columns=None,
dnn_optimizer='Adagrad',
dnn_hidden_units=None,
dnn_activation_fn=tf.nn.relu,
dnn_dropout=None,
n_classes=2,
weight_column=None,
label_vocabulary=None,
input_layer_partitioner=None,
config=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
batch_norm=False,
linear_sparse_combiner='sum'
)
```
>
> **Note:** This estimator is also known as wide-n-deep.
>
#### Example:
```
numeric_feature = numeric_column(...)
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
categorical_feature_a_emb = embedding_column(
categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
categorical_id_column=categorical_feature_b, ...)
estimator = tf.estimator.DNNLinearCombinedClassifier(
# wide settings
linear_feature_columns=[categorical_feature_a_x_categorical_feature_b],
linear_optimizer=tf.keras.optimizers.Ftrl(...),
# deep settings
dnn_feature_columns=[
categorical_feature_a_emb, categorical_feature_b_emb,
numeric_feature],
dnn_hidden_units=[1000, 500, 100],
dnn_optimizer=tf.keras.optimizers.Adagrad(...),
# warm-start settings
warm_start_from="/path/to/checkpoint/dir")
# To apply L1 and L2 regularization, you can set dnn_optimizer to:
tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=0.001)
# To apply learning rate decay, you can set dnn_optimizer to a callable:
lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96)
# It is the same for linear_optimizer.
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train, steps=100)
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* for each `column` in `dnn_feature_columns` + `linear_feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using softmax cross entropy.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.DNNClassifier tf.compat.v1.estimator.DNNClassifier
====================================
A classifier for TensorFlow DNN models.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNClassifier(
hidden_units,
feature_columns,
model_dir=None,
n_classes=2,
weight_column=None,
label_vocabulary=None,
optimizer='Adagrad',
activation_fn=tf.nn.relu,
dropout=None,
input_layer_partitioner=None,
config=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
batch_norm=False
)
```
#### Example:
```
categorical_feature_a = categorical_column_with_hash_bucket(...)
categorical_feature_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_emb = embedding_column(
categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
categorical_column=categorical_feature_b, ...)
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using softmax cross entropy.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow Module: tf.compat.v1.estimator.inputs Module: tf.compat.v1.estimator.inputs
=====================================
Utility methods to create simple input\_fns.
Functions
---------
[`numpy_input_fn(...)`](inputs/numpy_input_fn): Returns input function that would feed dict of numpy arrays into the model.
[`pandas_input_fn(...)`](inputs/pandas_input_fn): Returns input function that would feed Pandas DataFrame into the model.
tensorflow tf.compat.v1.estimator.LinearEstimator tf.compat.v1.estimator.LinearEstimator
======================================
An estimator for TensorFlow linear models with user-specified head.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.LinearEstimator(
head,
feature_columns,
model_dir=None,
optimizer='Ftrl',
config=None,
partitioner=None,
sparse_combiner='sum',
warm_start_from=None
)
```
#### Example:
```
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
# Estimator using the default optimizer.
estimator = tf.estimator.LinearEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b])
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=lambda: tf.keras.optimizers.Ftrl(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b])
optimizer=tf.keras.optimizers.Ftrl(
learning_rate=0.1,
l1_regularization_strength=0.001
))
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train, steps=100)
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss and predicted output are determined by the specified head.
| Args |
| `head` | A `_Head` instance constructed with a method such as `tf.contrib.estimator.multi_label_head`. |
| `feature_columns` | An iterable containing all the feature columns used by the model. All items in the set should be instances of classes derived from `FeatureColumn`. |
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. |
| `optimizer` | An instance of `tf.Optimizer` used to train the model. Can also be a string (one of 'Adagrad', 'Adam', 'Ftrl', 'RMSProp', 'SGD'), or callable. Defaults to FTRL optimizer. |
| `config` | `RunConfig` object to configure the runtime settings. |
| `partitioner` | Optional. Partitioner for input layer. |
| `sparse_combiner` | A string specifying how to reduce if a categorical column is multivalent. One of "mean", "sqrtn", and "sum" -- these are effectively different ways to do example-level normalization, which can be useful for bag-of-words features. for more details, see `tf.feature_column.linear_model`. |
| `warm_start_from` | A string filepath to a checkpoint to warm-start from, or a `WarmStartSettings` object to fully configure warm-starting. If the string filepath is provided instead of a `WarmStartSettings`, then all weights and biases are warm-started, and it is assumed that vocabularies and Tensor names are unchanged. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.DNNEstimator tf.compat.v1.estimator.DNNEstimator
===================================
An estimator for TensorFlow DNN models with user-specified head.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNEstimator(
head,
hidden_units,
feature_columns,
model_dir=None,
optimizer='Adagrad',
activation_fn=tf.nn.relu,
dropout=None,
input_layer_partitioner=None,
config=None,
warm_start_from=None,
batch_norm=False
)
```
#### Example:
```
sparse_feature_a = sparse_column_with_hash_bucket(...)
sparse_feature_b = sparse_column_with_hash_bucket(...)
sparse_feature_a_emb = embedding_column(sparse_id_column=sparse_feature_a,
...)
sparse_feature_b_emb = embedding_column(sparse_id_column=sparse_feature_b,
...)
estimator = tf.estimator.DNNEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256])
# Or estimator using the ProximalAdagradOptimizer optimizer with
# regularization.
estimator = tf.estimator.DNNEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.DNNEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256],
optimizer=lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.DNNEstimator(
head=tf.estimator.MultiLabelHead(n_classes=3),
feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb],
hidden_units=[1024, 512, 256],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss and predicted output are determined by the specified head.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow Module: tf.compat.v1.estimator.experimental Module: tf.compat.v1.estimator.experimental
===========================================
Public API for tf.estimator.experimental namespace.
Classes
-------
[`class InMemoryEvaluatorHook`](../../../estimator/experimental/inmemoryevaluatorhook): Hook to run evaluation in training without a checkpoint.
[`class KMeans`](experimental/kmeans): An Estimator for K-Means clustering.
[`class LinearSDCA`](../../../estimator/experimental/linearsdca): Stochastic Dual Coordinate Ascent helper for linear estimators.
Functions
---------
[`build_raw_supervised_input_receiver_fn(...)`](../../../estimator/experimental/build_raw_supervised_input_receiver_fn): Build a supervised\_input\_receiver\_fn for raw features and labels.
[`call_logit_fn(...)`](../../../estimator/experimental/call_logit_fn): Calls logit\_fn (experimental).
[`dnn_logit_fn_builder(...)`](experimental/dnn_logit_fn_builder): Function builder for a dnn logit\_fn.
[`linear_logit_fn_builder(...)`](experimental/linear_logit_fn_builder): Function builder for a linear logit\_fn.
[`make_early_stopping_hook(...)`](../../../estimator/experimental/make_early_stopping_hook): Creates early-stopping hook.
[`make_stop_at_checkpoint_step_hook(...)`](../../../estimator/experimental/make_stop_at_checkpoint_step_hook): Creates a proper StopAtCheckpointStepHook based on chief status.
[`stop_if_higher_hook(...)`](../../../estimator/experimental/stop_if_higher_hook): Creates hook to stop if the given metric is higher than the threshold.
[`stop_if_lower_hook(...)`](../../../estimator/experimental/stop_if_lower_hook): Creates hook to stop if the given metric is lower than the threshold.
[`stop_if_no_decrease_hook(...)`](../../../estimator/experimental/stop_if_no_decrease_hook): Creates hook to stop if metric does not decrease within given max steps.
[`stop_if_no_increase_hook(...)`](../../../estimator/experimental/stop_if_no_increase_hook): Creates hook to stop if metric does not increase within given max steps.
tensorflow tf.compat.v1.estimator.regressor_parse_example_spec tf.compat.v1.estimator.regressor\_parse\_example\_spec
======================================================
Generates parsing spec for tf.parse\_example to be used with regressors.
```
tf.compat.v1.estimator.regressor_parse_example_spec(
feature_columns,
label_key,
label_dtype=tf.dtypes.float32,
label_default=None,
label_dimension=1,
weight_column=None
)
```
If users keep data in tf.Example format, they need to call tf.parse\_example with a proper feature spec. There are two main things that this utility helps:
* Users need to combine parsing spec of features with labels and weights (if any) since they are all parsed from same tf.Example instance. This utility combines these specs.
* It is difficult to map expected label by a regressor such as `DNNRegressor` to corresponding tf.parse\_example spec. This utility encodes it by getting related information from users (key, dtype).
Example output of parsing spec:
```
# Define features and transformations
feature_b = tf.feature_column.numeric_column(...)
feature_c_bucketized = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("feature_c"), ...)
feature_a_x_feature_c = tf.feature_column.crossed_column(
columns=["feature_a", feature_c_bucketized], ...)
feature_columns = [feature_b, feature_c_bucketized, feature_a_x_feature_c]
parsing_spec = tf.estimator.regressor_parse_example_spec(
feature_columns, label_key='my-label')
# For the above example, regressor_parse_example_spec would return the dict:
assert parsing_spec == {
"feature_a": parsing_ops.VarLenFeature(tf.string),
"feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32),
"feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32)
"my-label" : parsing_ops.FixedLenFeature([1], dtype=tf.float32)
}
```
Example usage with a regressor:
```
feature_columns = # define features via tf.feature_column
estimator = DNNRegressor(
hidden_units=[256, 64, 16],
feature_columns=feature_columns,
weight_column='example-weight',
label_dimension=3)
# This label configuration tells the regressor the following:
# * weights are retrieved with key 'example-weight'
# * label is a 3 dimension tensor with float32 dtype.
# Input builders
def input_fn_train(): # Returns a tuple of features and labels.
features = tf.contrib.learn.read_keyed_batch_features(
file_pattern=train_files,
batch_size=batch_size,
# creates parsing configuration for tf.parse_example
features=tf.estimator.classifier_parse_example_spec(
feature_columns,
label_key='my-label',
label_dimension=3,
weight_column='example-weight'),
reader=tf.RecordIOReader)
labels = features.pop('my-label')
return features, labels
estimator.train(input_fn=input_fn_train)
```
| Args |
| `feature_columns` | An iterable containing all feature columns. All items should be instances of classes derived from `_FeatureColumn`. |
| `label_key` | A string identifying the label. It means tf.Example stores labels with this key. |
| `label_dtype` | A `tf.dtype` identifies the type of labels. By default it is [`tf.float32`](../../../../tf#float32). |
| `label_default` | used as label if label\_key does not exist in given tf.Example. By default default\_value is none, which means `tf.parse_example` will error out if there is any missing label. |
| `label_dimension` | Number of regression targets per example. This is the size of the last dimension of the labels and logits `Tensor` objects (typically, these have shape `[batch_size, label_dimension]`). |
| `weight_column` | A string or a `NumericColumn` created by [`tf.feature_column.numeric_column`](../../../feature_column/numeric_column) defining feature column representing weights. It is used to down weight or boost examples during training. It will be multiplied by the loss of the example. If it is a string, it is used as a key to fetch weight tensor from the `features`. If it is a `NumericColumn`, raw tensor is fetched by key `weight_column.key`, then weight\_column.normalizer\_fn is applied on it to get weight tensor. |
| Returns |
| A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature` value. |
| Raises |
| `ValueError` | If label is used in `feature_columns`. |
| `ValueError` | If weight\_column is used in `feature_columns`. |
| `ValueError` | If any of the given `feature_columns` is not a `_FeatureColumn` instance. |
| `ValueError` | If `weight_column` is not a `NumericColumn` instance. |
| `ValueError` | if label\_key is None. |
tensorflow tf.compat.v1.estimator.DNNLinearCombinedRegressor tf.compat.v1.estimator.DNNLinearCombinedRegressor
=================================================
An estimator for TensorFlow Linear and DNN joined models for regression.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.DNNLinearCombinedRegressor(
model_dir=None,
linear_feature_columns=None,
linear_optimizer='Ftrl',
dnn_feature_columns=None,
dnn_optimizer='Adagrad',
dnn_hidden_units=None,
dnn_activation_fn=tf.nn.relu,
dnn_dropout=None,
label_dimension=1,
weight_column=None,
input_layer_partitioner=None,
config=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
batch_norm=False,
linear_sparse_combiner='sum'
)
```
>
> **Note:** This estimator is also known as wide-n-deep.
>
#### Example:
```
numeric_feature = numeric_column(...)
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
categorical_feature_a_emb = embedding_column(
categorical_column=categorical_feature_a, ...)
categorical_feature_b_emb = embedding_column(
categorical_column=categorical_feature_b, ...)
estimator = tf.estimator.DNNLinearCombinedRegressor(
# wide settings
linear_feature_columns=[categorical_feature_a_x_categorical_feature_b],
linear_optimizer=tf.keras.optimizers.Ftrl(...),
# deep settings
dnn_feature_columns=[
categorical_feature_a_emb, categorical_feature_b_emb,
numeric_feature],
dnn_hidden_units=[1000, 500, 100],
dnn_optimizer=tf.keras.optimizers.Adagrad(...),
# warm-start settings
warm_start_from="/path/to/checkpoint/dir")
# To apply L1 and L2 regularization, you can set dnn_optimizer to:
tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate=0.1,
l1_regularization_strength=0.001,
l2_regularization_strength=0.001)
# To apply learning rate decay, you can set dnn_optimizer to a callable:
lambda: tf.keras.optimizers.Adam(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96)
# It is the same for linear_optimizer.
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train, steps=100)
metrics = estimator.evaluate(input_fn=input_fn_eval, steps=10)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* for each `column` in `dnn_feature_columns` + `linear_feature_columns`:
+ if `column` is a `CategoricalColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedCategoricalColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `DenseColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using mean squared error.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.BaselineRegressor tf.compat.v1.estimator.BaselineRegressor
========================================
A regressor that can establish a simple baseline.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.BaselineRegressor(
model_dir=None,
label_dimension=1,
weight_column=None,
optimizer='Ftrl',
config=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM
)
```
This regressor ignores feature values and will learn to predict the average value of each label.
#### Example:
```
# Build BaselineRegressor
regressor = tf.estimator.BaselineRegressor()
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
# Fit model.
regressor.train(input_fn=input_fn_train)
# Evaluate squared-loss between the test and train targets.
loss = regressor.evaluate(input_fn=input_fn_eval)["loss"]
# predict outputs the mean value seen during training.
predictions = regressor.predict(new_samples)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.LinearRegressor tf.compat.v1.estimator.LinearRegressor
======================================
An estimator for TensorFlow Linear regression problems.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.LinearRegressor(
feature_columns,
model_dir=None,
label_dimension=1,
weight_column=None,
optimizer='Ftrl',
config=None,
partitioner=None,
warm_start_from=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM,
sparse_combiner='sum'
)
```
Train a linear regression model to predict label value given observation of feature values.
#### Example:
```
categorical_column_a = categorical_column_with_hash_bucket(...)
categorical_column_b = categorical_column_with_hash_bucket(...)
categorical_feature_a_x_categorical_feature_b = crossed_column(...)
# Estimator using the default optimizer.
estimator = tf.estimator.LinearRegressor(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b])
# Or estimator using the FTRL optimizer with regularization.
estimator = tf.estimator.LinearRegressor(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=tf.keras.optimizers.Ftrl(
learning_rate=0.1,
l1_regularization_strength=0.001
))
# Or estimator using an optimizer with a learning rate decay.
estimator = tf.estimator.LinearRegressor(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
optimizer=lambda: tf.keras.optimizers.Ftrl(
learning_rate=tf.compat.v1.train.exponential_decay(
learning_rate=0.1,
global_step=tf.compat.v1.train.get_global_step(),
decay_steps=10000,
decay_rate=0.96))
# Or estimator with warm-starting from a previous checkpoint.
estimator = tf.estimator.LinearRegressor(
feature_columns=[categorical_column_a,
categorical_feature_a_x_categorical_feature_b],
warm_start_from="/path/to/checkpoint/dir")
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_predict:
# Returns tf.data.Dataset of (x, None) tuple.
pass
estimator.train(input_fn=input_fn_train)
metrics = estimator.evaluate(input_fn=input_fn_eval)
predictions = estimator.predict(input_fn=input_fn_predict)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a KeyError:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
* for each `column` in `feature_columns`:
+ if `column` is a `SparseColumn`, a feature with `key=column.name` whose `value` is a `SparseTensor`.
+ if `column` is a `WeightedSparseColumn`, two features: the first with `key` the id column name, the second with `key` the weight column name. Both features' `value` must be a `SparseTensor`.
+ if `column` is a `RealValuedColumn`, a feature with `key=column.name` whose `value` is a `Tensor`.
Loss is calculated by using mean squared error.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow Module: tf.compat.v1.estimator.export Module: tf.compat.v1.estimator.export
=====================================
All public utility methods for exporting Estimator to SavedModel.
This file includes functions and constants from core (model\_utils) and export.py
Classes
-------
[`class ClassificationOutput`](../../../estimator/export/classificationoutput): Represents the output of a classification head.
[`class EvalOutput`](../../../estimator/export/evaloutput): Represents the output of a supervised eval process.
[`class ExportOutput`](../../../estimator/export/exportoutput): Represents an output of a model that can be served.
[`class PredictOutput`](../../../estimator/export/predictoutput): Represents the output of a generic prediction head.
[`class RegressionOutput`](../../../estimator/export/regressionoutput): Represents the output of a regression head.
[`class ServingInputReceiver`](../../../estimator/export/servinginputreceiver): A return type for a serving\_input\_receiver\_fn.
[`class TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver): A return type for a serving\_input\_receiver\_fn.
Functions
---------
[`build_parsing_serving_input_receiver_fn(...)`](../../../estimator/export/build_parsing_serving_input_receiver_fn): Build a serving\_input\_receiver\_fn expecting fed tf.Examples.
[`build_raw_serving_input_receiver_fn(...)`](../../../estimator/export/build_raw_serving_input_receiver_fn): Build a serving\_input\_receiver\_fn expecting feature Tensors.
tensorflow tf.compat.v1.estimator.BaselineClassifier tf.compat.v1.estimator.BaselineClassifier
=========================================
A classifier that can establish a simple baseline.
Inherits From: [`Estimator`](estimator)
```
tf.compat.v1.estimator.BaselineClassifier(
model_dir=None,
n_classes=2,
weight_column=None,
label_vocabulary=None,
optimizer='Ftrl',
config=None,
loss_reduction=tf.compat.v1.losses.Reduction.SUM
)
```
This classifier ignores feature values and will learn to predict the average value of each label. For single-label problems, this will predict the probability distribution of the classes as seen in the labels. For multi-label problems, this will predict the fraction of examples that are positive for each class.
#### Example:
```
# Build BaselineClassifier
classifier = tf.estimator.BaselineClassifier(n_classes=3)
# Input builders
def input_fn_train:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
def input_fn_eval:
# Returns tf.data.Dataset of (x, y) tuple where y represents label's class
# index.
pass
# Fit model.
classifier.train(input_fn=input_fn_train)
# Evaluate cross entropy between the test and train labels.
loss = classifier.evaluate(input_fn=input_fn_eval)["loss"]
# predict outputs the probability distribution of the classes as seen in
# training.
predictions = classifier.predict(new_samples)
```
Input of `train` and `evaluate` should have following features, otherwise there will be a `KeyError`:
* if `weight_column` is not `None`, a feature with `key=weight_column` whose value is a `Tensor`.
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Estimators can be used while eager execution is enabled. Note that `input_fn` and all hooks are executed inside a graph context, so they have to be written to be compatible with graph mode. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow tf.compat.v1.estimator.Estimator tf.compat.v1.estimator.Estimator
================================
Estimator class to train and evaluate TensorFlow models.
```
tf.compat.v1.estimator.Estimator(
model_fn, model_dir=None, config=None, params=None, warm_start_from=None
)
```
The `Estimator` object wraps a model which is specified by a `model_fn`, which, given inputs and a number of other parameters, returns the ops necessary to perform training, evaluation, or predictions.
All outputs (checkpoints, event files, etc.) are written to `model_dir`, or a subdirectory thereof. If `model_dir` is not set, a temporary directory is used.
The `config` argument can be passed [`tf.estimator.RunConfig`](../../../estimator/runconfig) object containing information about the execution environment. It is passed on to the `model_fn`, if the `model_fn` has a parameter named "config" (and input functions in the same manner). If the `config` parameter is not passed, it is instantiated by the `Estimator`. Not passing config means that defaults useful for local execution are used. `Estimator` makes config available to the model (for instance, to allow specialization based on the number of workers available), and also uses some of its fields to control internals, especially regarding checkpointing.
The `params` argument contains hyperparameters. It is passed to the `model_fn`, if the `model_fn` has a parameter named "params", and to the input functions in the same manner. `Estimator` only passes params along, it does not inspect it. The structure of `params` is therefore entirely up to the developer.
None of `Estimator`'s methods can be overridden in subclasses (its constructor enforces this). Subclasses should use `model_fn` to configure the base class, and may add methods implementing specialized functionality.
See [estimators](https://tensorflow.org/guide/estimator) for more information.
To warm-start an `Estimator`:
```
estimator = tf.estimator.DNNClassifier(
feature_columns=[categorical_feature_a_emb, categorical_feature_b_emb],
hidden_units=[1024, 512, 256],
warm_start_from="/path/to/checkpoint/dir")
```
For more details on warm-start configuration, see [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings).
| Args |
| `model_fn` | Model function. Follows the signature: * `features` -- This is the first item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same.
* `labels` -- This is the second item returned from the `input_fn` passed to `train`, `evaluate`, and `predict`. This should be a single [`tf.Tensor`](../../../tensor) or `dict` of same (for multi-head models). If mode is [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT), `labels=None` will be passed. If the `model_fn`'s signature does not accept `mode`, the `model_fn` must still be able to handle `labels=None`.
* `mode` -- Optional. Specifies if this is training, evaluation or prediction. See [`tf.estimator.ModeKeys`](../../../estimator/modekeys). `params` -- Optional `dict` of hyperparameters. Will receive what is passed to Estimator in `params` parameter. This allows to configure Estimators from hyper parameter tuning.
* `config` -- Optional [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) object. Will receive what is passed to Estimator as its `config` parameter, or a default value. Allows setting up things in your `model_fn` based on configuration such as `num_ps_replicas`, or `model_dir`.
* Returns -- [`tf.estimator.EstimatorSpec`](../../../estimator/estimatorspec)
|
| `model_dir` | Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into an estimator to continue training a previously saved model. If `PathLike` object, the path will be resolved. If `None`, the model\_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. |
| `config` | [`estimator.RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) configuration object. |
| `params` | `dict` of hyper parameters that will be passed into `model_fn`. Keys are names of parameters, values are basic python types. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings) object to fully configure warm-starting. If None, only TRAINABLE variables are warm-started. If the string filepath is provided instead of a [`tf.estimator.WarmStartSettings`](../../../estimator/warmstartsettings), then all variables are warm-started, and it is assumed that vocabularies and [`tf.Tensor`](../../../tensor) names are unchanged. |
| Raises |
| `ValueError` | parameters of `model_fn` don't match `params`. |
| `ValueError` | if this is called via a subclass and if that class overrides a member of `Estimator`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
eager compatibility
-------------------
Calling methods of `Estimator` will work while eager execution is enabled. However, the `model_fn` and `input_fn` is not executed eagerly, `Estimator` will switch to graph mode before calling all user-provided functions (incl. hooks), so their code has to be compatible with graph mode execution. Note that `input_fn` code using [`tf.data`](../../../data) generally works in both graph and eager modes.
| programming_docs |
tensorflow Module: tf.compat.v1.estimator.tpu Module: tf.compat.v1.estimator.tpu
==================================
Public API for tf.estimator.tpu namespace.
Modules
-------
[`experimental`](tpu/experimental) module: Public API for tf.estimator.tpu.experimental namespace.
Classes
-------
[`class InputPipelineConfig`](tpu/inputpipelineconfig): Please see the definition of these values in TPUConfig.
[`class RunConfig`](tpu/runconfig): RunConfig with TPU support.
[`class TPUConfig`](tpu/tpuconfig): TPU related configuration required by `TPUEstimator`.
[`class TPUEstimator`](tpu/tpuestimator): Estimator with TPU support.
[`class TPUEstimatorSpec`](tpu/tpuestimatorspec): Ops and objects returned from a `model_fn` and passed to `TPUEstimator`.
tensorflow tf.compat.v1.estimator.experimental.KMeans tf.compat.v1.estimator.experimental.KMeans
==========================================
An Estimator for K-Means clustering.
Inherits From: [`Estimator`](../estimator)
```
tf.compat.v1.estimator.experimental.KMeans(
num_clusters,
model_dir=None,
initial_clusters=RANDOM_INIT,
distance_metric=SQUARED_EUCLIDEAN_DISTANCE,
seed=None,
use_mini_batch=True,
mini_batch_steps_per_iteration=1,
kmeans_plus_plus_num_retries=2,
relative_tolerance=None,
config=None,
feature_columns=None
)
```
#### Example:
```
import numpy as np
import tensorflow as tf
num_points = 100
dimensions = 2
points = np.random.uniform(0, 1000, [num_points, dimensions])
def input_fn():
return tf.compat.v1.train.limit_epochs(
tf.convert_to_tensor(points, dtype=tf.float32), num_epochs=1)
num_clusters = 5
kmeans = tf.compat.v1.estimator.experimental.KMeans(
num_clusters=num_clusters, use_mini_batch=False)
# train
num_iterations = 10
previous_centers = None
for _ in xrange(num_iterations):
kmeans.train(input_fn)
cluster_centers = kmeans.cluster_centers()
if previous_centers is not None:
print 'delta:', cluster_centers - previous_centers
previous_centers = cluster_centers
print 'score:', kmeans.score(input_fn)
print 'cluster centers:', cluster_centers
# map the input points to their clusters
cluster_indices = list(kmeans.predict_cluster_index(input_fn))
for i, point in enumerate(points):
cluster_index = cluster_indices[i]
center = cluster_centers[cluster_index]
print 'point:', point, 'is in cluster', cluster_index, 'centered at', center
```
The `SavedModel` saved by the `export_saved_model` method does not include the cluster centers. However, the cluster centers may be retrieved by the latest checkpoint saved during training. Specifically,
```
kmeans.cluster_centers()
```
is equivalent to
```
tf.train.load_variable(
kmeans.model_dir, KMeansClustering.CLUSTER_CENTERS_VAR_NAME)
```
| Args |
| `num_clusters` | An integer tensor specifying the number of clusters. This argument is ignored if `initial_clusters` is a tensor or numpy array. |
| `model_dir` | The directory to save the model results and log files. |
| `initial_clusters` | Specifies how the initial cluster centers are chosen. One of the following: \* a tensor or numpy array with the initial cluster centers. \* a callable `f(inputs, k)` that selects and returns up to `k` centers from an input batch. `f` is free to return any number of centers from `0` to `k`. It will be invoked on successive input batches as necessary until all `num_clusters` centers are chosen. * `KMeansClustering.RANDOM_INIT`: Choose centers randomly from an input batch. If the batch size is less than `num_clusters` then the entire batch is chosen to be initial cluster centers and the remaining centers are chosen from successive input batches.
* `KMeansClustering.KMEANS_PLUS_PLUS_INIT`: Use kmeans++ to choose centers from the first input batch. If the batch size is less than `num_clusters`, a TensorFlow runtime error occurs.
|
| `distance_metric` | The distance metric used for clustering. One of: - `KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`: Euclidean distance between vectors `u` and `v` is defined as \(||u - v||\_2\) which is the square root of the sum of the absolute squares of the elements' difference.
- `KMeansClustering.COSINE_DISTANCE`: Cosine distance between vectors `u` and `v` is defined as \(1 - (u . v) / (||u||\_2 ||v||\_2)\).
|
| `seed` | Python integer. Seed for PRNG used to initialize centers. |
| `use_mini_batch` | A boolean specifying whether to use the mini-batch k-means algorithm. See explanation above. |
| `mini_batch_steps_per_iteration` | The number of steps after which the updated cluster centers are synced back to a master copy. Used only if `use_mini_batch=True`. See explanation above. |
| `kmeans_plus_plus_num_retries` | For each point that is sampled during kmeans++ initialization, this parameter specifies the number of additional points to draw from the current distribution before selecting the best. If a negative value is specified, a heuristic is used to sample `O(log(num_to_sample))` additional points. Used only if `initial_clusters=KMeansClustering.KMEANS_PLUS_PLUS_INIT`. |
| `relative_tolerance` | A relative tolerance of change in the loss between iterations. Stops learning if the loss changes less than this amount. This may not work correctly if `use_mini_batch=True`. |
| `config` | See [`tf.estimator.Estimator`](../../../../estimator/estimator). |
| `feature_columns` | An optionable iterable containing all the feature columns used by the model. All items in the set should be feature column instances that can be passed to `tf.feature_column.input_layer`. If this is None, all features will be used. |
| Raises |
| `ValueError` | An invalid argument was passed to `initial_clusters` or `distance_metric`. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `cluster_centers`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/kmeans.py#L477-L479)
```
cluster_centers()
```
Returns the cluster centers.
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L403-L478)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L555-L653)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `predict_cluster_index`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/kmeans.py#L427-L438)
```
predict_cluster_index(
input_fn
)
```
Finds the index of the closest cluster center to each input point.
| Args |
| `input_fn` | Input points. See [`tf.estimator.Estimator.predict`](../../../../estimator/estimator#predict). |
| Yields |
| The index of the closest cluster center for each input point. |
### `score`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/kmeans.py#L440-L454)
```
score(
input_fn
)
```
Returns the sum of squared distances to nearest clusters.
Note that this function is different from the corresponding one in sklearn which returns the negative sum.
| Args |
| `input_fn` | Input points. See [`tf.estimator.Estimator.evaluate`](../../../../estimator/estimator#evaluate). Only one batch is retrieved. |
| Returns |
| The sum of the squared distance from each point in the first batch of inputs to its nearest cluster center. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L284-L362)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
### `transform`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/canned/kmeans.py#L456-L475)
```
transform(
input_fn
)
```
Transforms each input point to its distances to all cluster centers.
Note that if `distance_metric=KMeansClustering.SQUARED_EUCLIDEAN_DISTANCE`, this function returns the squared Euclidean distance while the corresponding sklearn function returns the Euclidean distance.
| Args |
| `input_fn` | Input points. See [`tf.estimator.Estimator.predict`](../../../../estimator/estimator#predict). |
| Yields |
| The distances from each input point to each cluster center. |
| Class Variables |
| ALL\_DISTANCES | `'all_distances'` |
| CLUSTER\_CENTERS\_VAR\_NAME | `'clusters'` |
| CLUSTER\_INDEX | `'cluster_index'` |
| COSINE\_DISTANCE | `'cosine'` |
| KMEANS\_PLUS\_PLUS\_INIT | `'kmeans_plus_plus'` |
| RANDOM\_INIT | `'random'` |
| SCORE | `'score'` |
| SQUARED\_EUCLIDEAN\_DISTANCE | `'squared_euclidean'` |
| programming_docs |
tensorflow tf.compat.v1.estimator.experimental.dnn_logit_fn_builder tf.compat.v1.estimator.experimental.dnn\_logit\_fn\_builder
===========================================================
Function builder for a dnn logit\_fn.
```
tf.compat.v1.estimator.experimental.dnn_logit_fn_builder(
units,
hidden_units,
feature_columns,
activation_fn,
dropout,
input_layer_partitioner,
batch_norm
)
```
| Args |
| `units` | An int indicating the dimension of the logit layer. In the MultiHead case, this should be the sum of all component Heads' logit dimensions. |
| `hidden_units` | Iterable of integer number of hidden units per layer. |
| `feature_columns` | Iterable of `feature_column._FeatureColumn` model inputs. |
| `activation_fn` | Activation function applied to each layer. |
| `dropout` | When not `None`, the probability we will drop out a given coordinate. |
| `input_layer_partitioner` | Partitioner for input layer. |
| `batch_norm` | Whether to use batch normalization after each hidden layer. |
| Returns |
| A logit\_fn (see below). |
| Raises |
| `ValueError` | If units is not an int. |
tensorflow tf.compat.v1.estimator.experimental.linear_logit_fn_builder tf.compat.v1.estimator.experimental.linear\_logit\_fn\_builder
==============================================================
Function builder for a linear logit\_fn.
```
tf.compat.v1.estimator.experimental.linear_logit_fn_builder(
units, feature_columns, sparse_combiner='sum'
)
```
| Args |
| `units` | An int indicating the dimension of the logit layer. |
| `feature_columns` | An iterable containing all the feature columns used by the model. |
| `sparse_combiner` | A string specifying how to reduce if a categorical column is multivalent. One of "mean", "sqrtn", and "sum". |
| Returns |
| A logit\_fn (see below). |
tensorflow tf.compat.v1.estimator.tpu.TPUEstimatorSpec tf.compat.v1.estimator.tpu.TPUEstimatorSpec
===========================================
Ops and objects returned from a `model_fn` and passed to `TPUEstimator`.
```
tf.compat.v1.estimator.tpu.TPUEstimatorSpec(
mode,
predictions=None,
loss=None,
train_op=None,
eval_metrics=None,
export_outputs=None,
scaffold_fn=None,
host_call=None,
training_hooks=None,
evaluation_hooks=None,
prediction_hooks=None
)
```
Migrate to TF2
--------------
TPU Estimator manages its own TensorFlow graph and session, so it is not compatible with TF2 behaviors. We recommend that you migrate to the newer [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy). See the [TPU guide](https://www.tensorflow.org/guide/tpu) for details.
Description
-----------
See `EstimatorSpec` for `mode`, `predictions`, `loss`, `train_op`, and `export_outputs`.
For evaluation, `eval_metrics`is a tuple of `metric_fn` and `tensors`, where `metric_fn` runs on CPU to generate metrics and `tensors` represents the `Tensor`s transferred from TPU system to CPU host and passed to `metric_fn`. To be precise, TPU evaluation expects a slightly different signature from the [`tf.estimator.Estimator`](../../../../estimator/estimator). While [`EstimatorSpec.eval_metric_ops`](https://www.tensorflow.org/api_docs/python/tf/estimator/EstimatorSpec#eval_metric_ops) expects a dict, `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`. The `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. The `tensors` usually specify the model logits, which are transferred back from TPU system to CPU host. All tensors must have be batch-major, i.e., the batch size is the first dimension. Once all tensors are available at CPU host from all shards, they are concatenated (on CPU) and passed as positional arguments to the `metric_fn` if `tensors` is list or keyword arguments if `tensors` is a dict. `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple. See `TPUEstimator` for MNIST example how to specify the `eval_metrics`.
`scaffold_fn` is a function running on CPU to generate the `Scaffold`. This function should not capture any Tensors in `model_fn`.
`host_call` is a tuple of a `function` and a list or dictionary of `tensors` to pass to that function and returns a list of Tensors. `host_call` currently works for train() and evaluate(). The Tensors returned by the function is executed on the CPU on every step, so there is communication overhead when sending tensors from TPU to CPU. To reduce the overhead, try reducing the size of the tensors. The `tensors` are concatenated along their major (batch) dimension, and so must be >= rank 1. The `host_call` is useful for writing summaries with `tf.contrib.summary.create_file_writer`.
| Attributes |
| `mode` | A `namedtuple` alias for field number 0 |
| `predictions` | A `namedtuple` alias for field number 1 |
| `loss` | A `namedtuple` alias for field number 2 |
| `train_op` | A `namedtuple` alias for field number 3 |
| `eval_metrics` | A `namedtuple` alias for field number 4 |
| `export_outputs` | A `namedtuple` alias for field number 5 |
| `scaffold_fn` | A `namedtuple` alias for field number 6 |
| `host_call` | A `namedtuple` alias for field number 7 |
| `training_hooks` | A `namedtuple` alias for field number 8 |
| `evaluation_hooks` | A `namedtuple` alias for field number 9 |
| `prediction_hooks` | A `namedtuple` alias for field number 10 |
Methods
-------
### `as_estimator_spec`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py#L368-L395)
```
as_estimator_spec()
```
Creates an equivalent `EstimatorSpec` used by CPU train/eval.
tensorflow tf.compat.v1.estimator.tpu.InputPipelineConfig tf.compat.v1.estimator.tpu.InputPipelineConfig
==============================================
Please see the definition of these values in TPUConfig.
Migrate to TF2
--------------
TPU Estimator manages its own TensorFlow graph and session, so it is not compatible with TF2 behaviors. We recommend that you migrate to the newer [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy). See the [TPU guide](https://www.tensorflow.org/guide/tpu) for details.
Description
-----------
| Class Variables |
| BROADCAST | `4` |
| PER\_HOST\_V1 | `2` |
| PER\_HOST\_V2 | `3` |
| PER\_SHARD\_V1 | `1` |
| SLICED | `5` |
tensorflow tf.compat.v1.estimator.tpu.TPUConfig tf.compat.v1.estimator.tpu.TPUConfig
====================================
TPU related configuration required by `TPUEstimator`.
```
tf.compat.v1.estimator.tpu.TPUConfig(
iterations_per_loop=2,
num_shards=None,
num_cores_per_replica=None,
per_host_input_for_training=True,
tpu_job_name=None,
initial_infeed_sleep_secs=None,
input_partition_dims=None,
eval_training_input_configuration=InputPipelineConfig.PER_HOST_V1,
experimental_host_call_every_n_steps=1,
experimental_allow_per_host_v2_parallel_get_next=False,
experimental_feed_hook=None
)
```
Migrate to TF2
--------------
TPU Estimator manages its own TensorFlow graph and session, so it is not compatible with TF2 behaviors. We recommend that you migrate to the newer [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy). See the [TPU guide](https://www.tensorflow.org/guide/tpu) for details.
Description
-----------
| Args |
| `iterations_per_loop` | This is the number of train steps running in TPU system before returning to CPU host for each `Session.run`. This means global step is increased `iterations_per_loop` times in one `Session.run`. It is recommended to be set as number of global steps for next checkpoint. Note that in evaluation don't use this value, instead we run total eval `steps` on TPU for a single `Session.run`. [Experimental]: `iterations_per_loop` can be specified as a time interval. To specify N seconds in one `Session.run`, one can specify it as `Ns` and substitute the N with the N with the number of desired seconds. Alternatively, the unit of time can also be specified in minutes or hours, e.g. `3600s` or `60m` or `1h`. |
| `num_shards` | (Deprecated, ignored by TPUEstimator). The number of model replicas in the system. For non-model-parallelism case, this number equals the total number of TPU cores. For model-parallelism, the total number of TPU cores equals num\_cores\_per\_replica \* num\_shards. |
| `num_cores_per_replica` | Defaults to `None`, which disables model parallelism. An integer which describes the number of TPU cores per model replica. This is required by model-parallelism which enables partitioning the model to multiple cores. Currently num\_cores\_per\_replica must be 1, 2, 4, or 8. |
| `per_host_input_for_training` | If `True`, for `PER_HOST_V1`, the `input_fn` is invoked once on each host, and the number of hosts must be smaller or equal to the number of replicas. For PER\_HOST\_V2, the `input_fn` is invoked once for each host (if the number of hosts is less than the number of replicas) or replica (if the number of replicas is less than the number of hosts. With the per-core input pipeline configuration, it is invoked once for each core. With a global batch size `train_batch_size` in `TPUEstimator` constructor, the batch size for each shard is `train_batch_size` // #hosts in the `True` or `PER_HOST_V1` mode. In `PER_HOST_V2` mode, it is `train_batch_size` // #cores. In `BROADCAST` mode, `input_fn` is only invoked once on host 0 and the tensors are broadcasted to all other replicas. The batch size equals to `train_batch_size`. With the per-core input pipeline configuration, the shard batch size is also `train_batch_size` // #cores. Note: per\_host\_input\_for\_training==PER\_SHARD\_V1 only supports mode.TRAIN. |
| `tpu_job_name` | The name of the TPU job. Typically, this name is auto-inferred within TPUEstimator, however when using ClusterSpec propagation in more esoteric cluster configurations, you may need to specify the job name as a string. |
| `initial_infeed_sleep_secs` | The number of seconds the infeed thread should wait before enqueueing the first batch. This helps avoid timeouts for models that require a long compilation time. |
| `input_partition_dims` | A nested list to describe the partition dims for all the tensors from input\_fn(). The structure of input\_partition\_dims must match the structure of `features` and `labels` from input\_fn(). The total number of partitions must match `num_cores_per_replica`. For example, if input\_fn() returns two tensors: images with shape [N, H, W, C] and labels [N]. input\_partition\_dims = [[1, 2, 2, 1], None] will split the images to 4 pieces and feed into 4 TPU cores. labels tensor are directly broadcasted to all the TPU cores since the partition dims is `None`. Current limitations: This feature is only supported with the PER\_HOST\_V2 input mode. |
| `eval_training_input_configuration` | If `SLICED`, `input_fn` is only invoked once on host 0 and the tensors are broadcasted to all other replicas. Unlike per\_host\_input\_for\_training=BROADCAST, each replica will only get a slice of the data instead of a whole copy. If `PER_HOST_V1`, the behaviour is determined by per\_host\_input\_for\_training. |
| `experimental_host_call_every_n_steps` | Within a training loop, this argument sets how often host calls are performed during training. Host calls will be evaluated every n steps within a training loop where n is the value of this argument. |
| `experimental_allow_per_host_v2_parallel_get_next` | When enabled, allows concurrent execution of dataset get next calls when using PER\_HOST\_V2 input. May result in a performance increase for models with a small step time, but as a consequence TPUEstimator may non-deterministically distribute batches to different cores, rather than guaranteeing round robin behavior. |
| `experimental_feed_hook` | This is a class which user can provide to the TPU estimator to override the default TPUInfeedOutfeedSessionHook implementation and add customized implementatioin to handle infeed outfeed logic. If given class is None, TPU estimator uses default TPUInfeedOutfeedSessionHook implementation in tpu\_estimator.py. If not None, TPU estimator uses this customized tpu infeed outfeed session hook class rather to override the default one. |
| Raises |
| `ValueError` | If `num_cores_per_replica` is not 1, 2, 4, 8, ..., 128. |
| Attributes |
| `iterations_per_loop` | A `namedtuple` alias for field number 0 |
| `num_shards` | A `namedtuple` alias for field number 1 |
| `num_cores_per_replica` | A `namedtuple` alias for field number 2 |
| `per_host_input_for_training` | A `namedtuple` alias for field number 3 |
| `tpu_job_name` | A `namedtuple` alias for field number 4 |
| `initial_infeed_sleep_secs` | A `namedtuple` alias for field number 5 |
| `input_partition_dims` | A `namedtuple` alias for field number 6 |
| `eval_training_input_configuration` | A `namedtuple` alias for field number 7 |
| `experimental_host_call_every_n_steps` | A `namedtuple` alias for field number 8 |
| `experimental_allow_per_host_v2_parallel_get_next` | A `namedtuple` alias for field number 9 |
| `experimental_feed_hook` | A `namedtuple` alias for field number 10 |
tensorflow Module: tf.compat.v1.estimator.tpu.experimental Module: tf.compat.v1.estimator.tpu.experimental
===============================================
Public API for tf.estimator.tpu.experimental namespace.
Classes
-------
[`class EmbeddingConfigSpec`](experimental/embeddingconfigspec): Class to keep track of the specification for TPU embeddings.
tensorflow tf.compat.v1.estimator.tpu.TPUEstimator tf.compat.v1.estimator.tpu.TPUEstimator
=======================================
Estimator with TPU support.
Inherits From: [`Estimator`](../estimator)
```
tf.compat.v1.estimator.tpu.TPUEstimator(
model_fn=None,
model_dir=None,
config=None,
params=None,
use_tpu=True,
train_batch_size=None,
eval_batch_size=None,
predict_batch_size=None,
batch_axis=None,
eval_on_tpu=True,
export_to_tpu=True,
export_to_cpu=True,
warm_start_from=None,
embedding_config_spec=None,
export_saved_model_api_version=ExportSavedModelApiVersion.V1
)
```
Migrate to TF2
--------------
TPU Estimator manages its own TensorFlow graph and session, so it is not compatible with TF2 behaviors. We recommend that you migrate to the newer [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy). See the [TPU guide](https://www.tensorflow.org/guide/tpu) for details.
Description
-----------
TPUEstimator also supports training on CPU and GPU. You don't need to define a separate [`tf.estimator.Estimator`](../../../../estimator/estimator).
TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks.
TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the `input_fn` and `model_fn`. Users should specify global batch size in constructor, and then get the batch size for each shard in `input_fn` and `model_fn` by `params['batch_size']`.
* For training, `model_fn` gets per-core batch size; `input_fn` may get per-core or per-host batch size depending on `per_host_input_for_training` in `TPUConfig` (See docstring for TPUConfig for details).
* For evaluation and prediction, `model_fn` gets per-core batch size and `input_fn` get per-host batch size.
Evaluation
==========
`model_fn` should return `TPUEstimatorSpec`, which expects the `eval_metrics` for TPU evaluation. If eval\_on\_tpu is False, the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply.
`TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`, where `tensors` could be a list of any nested structure of `Tensor`s (See `TPUEstimatorSpec` for details). `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple.
One can set `use_tpu` to `False` for testing. All training, evaluation, and predict will be executed on CPU. `input_fn` and `model_fn` will receive `train_batch_size` or `eval_batch_size` unmodified as `params['batch_size']`.
#### Current limitations:
1. TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode.
2. `input_fn` for evaluation should **NOT** raise an end-of-input exception (`OutOfRangeError` or `StopIteration`). And all evaluation steps and all batches should have the same size.
Example (MNIST):
----------------
```
# The metric Fn which runs on CPU.
def metric_fn(labels, logits):
predictions = tf.argmax(logits, 1)
return {
'accuracy': tf.compat.v1.metrics.precision(
labels=labels, predictions=predictions),
}
# Your model Fn which runs on TPU (eval_metrics is list in this example)
def model_fn(features, labels, mode, config, params):
...
logits = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, [labels, logits]))
# or specify the eval_metrics tensors as dict.
def model_fn(features, labels, mode, config, params):
...
final_layer_output = ...
if mode = tf.estimator.ModeKeys.EVAL:
return tpu_estimator.TPUEstimatorSpec(
mode=mode,
loss=loss,
eval_metrics=(metric_fn, {
'labels': labels,
'logits': final_layer_output,
}))
```
Prediction
==========
Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU `.predict`, i.e., creating a new `TPUEstimator` instance with `use_tpu=False`, might be more convenient.
>
> **Note:** In contrast to TPU training/evaluation, the `input_fn` for prediction *should* raise an end-of-input exception (`OutOfRangeError` or `StopIteration`), which serves as the stopping signal to `TPUEstimator`. To be precise, the ops created by `input_fn` produce one batch of the data. The `predict()` API processes one batch at a time. When reaching the end of the data source, an end-of-input exception should be raised by one of these operations. The user usually does not need to do this manually. As long as the dataset is not repeated forever, the [`tf.data`](../../../../data) API will raise an end-of-input exception automatically after the last batch has been produced.
>
>
> **Note:** Estimator.predict returns a Python generator. Please consume all the data from the generator so that TPUEstimator can shutdown the TPU system properly for user.
>
#### Current limitations:
1. TPU prediction only works on a single host (one TPU worker).
2. `input_fn` must return a `Dataset` instance rather than `features`. In fact, .train() and .evaluate() also support Dataset as return value.
Example (MNIST):
----------------
```
height = 32
width = 32
total_examples = 100
def predict_input_fn(params):
batch_size = params['batch_size']
images = tf.random.uniform(
[total_examples, height, width, 3], minval=-1, maxval=1)
dataset = tf.data.Dataset.from_tensor_slices(images)
dataset = dataset.map(lambda images: {'image': images})
dataset = dataset.batch(batch_size)
return dataset
def model_fn(features, labels, params, mode):
# Generate predictions, called 'output', from features['image']
if mode == tf.estimator.ModeKeys.PREDICT:
return tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
predictions={
'predictions': output,
'is_padding': features['is_padding']
})
tpu_est = TPUEstimator(
model_fn=model_fn,
...,
predict_batch_size=16)
# Fully consume the generator so that TPUEstimator can shutdown the TPU
# system.
for item in tpu_est.predict(input_fn=input_fn):
# Filter out item if the `is_padding` is 1.
# Process the 'predictions'
```
Exporting
=========
`export_saved_model` exports 2 metagraphs, one with [`saved_model.SERVING`](https://www.tensorflow.org/api_docs/python/tf/saved_model#SERVING), and another with [`saved_model.SERVING`](https://www.tensorflow.org/api_docs/python/tf/saved_model#SERVING) and [`saved_model.TPU`](https://www.tensorflow.org/api_docs/python/tf/saved_model#TPU) tags. At serving time, these tags are used to select the appropriate metagraph to load.
Before running the graph on TPU, the TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please use `session.run(tpu.initialize_system())`.
There are two versions of the API: 1 or 2.
In V1, the exported CPU graph is `model_fn` as it is. The exported TPU graph wraps `tpu.rewrite()` and `TPUPartitionedCallOp` around `model_fn` so `model_fn` is on TPU by default. To place ops on CPU, `tpu.outside_compilation(host_call, logits)` can be used.
#### Example:
```
def model_fn(features, labels, mode, config, params):
...
logits = ...
export_outputs = {
'logits': export_output_lib.PredictOutput(
{'logits': logits})
}
def host_call(logits):
class_ids = math_ops.argmax(logits)
classes = string_ops.as_string(class_ids)
export_outputs['classes'] =
export_output_lib.ClassificationOutput(classes=classes)
tpu.outside_compilation(host_call, logits)
...
```
In V2, `export_saved_model()` sets up `params['use_tpu']` flag to let the user know if the code is exporting to TPU (or not). When `params['use_tpu']` is `True`, users need to call `tpu.rewrite()`, `TPUPartitionedCallOp` and/or `batch_function()`.
TIP: V2 is recommended as it is more flexible (eg: batching, etc).
| Args |
| `model_fn` | Model function as required by `Estimator` which returns EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation\_hooks', and `prediction_hooks` must not capure any TPU Tensor inside the model\_fn. |
| `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` | An `tpu_config.RunConfig` configuration object. Cannot be `None`. |
| `params` | An optional `dict` of hyper parameters that will be passed into `input_fn` and `model_fn`. Keys are names of parameters, values are basic python types. There are reserved keys for `TPUEstimator`, including 'batch\_size'. |
| `use_tpu` | A bool indicating whether TPU support is enabled. Currently, - TPU training and evaluation respect this bit, but eval\_on\_tpu can override execution of eval. See below. |
| `train_batch_size` | An int representing the global training batch size. TPUEstimator transforms this global batch size to a per-shard batch size, as params['batch\_size'], when calling `input_fn` and `model_fn`. Cannot be `None` if `use_tpu` is `True`. Must be divisible by total number of replicas. |
| `eval_batch_size` | An int representing evaluation batch size. Must be divisible by total number of replicas. |
| `predict_batch_size` | An int representing the prediction batch size. Must be divisible by total number of replicas. |
| `batch_axis` | A python tuple of int values describing how each tensor produced by the Estimator `input_fn` should be split across the TPU compute shards. For example, if your input\_fn produced (images, labels) where the images tensor is in `HWCN` format, your shard dimensions would be [3, 0], where 3 corresponds to the `N` dimension of your images Tensor, and 0 corresponds to the dimension along which to split the labels to match up with the corresponding images. If None is supplied, and per\_host\_input\_for\_training is True, batches will be sharded based on the major dimension. If tpu\_config.per\_host\_input\_for\_training is False or `PER_HOST_V2`, batch\_axis is ignored. |
| `eval_on_tpu` | If False, evaluation runs on CPU or GPU. In this case, the model\_fn must return `EstimatorSpec` when called with `mode` as `EVAL`. |
| `export_to_tpu` | If True, `export_saved_model()` exports a metagraph for serving on TPU. Note that unsupported export modes such as EVAL will be ignored. For those modes, only a CPU model will be exported. Currently, export\_to\_tpu only supports PREDICT. |
| `export_to_cpu` | If True, `export_saved_model()` exports a metagraph for serving on CPU. |
| `warm_start_from` | Optional string filepath to a checkpoint or SavedModel to warm-start from, or a [`tf.estimator.WarmStartSettings`](../../../../estimator/warmstartsettings) object to fully configure warm-starting. If the string filepath is provided instead of a `WarmStartSettings`, then all variables are warm-started, and it is assumed that vocabularies and Tensor names are unchanged. |
| `embedding_config_spec` | Optional EmbeddingConfigSpec instance to support using TPU embedding. |
| `export_saved_model_api_version` | an integer: 1 or 2. 1 corresponds to V1, 2 corresponds to V2. (Defaults to V1). With V1, `export_saved_model()` adds rewrite() and TPUPartitionedCallOp() for user; while in v2, user is expected to add rewrite(), TPUPartitionedCallOp() etc in their model\_fn. |
| Raises |
| `ValueError` | `params` has reserved keys already. |
| Attributes |
| `config` | |
| `model_dir` | |
| `model_fn` | Returns the `model_fn` which is bound to `self.params`. |
| `params` | |
Methods
-------
### `eval_dir`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L389-L401)
```
eval_dir(
name=None
)
```
Shows the directory name where evaluation metrics are dumped.
| Args |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A string which is the path of directory contains evaluation metrics. |
### `evaluate`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py#L3104-L3123)
```
evaluate(
input_fn, steps=None, hooks=None, checkpoint_path=None, name=None
)
```
Evaluates the model given evaluation data `input_fn`.
For each step, calls `input_fn`, which returns one batch of data. Evaluates until:
* `steps` batches are processed, or
* `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../../errors/outofrangeerror) or `StopIteration`).
| Args |
| `input_fn` | A function that constructs the input data for evaluation. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `steps` | Number of steps for which to evaluate model. If `None`, evaluates until `input_fn` raises an end-of-input exception. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the evaluation call. |
| `checkpoint_path` | Path of a specific checkpoint to evaluate. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, evaluation is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `name` | Name of the evaluation if user needs to run multiple evaluations on different data sets, such as on training data vs test data. Metrics for different evaluations are saved in separate folders, and appear separately in tensorboard. |
| Returns |
| A dict containing the evaluation metrics specified in `model_fn` keyed by name, as well as an entry `global_step` which contains the value of the global step for which this evaluation was performed. For canned estimators, the dict contains the `loss` (mean loss per mini-batch) and the `average_loss` (mean loss per sample). Canned classifiers also return the `accuracy`. Canned regressors also return the `label/mean` and the `prediction/mean`. |
| Raises |
| `ValueError` | If `steps <= 0`. |
### `experimental_export_all_saved_models`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L738-L810)
```
experimental_export_all_saved_models(
export_dir_base,
input_receiver_fn_map,
assets_extra=None,
as_text=False,
checkpoint_path=None
)
```
Exports a `SavedModel` with `tf.MetaGraphDefs` for each requested mode.
For each mode passed in via the `input_receiver_fn_map`, this method builds a new graph by calling the `input_receiver_fn` to obtain feature and label `Tensor`s. Next, this method calls the `Estimator`'s `model_fn` in the passed mode to generate the model graph based on those features and labels, and restores the given checkpoint (or, lacking that, the most recent checkpoint) into the graph. Only one of the modes is used for saving variables to the `SavedModel` (order of preference: [`tf.estimator.ModeKeys.TRAIN`](../../../../estimator/modekeys#TRAIN), [`tf.estimator.ModeKeys.EVAL`](../../../../estimator/modekeys#EVAL), then [`tf.estimator.ModeKeys.PREDICT`](../../../../estimator/modekeys#PREDICT)), such that up to three `tf.MetaGraphDefs` are saved with a single set of variables in a single `SavedModel` directory.
For the variables and `tf.MetaGraphDefs`, a timestamped export directory below `export_dir_base`, and writes a `SavedModel` into it containing the `tf.MetaGraphDef` for the given mode and its associated signatures.
For prediction, the exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/exportoutput)s, and the inputs are always the input receivers provided by the `serving_input_receiver_fn`.
For training and evaluation, the `train_op` is stored in an extra collection, and loss, metrics, and predictions are included in a `SignatureDef` for the mode in question.
Extra assets may be written into the `SavedModel` via the `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `input_receiver_fn_map` | dict of [`tf.estimator.ModeKeys`](../../../../estimator/modekeys) to `input_receiver_fn` mappings, where the `input_receiver_fn` is a function that takes no arguments and returns the appropriate subclass of `InputReceiver`. |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if any `input_receiver_fn` is `None`, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_saved_model`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L659-L736)
```
export_saved_model(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
experimental_mode=ModeKeys.PREDICT
)
```
Exports inference graph as a `SavedModel` into the given dir.
For a detailed guide on SavedModel, see [Using the SavedModel format](https://tensorflow.org/guide/saved_model#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
The experimental\_mode parameter can be used to export a single train/eval/predict graph as a `SavedModel`. See `experimental_export_all_saved_models` for full docs.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `experimental_mode` | [`tf.estimator.ModeKeys`](../../../../estimator/modekeys) value indicating with mode will be exported. Note that this feature is experimental. |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `export_savedmodel`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L1688-L1762)
```
export_savedmodel(
export_dir_base,
serving_input_receiver_fn,
assets_extra=None,
as_text=False,
checkpoint_path=None,
strip_default_attrs=False
)
```
Exports inference graph as a `SavedModel` into the given dir. (deprecated)
For a detailed guide, see [SavedModel from Estimators.](https://www.tensorflow.org/guide/estimator#savedmodels_from_estimators).
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 `tf.MetaGraphDef` saved from this session.
The exported `MetaGraphDef` will provide one `SignatureDef` for each element of the `export_outputs` dict returned from the `model_fn`, named using the same keys. One of these keys is always `tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY`, indicating which signature will be served when a serving request does not specify one. For each signature, the outputs are provided by the corresponding [`tf.estimator.export.ExportOutput`](../../../../estimator/export/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 `assets_extra` argument. This should be a dict, where each key gives a destination path (including the filename) relative to the assets.extra directory. The corresponding value gives the full path of the source file to be copied. For example, the simple case of copying a single file without renaming it is specified as `{'my_asset_file.txt': '/path/to/my_asset_file.txt'}`.
| Args |
| `export_dir_base` | A string containing a directory in which to create timestamped subdirectories containing exported `SavedModel`s. |
| `serving_input_receiver_fn` | A function that takes no argument and returns a [`tf.estimator.export.ServingInputReceiver`](../../../../estimator/export/servinginputreceiver) or [`tf.estimator.export.TensorServingInputReceiver`](../../../../estimator/export/tensorservinginputreceiver). |
| `assets_extra` | A dict specifying how to populate the assets.extra directory within the exported `SavedModel`, or `None` if no extra assets are needed. |
| `as_text` | whether to write the `SavedModel` proto in text format. |
| `checkpoint_path` | The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the `NodeDef`s. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| Returns |
| The path to the exported directory as a bytes object. |
| Raises |
| `ValueError` | if no `serving_input_receiver_fn` is provided, no `export_outputs` are provided, or no checkpoint can be found. |
### `get_variable_names`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L261-L272)
```
get_variable_names()
```
Returns list of all variable names in this model.
| Returns |
| List of names. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `get_variable_value`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L245-L259)
```
get_variable_value(
name
)
```
Returns value of the variable given by name.
| Args |
| `name` | string or a list of string, name of the tensor. |
| Returns |
| Numpy array - value of the tensor. |
| Raises |
| `ValueError` | If the `Estimator` has not produced a checkpoint yet. |
### `latest_checkpoint`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/estimator.py#L274-L282)
```
latest_checkpoint()
```
Finds the filename of the latest saved checkpoint file in `model_dir`.
| Returns |
| The full path to the latest checkpoint or `None` if no checkpoint was found. |
### `predict`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py#L3125-L3148)
```
predict(
input_fn,
predict_keys=None,
hooks=None,
checkpoint_path=None,
yield_single_examples=True
)
```
Yields predictions for given features.
Please note that interleaving two predict outputs does not work. See: [issue/20506](https://github.com/tensorflow/tensorflow/issues/20506#issuecomment-422208517)
| Args |
| `input_fn` | A function that constructs the features. Prediction continues until `input_fn` raises an end-of-input exception ([`tf.errors.OutOfRangeError`](../../../../errors/outofrangeerror) or `StopIteration`). See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * [`tf.data.Dataset`](../../../../data/dataset) object -- Outputs of `Dataset` object must have same constraints as below.
* features -- A [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor`. features are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
* A tuple, in which case the first item is extracted as features.
|
| `predict_keys` | list of `str`, name of the keys to predict. It is used if the [`tf.estimator.EstimatorSpec.predictions`](../../../../estimator/estimatorspec#predictions) is a `dict`. If `predict_keys` is used then rest of the predictions will be filtered from the dictionary. If `None`, returns all. |
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the prediction call. |
| `checkpoint_path` | Path of a specific checkpoint to predict. If `None`, the latest checkpoint in `model_dir` is used. If there are no checkpoints in `model_dir`, prediction is run with newly initialized `Variables` instead of ones restored from checkpoint. |
| `yield_single_examples` | If `False`, yields the whole batch as returned by the `model_fn` instead of decomposing the batch into individual elements. This is useful if `model_fn` returns some tensors whose first dimension is not equal to the batch size. |
| Yields |
| Evaluated values of `predictions` tensors. |
| Raises |
| `ValueError` | If batch length of predictions is not the same and `yield_single_examples` is `True`. |
| `ValueError` | If there is a conflict between `predict_keys` and `predictions`. For example if `predict_keys` is not `None` but [`tf.estimator.EstimatorSpec.predictions`](../../../../estimator/estimatorspec#predictions) is not a `dict`. |
### `train`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/tpu/tpu_estimator.py#L3083-L3102)
```
train(
input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None
)
```
Trains a model given training data `input_fn`.
| Args |
| `input_fn` | A function that provides input data for training as minibatches. See [Premade Estimators](https://tensorflow.org/guide/premade_estimators#create_input_functions) for more information. The function should construct and return one of the following: * A [`tf.data.Dataset`](../../../../data/dataset) object: Outputs of `Dataset` object must be a tuple `(features, labels)` with same constraints as below.
* A tuple `(features, labels)`: Where `features` is a [`tf.Tensor`](../../../../tensor) or a dictionary of string feature name to `Tensor` and `labels` is a `Tensor` or a dictionary of string label name to `Tensor`. Both `features` and `labels` are consumed by `model_fn`. They should satisfy the expectation of `model_fn` from inputs.
|
| `hooks` | List of `tf.train.SessionRunHook` subclass instances. Used for callbacks inside the training loop. |
| `steps` | Number of steps for which to train the model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. `steps` works incrementally. If you call two times `train(steps=10)` then training occurs in total 20 steps. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before 20 steps. If you don't want to have incremental behavior please set `max_steps` instead. If set, `max_steps` must be `None`. |
| `max_steps` | Number of total steps for which to train model. If `None`, train forever or train until `input_fn` generates the `tf.errors.OutOfRange` error or `StopIteration` exception. If set, `steps` must be `None`. If `OutOfRange` or `StopIteration` occurs in the middle, training stops before `max_steps` steps. Two calls to `train(steps=100)` means 200 training iterations. On the other hand, two calls to `train(max_steps=100)` means that the second call will not do any iteration since first call did all 100 steps. |
| `saving_listeners` | list of `CheckpointSaverListener` objects. Used for callbacks that run immediately before or after checkpoint savings. |
| Returns |
| `self`, for chaining. |
| Raises |
| `ValueError` | If both `steps` and `max_steps` are not `None`. |
| `ValueError` | If either `steps` or `max_steps <= 0`. |
| programming_docs |
tensorflow tf.compat.v1.estimator.tpu.RunConfig tf.compat.v1.estimator.tpu.RunConfig
====================================
RunConfig with TPU support.
Inherits From: [`RunConfig`](../../../../estimator/runconfig)
```
tf.compat.v1.estimator.tpu.RunConfig(
tpu_config=None,
evaluation_master=None,
master=None,
cluster=None,
**kwargs
)
```
| Args |
| `tpu_config` | the TPUConfig that specifies TPU-specific configuration. |
| `evaluation_master` | a string. The address of the master to use for eval. Defaults to master if not set. |
| `master` | a string. The address of the master to use for training. |
| `cluster` | a ClusterResolver |
| `**kwargs` | keyword config parameters. |
| Raises |
| `ValueError` | if cluster is not None and the provided session\_config has a cluster\_def already. |
| Attributes |
| `checkpoint_save_graph_def` | |
| `cluster` | |
| `cluster_spec` | |
| `device_fn` | Returns the device\_fn. If device\_fn is not `None`, it overrides the default device function used in `Estimator`. Otherwise the default one is used. |
| `eval_distribute` | Optional [`tf.distribute.Strategy`](../../../../distribute/strategy) for evaluation. |
| `evaluation_master` | |
| `experimental_max_worker_delay_secs` | |
| `global_id_in_cluster` | The global id in the training cluster. All global ids in the training cluster are assigned from an increasing sequence of consecutive integers. The first id is 0.
**Note:** Task id (the property field `task_id`) is tracking the index of the node among all nodes with the SAME task type. For example, given the cluster definition as follows:
```
cluster = {'chief': ['host0:2222'],
'ps': ['host1:2222', 'host2:2222'],
'worker': ['host3:2222', 'host4:2222', 'host5:2222']}
```
Nodes with task type `worker` can have id 0, 1, 2. Nodes with task type `ps` can have id, 0, 1. So, `task_id` is not unique, but the pair (`task_type`, `task_id`) can uniquely determine a node in the cluster. Global id, i.e., this field, is tracking the index of the node among ALL nodes in the cluster. It is uniquely assigned. For example, for the cluster spec given above, the global ids are assigned as:
```
task_type | task_id | global_id
--------------------------------
chief | 0 | 0
worker | 0 | 1
worker | 1 | 2
worker | 2 | 3
ps | 0 | 4
ps | 1 | 5
```
|
| `is_chief` | |
| `keep_checkpoint_every_n_hours` | |
| `keep_checkpoint_max` | |
| `log_step_count_steps` | |
| `master` | |
| `model_dir` | |
| `num_ps_replicas` | |
| `num_worker_replicas` | |
| `protocol` | Returns the optional protocol value. |
| `save_checkpoints_secs` | |
| `save_checkpoints_steps` | |
| `save_summary_steps` | |
| `service` | Returns the platform defined (in TF\_CONFIG) service dict. |
| `session_config` | |
| `session_creation_timeout_secs` | |
| `task_id` | |
| `task_type` | |
| `tf_random_seed` | |
| `tpu_config` | |
| `train_distribute` | Optional [`tf.distribute.Strategy`](../../../../distribute/strategy) for training. |
Methods
-------
### `replace`
[View source](https://github.com/tensorflow/estimator/tree/master/tensorflow_estimator/python/estimator/tpu/tpu_config.py#L331-L338)
```
replace(
**kwargs
)
```
Returns a new instance of `RunConfig` replacing specified properties.
Only the properties in the following list are allowed to be replaced:
* `model_dir`,
* `tf_random_seed`,
* `save_summary_steps`,
* `save_checkpoints_steps`,
* `save_checkpoints_secs`,
* `session_config`,
* `keep_checkpoint_max`,
* `keep_checkpoint_every_n_hours`,
* `log_step_count_steps`,
* `train_distribute`,
* `device_fn`,
* `protocol`.
* `eval_distribute`,
* `experimental_distribute`,
* `experimental_max_worker_delay_secs`,
In addition, either `save_checkpoints_steps` or `save_checkpoints_secs` can be set (should not be both).
| Args |
| `**kwargs` | keyword named properties with new values. |
| Raises |
| `ValueError` | If any property name in `kwargs` does not exist or is not allowed to be replaced, or both `save_checkpoints_steps` and `save_checkpoints_secs` are set. |
| Returns |
| a new instance of `RunConfig`. |
tensorflow tf.compat.v1.estimator.tpu.experimental.EmbeddingConfigSpec tf.compat.v1.estimator.tpu.experimental.EmbeddingConfigSpec
===========================================================
Class to keep track of the specification for TPU embeddings.
```
tf.compat.v1.estimator.tpu.experimental.EmbeddingConfigSpec(
feature_columns=None,
optimization_parameters=None,
clipping_limit=None,
pipeline_execution_with_tensor_core=False,
experimental_gradient_multiplier_fn=None,
feature_to_config_dict=None,
table_to_config_dict=None,
partition_strategy='div',
profile_data_directory=None
)
```
Migrate to TF2
--------------
TPU Estimator manages its own TensorFlow graph and session, so it is not compatible with TF2 behaviors. We recommend that you migrate to the newer [`tf.distribute.TPUStrategy`](../../../../../distribute/tpustrategy). See the [TPU guide](https://www.tensorflow.org/guide/tpu) for details.
Description
-----------
Pass this class to `tf.estimator.tpu.TPUEstimator` via the `embedding_config_spec` parameter. At minimum you need to specify `feature_columns` and `optimization_parameters`. The feature columns passed should be created with some combination of `tf.tpu.experimental.embedding_column` and `tf.tpu.experimental.shared_embedding_columns`.
TPU embeddings do not support arbitrary Tensorflow optimizers and the main optimizer you use for your model will be ignored for the embedding table variables. Instead TPU embeddigns support a fixed set of predefined optimizers that you can select from and set the parameters of. These include adagrad, adam and stochastic gradient descent. Each supported optimizer has a `Parameters` class in the [`tf.tpu.experimental`](../../../../../tpu/experimental) namespace.
```
column_a = tf.feature_column.categorical_column_with_identity(...)
column_b = tf.feature_column.categorical_column_with_identity(...)
column_c = tf.feature_column.categorical_column_with_identity(...)
tpu_shared_columns = tf.tpu.experimental.shared_embedding_columns(
[column_a, column_b], 10)
tpu_non_shared_column = tf.tpu.experimental.embedding_column(
column_c, 10)
tpu_columns = [tpu_non_shared_column] + tpu_shared_columns
...
def model_fn(features):
dense_features = tf.keras.layers.DenseFeature(tpu_columns)
embedded_feature = dense_features(features)
...
estimator = tf.estimator.tpu.TPUEstimator(
model_fn=model_fn,
...
embedding_config_spec=tf.estimator.tpu.experimental.EmbeddingConfigSpec(
column=tpu_columns,
optimization_parameters=(
tf.estimator.tpu.experimental.AdagradParameters(0.1))))
```
| Args |
| `feature_columns` | All embedding `FeatureColumn`s used by model. |
| `optimization_parameters` | An instance of `AdagradParameters`, `AdamParameters` or `StochasticGradientDescentParameters`. This optimizer will be applied to all embedding variables specified by `feature_columns`. |
| `clipping_limit` | (Optional) Clipping limit (absolute value). |
| `pipeline_execution_with_tensor_core` | setting this to `True` makes training faster, but trained model will be different if step N and step N+1 involve the same set of embedding IDs. Please see `tpu_embedding_configuration.proto` for details. |
| `experimental_gradient_multiplier_fn` | (Optional) A Fn taking global step as input returning the current multiplier for all embedding gradients. |
| `feature_to_config_dict` | A dictionary mapping feature names to instances of the class `FeatureConfig`. Either features\_columns or the pair of `feature_to_config_dict` and `table_to_config_dict` must be specified. |
| `table_to_config_dict` | A dictionary mapping feature names to instances of the class `TableConfig`. Either features\_columns or the pair of `feature_to_config_dict` and `table_to_config_dict` must be specified. |
| `partition_strategy` | A string, determining how tensors are sharded to the tpu hosts. See [`tf.nn.safe_embedding_lookup_sparse`](../../../../../nn/safe_embedding_lookup_sparse) for more details. Allowed value are `"div"` and `"mod"'. If`"mod"`is used, evaluation and exporting the model to CPU will not work as expected. </td> </tr><tr> <td>`profile\_data\_directory` | Directory where embedding lookup statistics are stored. These statistics summarize information about the inputs to the embedding lookup operation, in particular, the average number of embedding IDs per example and how well the embedding IDs are load balanced across the system. The lookup statistics are used during TPU initialization for embedding table partitioning. Collection of lookup statistics is done at runtime by profiling the embedding inputs, only a small fraction of input samples are profiled to minimize host CPU overhead. Once a suitable number of samples are profiled, the lookup statistics are saved to table-specific files in the profile data directory generally at the end of a TPU training loop. The filename corresponding to each table is obtained by hashing table specific parameters (e.g., table name and number of features) and global configuration parameters (e.g., sharding strategy and task count). The same profile data directory can be shared among several models to reuse embedding lookup statistics. |
| Raises |
| `ValueError` | If the feature\_columns are not specified. |
| `TypeError` | If the feature columns are not of ths correct type (one of \_SUPPORTED\_FEATURE\_COLUMNS, \_TPU\_EMBEDDING\_COLUMN\_CLASSES OR \_EMBEDDING\_COLUMN\_CLASSES). |
| `ValueError` | If `optimization_parameters` is not one of the required types. |
| Attributes |
| `feature_columns` | A `namedtuple` alias for field number 0 |
| `tensor_core_feature_columns` | A `namedtuple` alias for field number 1 |
| `optimization_parameters` | A `namedtuple` alias for field number 2 |
| `clipping_limit` | A `namedtuple` alias for field number 3 |
| `pipeline_execution_with_tensor_core` | A `namedtuple` alias for field number 4 |
| `experimental_gradient_multiplier_fn` | A `namedtuple` alias for field number 5 |
| `feature_to_config_dict` | A `namedtuple` alias for field number 6 |
| `table_to_config_dict` | A `namedtuple` alias for field number 7 |
| `partition_strategy` | A `namedtuple` alias for field number 8 |
| `profile_data_directory` | A `namedtuple` alias for field number 9 |
tensorflow tf.compat.v1.estimator.inputs.numpy_input_fn tf.compat.v1.estimator.inputs.numpy\_input\_fn
==============================================
Returns input function that would feed dict of numpy arrays into the model.
```
tf.compat.v1.estimator.inputs.numpy_input_fn(
x,
y=None,
batch_size=128,
num_epochs=1,
shuffle=None,
queue_capacity=1000,
num_threads=1
)
```
This returns a function outputting `features` and `targets` based on the dict of numpy arrays. The dict `features` has the same keys as the `x`. The dict `targets` has the same keys as the `y` if `y` is a dict.
#### Example:
```
age = np.arange(4) * 1.0
height = np.arange(32, 36)
x = {'age': age, 'height': height}
y = np.arange(-32, -28)
with tf.Session() as session:
input_fn = numpy_io.numpy_input_fn(
x, y, batch_size=2, shuffle=False, num_epochs=1)
```
| Args |
| `x` | numpy array object or dict of numpy array objects. If an array, the array will be treated as a single feature. |
| `y` | numpy array object or dict of numpy array object. `None` if absent. |
| `batch_size` | Integer, size of batches to return. |
| `num_epochs` | Integer, number of epochs to iterate over data. If `None` will run forever. |
| `shuffle` | Boolean, if True shuffles the queue. Avoid shuffle at prediction time. |
| `queue_capacity` | Integer, size of queue to accumulate. |
| `num_threads` | Integer, number of threads used for reading and enqueueing. In order to have predicted and repeatable order of reading and enqueueing, such as in prediction and evaluation mode, `num_threads` should be 1. |
| Returns |
| Function, that has signature of ()->(dict of `features`, `targets`) |
| Raises |
| `ValueError` | if the shape of `y` mismatches the shape of values in `x` (i.e., values in `x` have same shape). |
| `ValueError` | if duplicate keys are in both `x` and `y` when `y` is a dict. |
| `ValueError` | if x or y is an empty dict. |
| `TypeError` | `x` is not a dict or array. |
| `ValueError` | if 'shuffle' is not provided or a bool. |
tensorflow tf.compat.v1.estimator.inputs.pandas_input_fn tf.compat.v1.estimator.inputs.pandas\_input\_fn
===============================================
Returns input function that would feed Pandas DataFrame into the model.
```
tf.compat.v1.estimator.inputs.pandas_input_fn(
x,
y=None,
batch_size=128,
num_epochs=1,
shuffle=None,
queue_capacity=1000,
num_threads=1,
target_column='target'
)
```
>
> **Note:** `y`'s index must match `x`'s index.
>
| Args |
| `x` | pandas `DataFrame` object. |
| `y` | pandas `Series` object or `DataFrame`. `None` if absent. |
| `batch_size` | int, size of batches to return. |
| `num_epochs` | int, number of epochs to iterate over data. If not `None`, read attempts that would exceed this value will raise `OutOfRangeError`. |
| `shuffle` | bool, whether to read the records in random order. |
| `queue_capacity` | int, size of the read queue. If `None`, it will be set roughly to the size of `x`. |
| `num_threads` | Integer, number of threads used for reading and enqueueing. In order to have predicted and repeatable order of reading and enqueueing, such as in prediction and evaluation mode, `num_threads` should be 1. |
| `target_column` | str, name to give the target column `y`. This parameter is not used when `y` is a `DataFrame`. |
| Returns |
| Function, that has signature of ()->(dict of `features`, `target`) |
| Raises |
| `ValueError` | if `x` already contains a column with the same name as `y`, or if the indexes of `x` and `y` don't match. |
| `ValueError` | if 'shuffle' is not provided or a bool. |
tensorflow Module: tf.compat.v1.io.gfile Module: tf.compat.v1.io.gfile
=============================
Public API for tf.io.gfile namespace.
Classes
-------
[`class GFile`](../../../io/gfile/gfile): File I/O wrappers without thread locking.
Functions
---------
[`copy(...)`](../../../io/gfile/copy): Copies data from `src` to `dst`.
[`exists(...)`](../../../io/gfile/exists): Determines whether a path exists or not.
[`get_registered_schemes(...)`](../../../io/gfile/get_registered_schemes): Returns the currently registered filesystem schemes.
[`glob(...)`](../../../io/gfile/glob): Returns a list of files that match the given pattern(s).
[`isdir(...)`](../../../io/gfile/isdir): Returns whether the path is a directory or not.
[`join(...)`](../../../io/gfile/join): Join one or more path components intelligently.
[`listdir(...)`](../../../io/gfile/listdir): Returns a list of entries contained within a directory.
[`makedirs(...)`](../../../io/gfile/makedirs): Creates a directory and all parent/intermediate directories.
[`mkdir(...)`](../../../io/gfile/mkdir): Creates a directory with the name given by `path`.
[`remove(...)`](../../../io/gfile/remove): Deletes the path located at 'path'.
[`rename(...)`](../../../io/gfile/rename): Rename or move a file / directory.
[`rmtree(...)`](../../../io/gfile/rmtree): Deletes everything under path recursively.
[`stat(...)`](../../../io/gfile/stat): Returns file statistics for a given path.
[`walk(...)`](../../../io/gfile/walk): Recursive directory tree generator for directories.
tensorflow tf.compat.v1.io.tf_record_iterator tf.compat.v1.io.tf\_record\_iterator
====================================
An iterator that read the records from a TFRecords file. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.python_io.tf_record_iterator`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/io/tf_record_iterator)
```
tf.compat.v1.io.tf_record_iterator(
path, options=None
)
```
| Args |
| `path` | The path to the TFRecords file. |
| `options` | (optional) A TFRecordOptions object. |
| Returns |
| An iterator of serialized TFRecords. |
| Raises |
| `IOError` | If `path` cannot be opened for reading. |
tensorflow tf.compat.v1.io.TFRecordCompressionType tf.compat.v1.io.TFRecordCompressionType
=======================================
The type of compression for the record.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.python_io.TFRecordCompressionType`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/io/TFRecordCompressionType)
| Class Variables |
| GZIP | `2` |
| NONE | `0` |
| ZLIB | `1` |
tensorflow tf.compat.v1.user_ops.my_fact tf.compat.v1.user\_ops.my\_fact
===============================
Example of overriding the generated code for an Op.
```
tf.compat.v1.user_ops.my_fact()
```
tensorflow tf.compat.v1.graph_util.must_run_on_cpu tf.compat.v1.graph\_util.must\_run\_on\_cpu
===========================================
Returns True if the given node\_def must run on CPU, otherwise False. (deprecated)
```
tf.compat.v1.graph_util.must_run_on_cpu(
node, pin_variables_on_cpu=False
)
```
| Args |
| `node` | The node to be assigned to a device. Could be either an ops.Operation or NodeDef. |
| `pin_variables_on_cpu` | If True, this function will return False if node\_def represents a variable-related op. |
| Returns |
| True if the given node must run on CPU, otherwise False. |
tensorflow tf.compat.v1.graph_util.remove_training_nodes tf.compat.v1.graph\_util.remove\_training\_nodes
================================================
Prunes out nodes that aren't needed for inference. (deprecated)
```
tf.compat.v1.graph_util.remove_training_nodes(
input_graph, protected_nodes=None
)
```
There are nodes like Identity and CheckNumerics that are only useful during training, and can be removed in graphs that will be used for nothing but inference. Here we identify and remove them, returning an equivalent graph. To be specific, CheckNumerics nodes are always removed, and Identity nodes that aren't involved in control edges are spliced out so that their input and outputs are directly connected.
| Args |
| `input_graph` | Model to analyze and prune. |
| `protected_nodes` | An optional list of names of nodes to be kept unconditionally. This is for example useful to preserve Identity output nodes. |
| Returns |
| A list of nodes with the unnecessary ones removed. |
tensorflow tf.compat.v1.graph_util.extract_sub_graph tf.compat.v1.graph\_util.extract\_sub\_graph
============================================
Extract the subgraph that can reach any of the nodes in 'dest\_nodes'. (deprecated)
```
tf.compat.v1.graph_util.extract_sub_graph(
graph_def, dest_nodes
)
```
| Args |
| `graph_def` | A graph\_pb2.GraphDef proto. |
| `dest_nodes` | An iterable of strings specifying the destination node names. |
| Returns |
| The GraphDef of the sub-graph. |
| Raises |
| `TypeError` | If 'graph\_def' is not a graph\_pb2.GraphDef proto. |
tensorflow tf.compat.v1.graph_util.tensor_shape_from_node_def_name tf.compat.v1.graph\_util.tensor\_shape\_from\_node\_def\_name
=============================================================
Convenience function to get a shape from a NodeDef's input string. (deprecated)
```
tf.compat.v1.graph_util.tensor_shape_from_node_def_name(
graph, input_name
)
```
| programming_docs |
tensorflow tf.compat.v1.graph_util.convert_variables_to_constants tf.compat.v1.graph\_util.convert\_variables\_to\_constants
==========================================================
Replaces all the variables in a graph with constants of the same values. (deprecated)
```
tf.compat.v1.graph_util.convert_variables_to_constants(
sess,
input_graph_def,
output_node_names,
variable_names_whitelist=None,
variable_names_blacklist=None
)
```
If you have a trained graph containing Variable ops, it can be convenient to convert them all to Const ops holding the same values. This makes it possible to describe the network fully with a single GraphDef file, and allows the removal of a lot of ops related to loading and saving the variables.
| Args |
| `sess` | Active TensorFlow session containing the variables. |
| `input_graph_def` | GraphDef object holding the network. |
| `output_node_names` | List of name strings for the result nodes of the graph. |
| `variable_names_whitelist` | The set of variable names to convert (by default, all variables are converted). |
| `variable_names_blacklist` | The set of variable names to omit converting to constants. |
| Returns |
| GraphDef containing a simplified version of the original. |
| Raises |
| `RuntimeError` | if a DT\_RESOURCE op is found whose ancestor Variables are both denylisted AND whitelisted for freezing. |
tensorflow tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite tf.compat.v1.mixed\_precision.enable\_mixed\_precision\_graph\_rewrite
======================================================================
Enable mixed precision via a graph rewrite.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.experimental.enable_mixed_precision_graph_rewrite`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/enable_mixed_precision_graph_rewrite)
```
tf.compat.v1.mixed_precision.enable_mixed_precision_graph_rewrite(
opt, loss_scale='dynamic'
)
```
Mixed precision is the use of both float32 and float16 data types when training a model to improve performance. This is achieved via a graph rewrite operation and a loss-scale optimizer.
Performing arithmetic operations in float16 takes advantage of specialized processing units, such as NVIDIA Tensor Cores, for much higher arithmetic throughput. However, due to the smaller representable range, performing the entire training with float16 can result in gradient underflow, that is, small gradient values becoming zeroes. Instead, performing only select arithmetic operations in float16 results in higher throughput and decreased training time when using compatible hardware accelerators while also reducing memory usage, typically without sacrificing model accuracy.
>
> **Note:** While the mixed precision rewrite changes the datatype of various layers throughout the model, the same accuracy reached in float32 is expected. If a `NaN` gradient occurs with dynamic loss scaling, the model update for that batch is skipped. In this case, the global step count is not incremented, and the `LossScaleOptimizer` attempts to decrease the loss scaling value to avoid `NaN` values in subsequent iterations. This approach has been shown to achieve the same accuracy as float32 and, in most cases, better training throughput.
>
#### Example:
```
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(64, activation='softmax'),
])
opt = tf.keras.optimizers.SGD()
opt = tf.train.experimental.enable_mixed_precision_graph_rewrite(opt)
model.compile(loss="mse", optimizer=opt)
x_train = np.random.random((1024, 64))
y_train = np.random.random((1024, 64))
model.fit(x_train, y_train)
```
Calling `enable_mixed_precision_graph_rewrite(opt)` enables the graph rewrite operation before computing gradients. The function additionally returns an `Optimizer` (`opt`) wrapped with a `LossScaleOptimizer`. This prevents underflow in the float16 tensors during the backward pass. An optimizer of type `tf.train.Optimizer` or [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) must be passed to this function, which will then be wrapped to use loss scaling.
The graph rewrite operation changes the `dtype` of certain operations in the graph from float32 to float16. There are several categories of operations that are either included or excluded by this rewrite operation. The following categories of Ops are defined inside corresponding functions under the class `AutoMixedPrecisionLists` in [auto\_mixed\_precision\_lists.h](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/grappler/optimizers/auto_mixed_precision_lists.h):
* `ClearList`: Ops that do not have numerically significant adverse effects. E.g. `ArgMax` and `Floor`.
* `AllowList`: Ops that are considered numerically safe for execution in float16, and thus are always converted. E.g. `Conv2D`.
* `DenyList`: Ops that are numerically unsafe to execute in float16 and can negatively affect downstream nodes. E.g. `Softmax`.
* `GrayList`: Ops that are considered numerically safe for execution in float16 unless downstream from a DenyList Op. E.g. `Add` and `AvgPool`.
When this function is used, gradients should only be computed and applied with the returned optimizer, either by calling `opt.minimize()` or `opt.compute_gradients()` followed by `opt.apply_gradients()`. Gradients should not be computed with [`tf.gradients`](../../../gradients) or [`tf.GradientTape`](../../../gradienttape). This is because the returned optimizer will apply loss scaling, and [`tf.gradients`](../../../gradients) or [`tf.GradientTape`](../../../gradienttape) will not. If you do directly use [`tf.gradients`](../../../gradients) or [`tf.GradientTape`](../../../gradienttape), your model may not converge due to float16 underflow problems.
When eager execution is enabled, the mixed precision graph rewrite is only enabled within [`tf.function`](../../../function)s, as outside [`tf.function`](../../../function)s, there is no graph.
For NVIDIA GPUs with Tensor cores, as a general performance guide, dimensions (such as batch size, input size, output size, and channel counts) should be powers of two if under 256, or otherwise divisible by 8 if above 256. For more information, check out the [NVIDIA Deep Learning Performance Guide](https://docs.nvidia.com/deeplearning/sdk/dl-performance-guide/index.html).
Currently, mixed precision is only enabled on NVIDIA Tensor Core GPUs with Compute Capability 7.0 and above (Volta, Turing, or newer architectures). The parts of the graph on CPUs and TPUs are untouched by the graph rewrite.
| Raises |
| `ValueError`, if the [`tf.keras.mixed_precision`](../../../keras/mixed_precision) API is also used by calling [`tf.keras.mixed_precision.set_global_policy`](../../../keras/mixed_precision/set_global_policy). Only one mixed precision API can be used. |
| Args |
| `opt` | An instance of a [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) or a `tf.train.Optimizer`. |
| `loss_scale` | Either an int/float, the string `"dynamic"`, or an instance of a [`tf.mixed_precision.experimental.LossScale`](https://www.tensorflow.org/api_docs/python/tf/mixed_precision/experimental/LossScale). The loss scale to use. It is recommended to keep this as its default value of `"dynamic"`, which will adjust the scaling automatically to prevent `Inf` or `NaN` values. |
| Returns |
| A version of `opt` that will use loss scaling to prevent underflow. |
tensorflow tf.compat.v1.mixed_precision.FixedLossScale tf.compat.v1.mixed\_precision.FixedLossScale
============================================
Loss scale with a fixed value.
Inherits From: [`LossScale`](lossscale)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.mixed_precision.experimental.FixedLossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/FixedLossScale), [`tf.compat.v1.train.experimental.FixedLossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/FixedLossScale)
```
tf.compat.v1.mixed_precision.FixedLossScale(
loss_scale_value
)
```
The loss scale is not updated for the lifetime of instances of this class. A given instance of this class always returns the same number when called.
| Args |
| `loss_scale_value` | A Python float. Its ideal value varies depending on models to run. Choosing a too small loss\_scale might affect model quality; a too big loss\_scale might cause inf or nan. There is no single right loss\_scale to apply. There is no harm choosing a relatively big number as long as no nan or inf is encountered in training. |
| Raises |
| `ValueError` | If loss\_scale\_value is less than 1. |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L195-L198)
```
@classmethod
from_config(
config
)
```
Creates the LossScale from its config.
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L256-L257)
```
get_config()
```
Returns the config of this loss scale.
### `update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L249-L251)
```
update(
grads
)
```
Updates the value of the loss scale.
The loss scale will be potentially updated, based on the value of `grads`. The tensor returned by calling this class is only updated when this function is evaluated.
In eager mode, this directly updates the loss scale, so that calling `__call__` will return the newly updated loss scale. In graph mode, this returns an op that, when evaluated, updates the loss scale.
This function also returns a `should_apply_gradients` bool. If False, gradients should not be applied to the variables that step, as nonfinite gradients were found, and the loss scale has been be updated to reduce the chance of finding nonfinite gradients in the next step. Some loss scale classes will always return True, as they cannot adjust themselves in response to nonfinite gradients.
When a DistributionStrategy is used, this function may only be called in a cross-replica context.
| Args |
| `grads` | A nested structure of unscaled gradients, each which is the gradient of the loss with respect to a weight. The gradients should have already been divided by the loss scale being before passed to this function. 'None' gradients are accepted, and are ignored. |
| Returns |
| `update_op` | In eager mode, None. In graph mode, an op to update the loss scale. |
| `should_apply_gradients` | Either a bool or a scalar boolean tensor. If False, the caller should skip applying `grads` to the variables this step. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L246-L247)
```
__call__()
```
Returns the current loss scale as a scalar `float32` tensor.
tensorflow tf.compat.v1.mixed_precision.disable_mixed_precision_graph_rewrite tf.compat.v1.mixed\_precision.disable\_mixed\_precision\_graph\_rewrite
=======================================================================
Disables the mixed precision graph rewrite.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.experimental.disable_mixed_precision_graph_rewrite`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/disable_mixed_precision_graph_rewrite)
```
tf.compat.v1.mixed_precision.disable_mixed_precision_graph_rewrite()
```
After this is called, the mixed precision graph rewrite will no longer run for new Sessions, and so float32 operations will no longer be converted to float16 in such Sessions. However, any existing Sessions will continue to have the graph rewrite enabled if they were created after `enable_mixed_precision_graph_rewrite` was called but before `disable_mixed_precision_graph_rewrite` was called.
This does not undo the effects of loss scaling. Any optimizers wrapped with a LossScaleOptimizer will continue to do loss scaling, although this loss scaling will no longer be useful if the optimizer is used in new Sessions, as the graph rewrite no longer converts the graph to use float16.
This function is useful for unit testing. A unit tests can test using the mixed precision graph rewrite, then disable it so future unit tests continue using float32. If this is done, unit tests should not share a single session, as `enable_mixed_precision_graph_rewrite` and `disable_mixed_precision_graph_rewrite` have no effect on existing sessions.
tensorflow tf.compat.v1.mixed_precision.DynamicLossScale tf.compat.v1.mixed\_precision.DynamicLossScale
==============================================
Loss scale that dynamically adjusts itself.
Inherits From: [`LossScale`](lossscale)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.mixed_precision.experimental.DynamicLossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/DynamicLossScale), [`tf.compat.v1.train.experimental.DynamicLossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/DynamicLossScale)
```
tf.compat.v1.mixed_precision.DynamicLossScale(
initial_loss_scale=(2 ** 15), increment_period=2000, multiplier=2.0
)
```
Dynamic loss scaling works by adjusting the loss scale as training progresses. The goal is to keep the loss scale as high as possible without overflowing the gradients. As long as the gradients do not overflow, raising the loss scale never hurts.
The algorithm starts by setting the loss scale to an initial value. Every N steps that the gradients are finite, the loss scale is increased by some factor. However, if a NaN or Inf gradient is found, the gradients for that step are not applied, and the loss scale is decreased by the factor. This process tends to keep the loss scale as high as possible without gradients overflowing.
| Args |
| `initial_loss_scale` | A Python float. The loss scale to use at the beginning. It's better to start this at a very high number, because a loss scale that is too high gets lowered far more quickly than a loss scale that is too low gets raised. The default is 2 \*\* 15, which is approximately half the maximum float16 value. |
| `increment_period` | Increases loss scale every `increment_period` consecutive steps that finite gradients are encountered. If a nonfinite gradient is encountered, the count is reset back to zero. |
| `multiplier` | The multiplier to use when increasing or decreasing the loss scale. |
| Attributes |
| `increment_period` | |
| `initial_loss_scale` | |
| `multiplier` | |
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L195-L198)
```
@classmethod
from_config(
config
)
```
Creates the LossScale from its config.
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L428-L433)
```
get_config()
```
Returns the config of this loss scale.
### `update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L368-L415)
```
update(
grads
)
```
Updates loss scale based on if gradients are finite in current step.
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L365-L366)
```
__call__()
```
Returns the current loss scale as a scalar `float32` tensor.
tensorflow Module: tf.compat.v1.mixed_precision.experimental Module: tf.compat.v1.mixed\_precision.experimental
==================================================
Public API for tf.mixed\_precision.experimental namespace.
Classes
-------
[`class DynamicLossScale`](dynamiclossscale): Loss scale that dynamically adjusts itself.
[`class FixedLossScale`](fixedlossscale): Loss scale with a fixed value.
[`class LossScale`](lossscale): Base class for all TF1 loss scales.
tensorflow tf.compat.v1.mixed_precision.LossScale tf.compat.v1.mixed\_precision.LossScale
=======================================
Base class for all TF1 loss scales.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.mixed_precision.experimental.LossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/LossScale), [`tf.compat.v1.train.experimental.LossScale`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/LossScale)
```
tf.compat.v1.mixed_precision.LossScale()
```
This is an abstract base class, so you cannot instantiate it directly. Instead, use one of its concrete subclasses:
* [`tf.compat.v1.mixed_precision.DynamicLossScale`](dynamiclossscale)
* [`tf.compat.v1.mixed_precision.FixedLossScale`](fixedlossscale)
Loss scaling is a process that multiplies the loss by a multiplier called the loss scale, and divides each gradient by the same multiplier. The pseudocode for this process is:
```
loss = ...
loss *= loss_scale
grads = gradients(loss, vars)
grads /= loss_scale
```
Mathematically, loss scaling has no effect, but can help avoid numerical underflow in intermediate gradients when float16 tensors are used for mixed precision training. By multiplying the loss, each intermediate gradient will have the same multiplier applied.
Instances of this class represent a loss scale. Calling instances of this class returns the loss scale as a scalar float32 tensor, while method `update()` updates the loss scale depending on the values of the gradients. Optimizers use instances of this class to scale loss and gradients.
In most functions that accept a LossScale, you can also pass an int (such as
8) to create a `FixedLossScale` or the string `"dynamic"` to create a dynamic loss scale.
Methods
-------
### `from_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L195-L198)
```
@classmethod
from_config(
config
)
```
Creates the LossScale from its config.
### `get_config`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L190-L193)
```
@abc.abstractmethod
get_config()
```
Returns the config of this loss scale.
### `update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L87-L122)
```
@abc.abstractmethod
update(
grads
)
```
Updates the value of the loss scale.
The loss scale will be potentially updated, based on the value of `grads`. The tensor returned by calling this class is only updated when this function is evaluated.
In eager mode, this directly updates the loss scale, so that calling `__call__` will return the newly updated loss scale. In graph mode, this returns an op that, when evaluated, updates the loss scale.
This function also returns a `should_apply_gradients` bool. If False, gradients should not be applied to the variables that step, as nonfinite gradients were found, and the loss scale has been be updated to reduce the chance of finding nonfinite gradients in the next step. Some loss scale classes will always return True, as they cannot adjust themselves in response to nonfinite gradients.
When a DistributionStrategy is used, this function may only be called in a cross-replica context.
| Args |
| `grads` | A nested structure of unscaled gradients, each which is the gradient of the loss with respect to a weight. The gradients should have already been divided by the loss scale being before passed to this function. 'None' gradients are accepted, and are ignored. |
| Returns |
| `update_op` | In eager mode, None. In graph mode, an op to update the loss scale. |
| `should_apply_gradients` | Either a bool or a scalar boolean tensor. If False, the caller should skip applying `grads` to the variables this step. |
### `__call__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale.py#L82-L85)
```
@abc.abstractmethod
__call__()
```
Returns the current loss scale as a scalar `float32` tensor.
| programming_docs |
tensorflow tf.compat.v1.mixed_precision.MixedPrecisionLossScaleOptimizer tf.compat.v1.mixed\_precision.MixedPrecisionLossScaleOptimizer
==============================================================
An optimizer that applies loss scaling.
Inherits From: [`Optimizer`](../train/optimizer)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.experimental.MixedPrecisionLossScaleOptimizer`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/mixed_precision/MixedPrecisionLossScaleOptimizer)
```
tf.compat.v1.mixed_precision.MixedPrecisionLossScaleOptimizer(
opt, loss_scale
)
```
Loss scaling is a process that multiplies the loss by a multiplier called the loss scale, and divides each gradient by the same multiplier. The pseudocode for this process is:
```
loss = ...
loss *= loss_scale
grads = gradients(loss, vars)
grads /= loss_scale
```
Mathematically, loss scaling has no effect, but can help avoid numerical underflow in intermediate gradients when float16 tensors are used for mixed precision training. By multiplying the loss, each intermediate gradient will have the same multiplier applied.
The loss scale can either be a fixed constant, chosen by the user, or be dynamically determined. Dynamically determining the loss scale is convenient as a loss scale does not have to be explicitly chosen. However it reduces performance.
This optimizer wraps another optimizer and applies loss scaling to it via a `LossScale`. Loss scaling is applied whenever gradients are computed, such as through `minimize()`.
| 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. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale_optimizer.py#L153-L186)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that conditionally applies gradients if all gradient values are finite. Otherwise no update is performed (nor is `global_step` incremented).
| 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 conditionally applies the specified gradients. If `global_step` was not None, that operation also increments `global_step`. |
| Raises |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale_optimizer.py#L80-L126)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=optimizer.Optimizer.GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
This adjusts the dynamic range of the gradient evaluation by scaling up the `loss` value. The gradient values are then scaled back down by the reciprocal of the loss scale. This is useful in reduced precision training where small gradient values would otherwise underflow the representable range.
| Args |
| `loss` | A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. |
| `var_list` | Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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`. |
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/experimental/loss_scale_optimizer.py#L248-L251)
```
variables()
```
Returns the variables of the Optimizer.
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.NameAttrList.AttrEntry tf.compat.v1.NameAttrList.AttrEntry
===================================
A ProtocolMessage
| Attributes |
| `key` | `string key` |
| `value` | `AttrValue value` |
tensorflow tf.compat.v1.lookup.StaticVocabularyTable tf.compat.v1.lookup.StaticVocabularyTable
=========================================
String to Id table that assigns out-of-vocabulary keys to hash buckets.
Inherits From: [`StaticVocabularyTable`](../../../lookup/staticvocabularytable), [`TrackableResource`](../../../saved_model/experimental/trackableresource)
```
tf.compat.v1.lookup.StaticVocabularyTable(
initializer,
num_oov_buckets,
lookup_key_dtype=None,
name=None,
experimental_is_anonymous=False
)
```
For example, if an instance of `StaticVocabularyTable` is initialized with a string-to-id initializer that maps:
```
init = tf.lookup.KeyValueTensorInitializer(
keys=tf.constant(['emerson', 'lake', 'palmer']),
values=tf.constant([0, 1, 2], dtype=tf.int64))
table = tf.lookup.StaticVocabularyTable(
init,
num_oov_buckets=5)
```
The `Vocabulary` object will performs the following mapping:
* `emerson -> 0`
* `lake -> 1`
* `palmer -> 2`
* `<other term> -> bucket_id`, where `bucket_id` will be between `3` and `3 + num_oov_buckets - 1 = 7`, calculated by: `hash(<term>) % num_oov_buckets + vocab_size`
#### If input\_tensor is:
```
input_tensor = tf.constant(["emerson", "lake", "palmer",
"king", "crimson"])
table[input_tensor].numpy()
array([0, 1, 2, 6, 7])
```
If `initializer` is None, only out-of-vocabulary buckets are used.
#### Example usage:
```
num_oov_buckets = 3
vocab = ["emerson", "lake", "palmer", "crimnson"]
import tempfile
f = tempfile.NamedTemporaryFile(delete=False)
f.write('\n'.join(vocab).encode('utf-8'))
f.close()
```
```
init = tf.lookup.TextFileInitializer(
f.name,
key_dtype=tf.string, key_index=tf.lookup.TextFileIndex.WHOLE_LINE,
value_dtype=tf.int64, value_index=tf.lookup.TextFileIndex.LINE_NUMBER)
table = tf.lookup.StaticVocabularyTable(init, num_oov_buckets)
table.lookup(tf.constant(["palmer", "crimnson" , "king",
"tarkus", "black", "moon"])).numpy()
array([2, 3, 5, 6, 6, 4])
```
The hash function used for generating out-of-vocabulary buckets ID is Fingerprint64.
Note that the out-of-vocabulary bucket IDs always range from the table `size` up to `size + num_oov_buckets - 1` regardless of the table values, which could cause unexpected collisions:
```
init = tf.lookup.KeyValueTensorInitializer(
keys=tf.constant(["emerson", "lake", "palmer"]),
values=tf.constant([1, 2, 3], dtype=tf.int64))
table = tf.lookup.StaticVocabularyTable(
init,
num_oov_buckets=1)
input_tensor = tf.constant(["emerson", "lake", "palmer", "king"])
table[input_tensor].numpy()
array([1, 2, 3, 3])
```
| Args |
| `initializer` | A `TableInitializerBase` object that contains the data used to initialize the table. If None, then we only use out-of-vocab buckets. |
| `num_oov_buckets` | Number of buckets to use for out-of-vocabulary keys. Must be greater than zero. If out-of-vocab buckets are not required, use `StaticHashTable` instead. |
| `lookup_key_dtype` | Data type of keys passed to `lookup`. Defaults to `initializer.key_dtype` if `initializer` is specified, otherwise [`tf.string`](../../../../tf#string). Must be string or integer, and must be castable to `initializer.key_dtype`. |
| `name` | A name for the operation (optional). |
| `experimental_is_anonymous` | Whether to use anonymous mode for the table (default is False). In anonymous mode, the table resource can only be accessed via a resource handle. It can't be looked up by a name. When all resource handles pointing to that resource are gone, the resource will be deleted automatically. |
| Raises |
| `ValueError` | when `num_oov_buckets` is not positive. |
| `TypeError` | when lookup\_key\_dtype or initializer.key\_dtype are not integer or string. Also when initializer.value\_dtype != int64. |
| Attributes |
| `initializer` | |
| `key_dtype` | The table key dtype. |
| `name` | The name of the table. |
| `resource_handle` | Returns the resource handle associated with this Resource. |
| `value_dtype` | The table value dtype. |
Methods
-------
### `lookup`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L1352-L1395)
```
lookup(
keys, name=None
)
```
Looks up `keys` in the table, outputs the corresponding values.
It assigns out-of-vocabulary keys to buckets based in their hashes.
| Args |
| `keys` | Keys to look up. May be either a `SparseTensor` or dense `Tensor`. |
| `name` | Optional name for the op. |
| Returns |
| A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged, otherwise a dense `Tensor`. |
| Raises |
| `TypeError` | when `keys` doesn't match the table key data type. |
### `size`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L1343-L1350)
```
size(
name=None
)
```
Compute the number of elements in this table.
### `__getitem__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L167-L169)
```
__getitem__(
keys
)
```
Looks up `keys` in a table, outputs the corresponding values.
tensorflow Module: tf.compat.v1.lookup.experimental Module: tf.compat.v1.lookup.experimental
========================================
Public API for tf.lookup.experimental namespace.
Classes
-------
[`class DenseHashTable`](../../../lookup/experimental/densehashtable): A mutable hash table with faster lookups and higher memory usage.
[`class MutableHashTable`](../../../lookup/experimental/mutablehashtable): A generic mutable hash table implementation.
tensorflow tf.compat.v1.lookup.StaticHashTable tf.compat.v1.lookup.StaticHashTable
===================================
A generic hash table that is immutable once initialized.
Inherits From: [`StaticHashTable`](../../../lookup/statichashtable), [`TrackableResource`](../../../saved_model/experimental/trackableresource)
```
tf.compat.v1.lookup.StaticHashTable(
initializer, default_value, name=None, experimental_is_anonymous=False
)
```
When running in graph mode, you must evaluate the tensor returned by `tf.tables_initializer()` before evaluating the tensor returned by this class's `lookup()` method. Example usage in graph mode:
```
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
out = table.lookup(input_tensor)
with tf.Session() as sess:
sess.run(tf.tables_initializer())
print(sess.run(out))
```
Note that in graph mode if you set `experimental_is_anonymous` to `True`, you should only call `Session.run` once, otherwise each `Session.run` will create (and destroy) a new table unrelated to each other, leading to errors such as "Table not initialized". You can do so like this:
```
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1,
experimental_is_anonymous=True)
with tf.control_dependencies([tf.tables_initializer()]):
out = table.lookup(input_tensor)
with tf.Session() as sess:
print(sess.run(out))
```
In eager mode, no special code is needed to initialize the table. Example usage in eager mode:
```
tf.enable_eager_execution()
keys_tensor = tf.constant([1, 2])
vals_tensor = tf.constant([3, 4])
input_tensor = tf.constant([1, 5])
table = tf.lookup.StaticHashTable(
tf.lookup.KeyValueTensorInitializer(keys_tensor, vals_tensor), -1)
print(table.lookup(input_tensor))
```
| Args |
| `initializer` | The table initializer to use. See `HashTable` kernel for supported key and value types. |
| `default_value` | The value to use if a key is missing in the table. |
| `name` | A name for the operation (optional). |
| `experimental_is_anonymous` | Whether to use anonymous mode for the table (default is False). In anonymous mode, the table resource can only be accessed via a resource handle. It can't be looked up by a name. When all resource handles pointing to that resource are gone, the resource will be deleted automatically. |
| Attributes |
| `default_value` | The default value of the table. |
| `initializer` | |
| `key_dtype` | The table key dtype. |
| `name` | The name of the table. |
| `resource_handle` | Returns the resource handle associated with this Resource. |
| `value_dtype` | The table value dtype. |
Methods
-------
### `export`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L371-L387)
```
export(
name=None
)
```
Returns tensors of all keys and values in the table.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A pair of tensors with the first tensor containing all keys and the second tensors containing all values in the table. |
### `lookup`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L225-L264)
```
lookup(
keys, name=None
)
```
Looks up `keys` in a table, outputs the corresponding values.
The `default_value` is used for keys not present in the table.
| Args |
| `keys` | Keys to look up. May be either a `SparseTensor` or dense `Tensor`. |
| `name` | A name for the operation (optional). |
| Returns |
| A `SparseTensor` if keys are sparse, a `RaggedTensor` if keys are ragged, otherwise a dense `Tensor`. |
| Raises |
| `TypeError` | when `keys` or `default_value` doesn't match the table data types. |
### `size`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L213-L223)
```
size(
name=None
)
```
Compute the number of elements in this table.
| Args |
| `name` | A name for the operation (optional). |
| Returns |
| A scalar tensor containing the number of elements in this table. |
### `__getitem__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/ops/lookup_ops.py#L167-L169)
```
__getitem__(
keys
)
```
Looks up `keys` in a table, outputs the corresponding values.
tensorflow tf.compat.v1.math.in_top_k tf.compat.v1.math.in\_top\_k
============================
Says whether the targets are in the top `K` predictions.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.nn.in_top_k`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/math/in_top_k)
```
tf.compat.v1.math.in_top_k(
predictions, targets, k, name=None
)
```
This outputs a `batch_size` bool array, an entry `out[i]` is `true` if the prediction for the target class is finite (not inf, -inf, or nan) and among the top `k` predictions among all predictions for example `i`. Note that the behavior of `InTopK` differs from the `TopK` op in its handling of ties; if multiple classes have the same prediction value and straddle the top-`k` boundary, all of those classes are considered to be in the top `k`.
More formally, let
\(predictions\_i\) be the predictions for all classes for example `i`, \(targets\_i\) be the target class for example `i`, \(out\_i\) be the output for example `i`,
\[out\_i = predictions\_{i, targets\_i} \in TopKIncludingTies(predictions\_i)\]
| Args |
| `predictions` | A `Tensor` of type `float32`. A `batch_size` x `classes` tensor. |
| `targets` | A `Tensor`. Must be one of the following types: `int32`, `int64`. A `batch_size` vector of class ids. |
| `k` | An `int`. Number of top elements to look at for computing precision. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `bool`. Computed Precision at `k` as a `bool Tensor`. |
| programming_docs |
tensorflow tf.compat.v1.math.softmax tf.compat.v1.math.softmax
=========================
Computes softmax activations.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.nn.softmax`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/math/softmax)
```
tf.compat.v1.math.softmax(
logits, axis=None, name=None, dim=None
)
```
Used for multi-class predictions. The sum of all outputs generated by softmax is 1.
This function performs the equivalent of
```
softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis, keepdims=True)
```
Example usage:
```
softmax = tf.nn.softmax([-1, 0., 1.])
softmax
<tf.Tensor: shape=(3,), dtype=float32,
numpy=array([0.09003057, 0.24472848, 0.66524094], dtype=float32)>
sum(softmax)
<tf.Tensor: shape=(), dtype=float32, numpy=1.0>
```
| Args |
| `logits` | A non-empty `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. |
| `axis` | The dimension softmax would be performed on. The default is -1 which indicates the last dimension. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor`. Has the same type and shape as `logits`. |
| Raises |
| `InvalidArgumentError` | if `logits` is empty or `axis` is beyond the last dimension of `logits`. |
tensorflow Module: tf.compat.v1.math.special Module: tf.compat.v1.math.special
=================================
Public API for tf.math.special namespace.
Functions
---------
[`bessel_i0(...)`](../../../math/bessel_i0): Computes the Bessel i0 function of `x` element-wise.
[`bessel_i0e(...)`](../../../math/bessel_i0e): Computes the Bessel i0e function of `x` element-wise.
[`bessel_i1(...)`](../../../math/bessel_i1): Computes the Bessel i1 function of `x` element-wise.
[`bessel_i1e(...)`](../../../math/bessel_i1e): Computes the Bessel i1e function of `x` element-wise.
[`bessel_j0(...)`](../../../math/special/bessel_j0): Computes the Bessel j0 function of `x` element-wise.
[`bessel_j1(...)`](../../../math/special/bessel_j1): Computes the Bessel j1 function of `x` element-wise.
[`bessel_k0(...)`](../../../math/special/bessel_k0): Computes the Bessel k0 function of `x` element-wise.
[`bessel_k0e(...)`](../../../math/special/bessel_k0e): Computes the Bessel k0e function of `x` element-wise.
[`bessel_k1(...)`](../../../math/special/bessel_k1): Computes the Bessel k1 function of `x` element-wise.
[`bessel_k1e(...)`](../../../math/special/bessel_k1e): Computes the Bessel k1e function of `x` element-wise.
[`bessel_y0(...)`](../../../math/special/bessel_y0): Computes the Bessel y0 function of `x` element-wise.
[`bessel_y1(...)`](../../../math/special/bessel_y1): Computes the Bessel y1 function of `x` element-wise.
[`dawsn(...)`](../../../math/special/dawsn): Computes Dawson's integral of `x` element-wise.
[`expint(...)`](../../../math/special/expint): Computes the Exponential integral of `x` element-wise.
[`fresnel_cos(...)`](../../../math/special/fresnel_cos): Computes Fresnel's cosine integral of `x` element-wise.
[`fresnel_sin(...)`](../../../math/special/fresnel_sin): Computes Fresnel's sine integral of `x` element-wise.
[`spence(...)`](../../../math/special/spence): Computes Spence's integral of `x` element-wise.
tensorflow tf.compat.v1.math.log_softmax tf.compat.v1.math.log\_softmax
==============================
Computes log softmax activations. (deprecated arguments)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.nn.log_softmax`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/math/log_softmax)
```
tf.compat.v1.math.log_softmax(
logits, axis=None, name=None, dim=None
)
```
For each batch `i` and class `j` we have
```
logsoftmax = logits - log(reduce_sum(exp(logits), axis))
```
| Args |
| `logits` | A non-empty `Tensor`. Must be one of the following types: `half`, `float32`, `float64`. |
| `axis` | The dimension softmax would be performed on. The default is -1 which indicates the last dimension. |
| `name` | A name for the operation (optional). |
| `dim` | Deprecated alias for `axis`. |
| Returns |
| A `Tensor`. Has the same type as `logits`. Same shape as `logits`. |
| Raises |
| `InvalidArgumentError` | if `logits` is empty or `axis` is beyond the last dimension of `logits`. |
tensorflow tf.compat.v1.RunOptions.Experimental tf.compat.v1.RunOptions.Experimental
====================================
A ProtocolMessage
| Attributes |
| `collective_graph_key` | `int64 collective_graph_key` |
| `run_handler_pool_options` | `RunHandlerPoolOptions run_handler_pool_options` |
| `use_run_handler_pool` | `bool use_run_handler_pool` |
Child Classes
-------------
[`class RunHandlerPoolOptions`](experimental/runhandlerpooloptions)
tensorflow tf.compat.v1.RunOptions.Experimental.RunHandlerPoolOptions tf.compat.v1.RunOptions.Experimental.RunHandlerPoolOptions
==========================================================
A ProtocolMessage
| Attributes |
| `priority` | `int64 priority` |
tensorflow tf.compat.v1.image.resize_nearest_neighbor tf.compat.v1.image.resize\_nearest\_neighbor
============================================
```
tf.compat.v1.image.resize_nearest_neighbor(
images, size, align_corners=False, name=None, half_pixel_centers=False
)
```
tensorflow tf.compat.v1.image.ResizeMethod tf.compat.v1.image.ResizeMethod
===============================
See [`v1.image.resize`](resize) for details.
| Class Variables |
| AREA | `3` |
| BICUBIC | `2` |
| BILINEAR | `0` |
| NEAREST\_NEIGHBOR | `1` |
tensorflow tf.compat.v1.image.resize_image_with_pad tf.compat.v1.image.resize\_image\_with\_pad
===========================================
Resizes and pads an image to a target width and height.
```
tf.compat.v1.image.resize_image_with_pad(
image,
target_height,
target_width,
method=ResizeMethodV1.BILINEAR,
align_corners=False
)
```
Resizes an image to a target width and height by keeping the aspect ratio the same without distortion. If the target dimensions don't match the image dimensions, the image is resized and then padded with zeroes to match requested dimensions.
| Args |
| `image` | 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor of shape `[height, width, channels]`. |
| `target_height` | Target height. |
| `target_width` | Target width. |
| `method` | Method to use for resizing image. See `resize_images()` |
| `align_corners` | bool. If True, the centers of the 4 corner pixels of the input and output tensors are aligned, preserving the values at the corner pixels. Defaults to `False`. |
| Raises |
| `ValueError` | if `target_height` or `target_width` are zero or negative. |
| Returns |
| Resized and padded image. If `images` was 4-D, a 4-D float Tensor of shape `[batch, new_height, new_width, channels]`. If `images` was 3-D, a 3-D float Tensor of shape `[new_height, new_width, channels]`. |
tensorflow tf.compat.v1.image.resize tf.compat.v1.image.resize
=========================
Resize `images` to `size` using the specified `method`.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.image.resize_images`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/image/resize)
```
tf.compat.v1.image.resize(
images,
size,
method=ResizeMethodV1.BILINEAR,
align_corners=False,
preserve_aspect_ratio=False,
name=None
)
```
Resized images will be distorted if their original aspect ratio is not the same as `size`. To avoid distortions see [`tf.image.resize_with_pad`](../../../image/resize_with_pad) or [`tf.image.resize_with_crop_or_pad`](../../../image/resize_with_crop_or_pad).
The `method` can be one of:
* **[`tf.image.ResizeMethod.BILINEAR`](../../../image/resizemethod#BILINEAR)**: [Bilinear interpolation.](https://en.wikipedia.org/wiki/Bilinear_interpolation)
* **[`tf.image.ResizeMethod.NEAREST_NEIGHBOR`](../../../image/resizemethod#NEAREST_NEIGHBOR)**: [Nearest neighbor interpolation.](https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation)
* **[`tf.image.ResizeMethod.BICUBIC`](../../../image/resizemethod#BICUBIC)**: [Bicubic interpolation.](https://en.wikipedia.org/wiki/Bicubic_interpolation)
* **[`tf.image.ResizeMethod.AREA`](../../../image/resizemethod#AREA)**: Area interpolation.
The return value has the same type as `images` if `method` is [`tf.image.ResizeMethod.NEAREST_NEIGHBOR`](../../../image/resizemethod#NEAREST_NEIGHBOR). It will also have the same type as `images` if the size of `images` can be statically determined to be the same as `size`, because `images` is returned in this case. Otherwise, the return value has type `float32`.
| Args |
| `images` | 4-D Tensor of shape `[batch, height, width, channels]` or 3-D Tensor of shape `[height, width, channels]`. |
| `size` | A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The new size for the images. |
| `method` | ResizeMethod. Defaults to [`tf.image.ResizeMethod.BILINEAR`](../../../image/resizemethod#BILINEAR). |
| `align_corners` | bool. If True, the centers of the 4 corner pixels of the input and output tensors are aligned, preserving the values at the corner pixels. Defaults to `False`. |
| `preserve_aspect_ratio` | Whether to preserve the aspect ratio. If this is set, then `images` will be resized to a size that fits in `size` while preserving the aspect ratio of the original image. Scales up the image if `size` is bigger than the current size of the `image`. Defaults to False. |
| `name` | A name for this operation (optional). |
| Raises |
| `ValueError` | if the shape of `images` is incompatible with the shape arguments to this function |
| `ValueError` | if `size` has invalid shape or type. |
| `ValueError` | if an unsupported resize method is specified. |
| Returns |
| If `images` was 4-D, a 4-D float Tensor of shape `[batch, new_height, new_width, channels]`. If `images` was 3-D, a 3-D float Tensor of shape `[new_height, new_width, channels]`. |
tensorflow tf.compat.v1.image.crop_and_resize tf.compat.v1.image.crop\_and\_resize
====================================
Extracts crops from the input image tensor and resizes them.
```
tf.compat.v1.image.crop_and_resize(
image,
boxes,
box_ind=None,
crop_size=None,
method='bilinear',
extrapolation_value=0,
name=None,
box_indices=None
)
```
Extracts crops from the input image tensor and resizes them using bilinear sampling or nearest neighbor sampling (possibly with aspect ratio change) to a common output size specified by `crop_size`. This is more general than the `crop_to_bounding_box` op which extracts a fixed size slice from the input image and does not allow resizing or aspect ratio change.
Returns a tensor with `crops` from the input `image` at positions defined at the bounding box locations in `boxes`. The cropped boxes are all resized (with bilinear or nearest neighbor interpolation) to a fixed `size = [crop_height, crop_width]`. The result is a 4-D tensor `[num_boxes, crop_height, crop_width, depth]`. The resizing is corner aligned. In particular, if `boxes = [[0, 0, 1, 1]]`, the method will give identical results to using `tf.image.resize_bilinear()` or `tf.image.resize_nearest_neighbor()`(depends on the `method` argument) with `align_corners=True`.
| Args |
| `image` | A `Tensor`. Must be one of the following types: `uint8`, `uint16`, `int8`, `int16`, `int32`, `int64`, `half`, `float32`, `float64`. A 4-D tensor of shape `[batch, image_height, image_width, depth]`. Both `image_height` and `image_width` need to be positive. |
| `boxes` | A `Tensor` of type `float32`. A 2-D tensor of shape `[num_boxes, 4]`. The `i`-th row of the tensor specifies the coordinates of a box in the `box_ind[i]` image and is specified in normalized coordinates `[y1, x1, y2, x2]`. A normalized coordinate value of `y` is mapped to the image coordinate at `y * (image_height - 1)`, so as the `[0, 1]` interval of normalized image height is mapped to `[0, image_height - 1]` in image height coordinates. We do allow `y1` > `y2`, in which case the sampled crop is an up-down flipped version of the original image. The width dimension is treated similarly. Normalized coordinates outside the `[0, 1]` range are allowed, in which case we use `extrapolation_value` to extrapolate the input image values. |
| `box_ind` | A `Tensor` of type `int32`. A 1-D tensor of shape `[num_boxes]` with int32 values in `[0, batch)`. The value of `box_ind[i]` specifies the image that the `i`-th box refers to. |
| `crop_size` | A `Tensor` of type `int32`. A 1-D tensor of 2 elements, `size = [crop_height, crop_width]`. All cropped image patches are resized to this size. The aspect ratio of the image content is not preserved. Both `crop_height` and `crop_width` need to be positive. |
| `method` | An optional `string` from: `"bilinear", "nearest"`. Defaults to `"bilinear"`. A string specifying the sampling method for resizing. It can be either `"bilinear"` or `"nearest"` and default to `"bilinear"`. Currently two sampling methods are supported: Bilinear and Nearest Neighbor. |
| `extrapolation_value` | An optional `float`. Defaults to `0`. Value used for extrapolation, when applicable. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.image.resize_bicubic tf.compat.v1.image.resize\_bicubic
==================================
```
tf.compat.v1.image.resize_bicubic(
images, size, align_corners=False, name=None, half_pixel_centers=False
)
```
tensorflow tf.compat.v1.image.extract_glimpse tf.compat.v1.image.extract\_glimpse
===================================
Extracts a glimpse from the input tensor.
```
tf.compat.v1.image.extract_glimpse(
input,
size,
offsets,
centered=True,
normalized=True,
uniform_noise=True,
name=None
)
```
Returns a set of windows called glimpses extracted at location `offsets` from the input tensor. If the windows only partially overlaps the inputs, the non-overlapping areas will be filled with random noise.
The result is a 4-D tensor of shape `[batch_size, glimpse_height, glimpse_width, channels]`. The channels and batch dimensions are the same as that of the input tensor. The height and width of the output windows are specified in the `size` parameter.
The argument `normalized` and `centered` controls how the windows are built:
* If the coordinates are normalized but not centered, 0.0 and 1.0 correspond to the minimum and maximum of each height and width dimension.
* If the coordinates are both normalized and centered, they range from -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper left corner, the lower right corner is located at (1.0, 1.0) and the center is at (0, 0).
* If the coordinates are not normalized they are interpreted as numbers of pixels.
#### Usage Example:
```
x = [[[[0.0],
[1.0],
[2.0]],
[[3.0],
[4.0],
[5.0]],
[[6.0],
[7.0],
[8.0]]]]
tf.compat.v1.image.extract_glimpse(x, size=(2, 2), offsets=[[1, 1]],
centered=False, normalized=False)
<tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=
array([[[[0.],
[1.]],
[[3.],
[4.]]]], dtype=float32)>
```
| Args |
| `input` | A `Tensor` of type `float32`. A 4-D float tensor of shape `[batch_size, height, width, channels]`. |
| `size` | A `Tensor` of type `int32`. A 1-D tensor of 2 elements containing the size of the glimpses to extract. The glimpse height must be specified first, following by the glimpse width. |
| `offsets` | A `Tensor` of type `float32`. A 2-D integer tensor of shape `[batch_size, 2]` containing the y, x locations of the center of each window. |
| `centered` | An optional `bool`. Defaults to `True`. indicates if the offset coordinates are centered relative to the image, in which case the (0, 0) offset is relative to the center of the input images. If false, the (0,0) offset corresponds to the upper left corner of the input images. |
| `normalized` | An optional `bool`. Defaults to `True`. indicates if the offset coordinates are normalized. |
| `uniform_noise` | An optional `bool`. Defaults to `True`. indicates if the noise should be generated using a uniform distribution or a Gaussian distribution. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.image.resize_bilinear tf.compat.v1.image.resize\_bilinear
===================================
```
tf.compat.v1.image.resize_bilinear(
images, size, align_corners=False, name=None, half_pixel_centers=False
)
```
tensorflow tf.compat.v1.image.sample_distorted_bounding_box tf.compat.v1.image.sample\_distorted\_bounding\_box
===================================================
Generate a single randomly distorted bounding box for an image. (deprecated)
```
tf.compat.v1.image.sample_distorted_bounding_box(
image_size,
bounding_boxes,
seed=None,
seed2=None,
min_object_covered=0.1,
aspect_ratio_range=None,
area_range=None,
max_attempts=None,
use_image_if_no_bounding_boxes=None,
name=None
)
```
Bounding box annotations are often supplied in addition to ground-truth labels in image recognition or object localization tasks. A common technique for training such a system is to randomly distort an image while preserving its content, i.e. *data augmentation*. This Op outputs a randomly distorted localization of an object, i.e. bounding box, given an `image_size`, `bounding_boxes` and a series of constraints.
The output of this Op is a single bounding box that may be used to crop the original image. The output is returned as 3 tensors: `begin`, `size` and `bboxes`. The first 2 tensors can be fed directly into [`tf.slice`](../../../slice) to crop the image. The latter may be supplied to [`tf.image.draw_bounding_boxes`](../../../image/draw_bounding_boxes) to visualize what the bounding box looks like.
Bounding boxes are supplied and returned as `[y_min, x_min, y_max, x_max]`. The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and height of the underlying image.
For example,
```
# Generate a single distorted bounding box.
begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(
tf.shape(image),
bounding_boxes=bounding_boxes,
min_object_covered=0.1)
# Draw the bounding box in an image summary.
image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),
bbox_for_draw)
tf.compat.v1.summary.image('images_with_box', image_with_box)
# Employ the bounding box to distort the image.
distorted_image = tf.slice(image, begin, size)
```
Note that if no bounding box information is available, setting `use_image_if_no_bounding_boxes = True` will assume there is a single implicit bounding box covering the whole image. If `use_image_if_no_bounding_boxes` is false and no bounding boxes are supplied, an error is raised.
| Args |
| `image_size` | A `Tensor`. Must be one of the following types: `uint8`, `int8`, `int16`, `int32`, `int64`. 1-D, containing `[height, width, channels]`. |
| `bounding_boxes` | A `Tensor` of type `float32`. 3-D with shape `[batch, N, 4]` describing the N bounding boxes associated with the image. |
| `seed` | An optional `int`. Defaults to `0`. If either `seed` or `seed2` are set to non-zero, the random number generator is seeded by the given `seed`. Otherwise, it is seeded by a random seed. |
| `seed2` | An optional `int`. Defaults to `0`. A second seed to avoid seed collision. |
| `min_object_covered` | A Tensor of type `float32`. Defaults to `0.1`. The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied. |
| `aspect_ratio_range` | An optional list of `floats`. Defaults to `[0.75, 1.33]`. The cropped area of the image must have an aspect ratio = width / height within this range. |
| `area_range` | An optional list of `floats`. Defaults to `[0.05, 1]`. The cropped area of the image must contain a fraction of the supplied image within this range. |
| `max_attempts` | An optional `int`. Defaults to `100`. Number of attempts at generating a cropped region of the image of the specified constraints. After `max_attempts` failures, return the entire image. |
| `use_image_if_no_bounding_boxes` | An optional `bool`. Defaults to `False`. Controls behavior if no bounding boxes supplied. If true, assume an implicit bounding box covering the whole input. If false, raise an error. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (begin, size, bboxes). |
| `begin` | A `Tensor`. Has the same type as `image_size`. 1-D, containing `[offset_height, offset_width, 0]`. Provide as input to [`tf.slice`](../../../slice). |
| `size` | A `Tensor`. Has the same type as `image_size`. 1-D, containing `[target_height, target_width, -1]`. Provide as input to [`tf.slice`](../../../slice). |
| `bboxes` | A `Tensor` of type `float32`. 3-D with shape `[1, 1, 4]` containing the distorted bounding box. Provide as input to [`tf.image.draw_bounding_boxes`](../../../image/draw_bounding_boxes). |
| Raises |
| `ValueError` | If no seed is specified and op determinism is enabled. |
| programming_docs |
tensorflow tf.compat.v1.image.resize_area tf.compat.v1.image.resize\_area
===============================
Resize `images` to `size` using area interpolation.
```
tf.compat.v1.image.resize_area(
images, size, align_corners=False, name=None
)
```
Input images can be of different types but output images are always float.
The range of pixel values for the output image might be slightly different from the range for the input image because of limited numerical precision. To guarantee an output range, for example `[0.0, 1.0]`, apply [`tf.clip_by_value`](../../../clip_by_value) to the output.
Each output pixel is computed by first transforming the pixel's footprint into the input tensor and then averaging the pixels that intersect the footprint. An input pixel's contribution to the average is weighted by the fraction of its area that intersects the footprint. This is the same as OpenCV's INTER\_AREA.
| Args |
| `images` | A `Tensor`. Must be one of the following types: `int8`, `uint8`, `int16`, `uint16`, `int32`, `int64`, `half`, `float32`, `float64`, `bfloat16`. 4-D with shape `[batch, height, width, channels]`. |
| `size` | A 1-D int32 Tensor of 2 elements: `new_height, new_width`. The new size for the images. |
| `align_corners` | An optional `bool`. Defaults to `False`. If true, the centers of the 4 corner pixels of the input and output tensors are aligned, preserving the values at the corner pixels. Defaults to false. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `float32`. |
tensorflow tf.compat.v1.image.draw_bounding_boxes tf.compat.v1.image.draw\_bounding\_boxes
========================================
Draw bounding boxes on a batch of images.
```
tf.compat.v1.image.draw_bounding_boxes(
images, boxes, name=None, colors=None
)
```
Outputs a copy of `images` but draws on top of the pixels zero or more bounding boxes specified by the locations in `boxes`. The coordinates of the each bounding box in `boxes` are encoded as `[y_min, x_min, y_max, x_max]`. The bounding box coordinates are floats in `[0.0, 1.0]` relative to the width and the height of the underlying image.
For example, if an image is 100 x 200 pixels (height x width) and the bounding box is `[0.1, 0.2, 0.5, 0.9]`, the upper-left and bottom-right coordinates of the bounding box will be `(40, 10)` to `(180, 50)` (in (x,y) coordinates).
Parts of the bounding box may fall outside the image.
| Args |
| `images` | A `Tensor`. Must be one of the following types: `float32`, `half`. 4-D with shape `[batch, height, width, depth]`. A batch of images. |
| `boxes` | A `Tensor` of type `float32`. 3-D with shape `[batch, num_bounding_boxes, 4]` containing bounding boxes. |
| `name` | A name for the operation (optional). |
| `colors` | A `Tensor` of type `float32`. 2-D. A list of RGBA colors to cycle through for the boxes. |
| Returns |
| A `Tensor`. Has the same type as `images`. |
#### Usage Example:
```
# create an empty image
img = tf.zeros([1, 3, 3, 3])
# draw a box around the image
box = np.array([0, 0, 1, 1])
boxes = box.reshape([1, 1, 4])
# alternate between red and blue
colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
tf.image.draw_bounding_boxes(img, boxes, colors)
<tf.Tensor: shape=(1, 3, 3, 3), dtype=float32, numpy=
array([[[[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]],
[[1., 0., 0.],
[0., 0., 0.],
[1., 0., 0.]],
[[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]]]], dtype=float32)>
```
tensorflow Module: tf.compat.v1.mlir.experimental Module: tf.compat.v1.mlir.experimental
======================================
Public API for tf.mlir.experimental namespace.
Functions
---------
[`convert_function(...)`](../../../mlir/experimental/convert_function): Import a ConcreteFunction and convert it to a textual MLIR module.
[`convert_graph_def(...)`](../../../mlir/experimental/convert_graph_def): Import a GraphDef and convert it to a textual MLIR module.
tensorflow tf.compat.v1.ConfigProto.Experimental tf.compat.v1.ConfigProto.Experimental
=====================================
A ProtocolMessage
| Attributes |
| `collective_deterministic_sequential_execution` | `bool collective_deterministic_sequential_execution` |
| `collective_group_leader` | `string collective_group_leader` |
| `collective_nccl` | `bool collective_nccl` |
| `coordination_config` | `CoordinationServiceConfig coordination_config` |
| `disable_functional_ops_lowering` | `bool disable_functional_ops_lowering` |
| `disable_output_partition_graphs` | `bool disable_output_partition_graphs` |
| `disable_thread_spinning` | `bool disable_thread_spinning` |
| `enable_mlir_bridge` | `bool enable_mlir_bridge` |
| `enable_mlir_graph_optimization` | `bool enable_mlir_graph_optimization` |
| `executor_type` | `string executor_type` |
| `mlir_bridge_rollout` | `MlirBridgeRollout mlir_bridge_rollout` |
| `optimize_for_static_graph` | `bool optimize_for_static_graph` |
| `recv_buf_max_chunk` | `int32 recv_buf_max_chunk` |
| `session_metadata` | `SessionMetadata session_metadata` |
| `share_cluster_devices_in_session` | `bool share_cluster_devices_in_session` |
| `share_session_state_in_clusterspec_propagation` | `bool share_session_state_in_clusterspec_propagation` |
| `use_numa_affinity` | `bool use_numa_affinity` |
| `use_tfrt` | `bool use_tfrt` |
| `xla_fusion_autotuner_thresh` | `int64 xla_fusion_autotuner_thresh` |
| `xla_prefer_single_graph_cluster` | `bool xla_prefer_single_graph_cluster` |
| Class Variables |
| MLIR\_BRIDGE\_ROLLOUT\_DISABLED | `2` |
| MLIR\_BRIDGE\_ROLLOUT\_ENABLED | `1` |
| MLIR\_BRIDGE\_ROLLOUT\_SAFE\_MODE\_ENABLED | `3` |
| MLIR\_BRIDGE\_ROLLOUT\_SAFE\_MODE\_FALLBACK\_ENABLED | `4` |
| MLIR\_BRIDGE\_ROLLOUT\_UNSPECIFIED | `0` |
| MlirBridgeRollout | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
tensorflow tf.compat.v1.ConfigProto.DeviceCountEntry tf.compat.v1.ConfigProto.DeviceCountEntry
=========================================
A ProtocolMessage
| Attributes |
| `key` | `string key` |
| `value` | `int32 value` |
tensorflow tf.compat.v1.NodeDef.AttrEntry tf.compat.v1.NodeDef.AttrEntry
==============================
A ProtocolMessage
| Attributes |
| `key` | `string key` |
| `value` | `AttrValue value` |
tensorflow tf.compat.v1.NodeDef.ExperimentalDebugInfo tf.compat.v1.NodeDef.ExperimentalDebugInfo
==========================================
A ProtocolMessage
| Attributes |
| `original_func_names` | `repeated string original_func_names` |
| `original_node_names` | `repeated string original_node_names` |
tensorflow tf.compat.v1.gfile.Exists tf.compat.v1.gfile.Exists
=========================
Determines whether a path exists or not.
```
tf.compat.v1.gfile.Exists(
filename
)
```
```
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.exists("/tmp/x")
True
```
You can also specify the URI scheme for selecting a different filesystem:
```
# for a GCS filesystem path:
# tf.io.gfile.exists("gs://bucket/file")
# for a local filesystem:
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.exists("file:///tmp/x")
True
```
This currently returns `True` for existing directories but don't rely on this behavior, especially if you are using cloud filesystems (e.g., GCS, S3, Hadoop):
```
tf.io.gfile.exists("/tmp")
True
```
| Args |
| `path` | string, a path |
| Returns |
| True if the path exists, whether it's a file or a directory. False if the path does not exist and there are no filesystem errors. |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Propagates any errors reported by the FileSystem API. |
tensorflow tf.compat.v1.gfile.Rename tf.compat.v1.gfile.Rename
=========================
Rename or move a file / directory.
```
tf.compat.v1.gfile.Rename(
oldname, newname, overwrite=False
)
```
| Args |
| `oldname` | string, pathname for a file |
| `newname` | string, pathname to which the file needs to be moved |
| `overwrite` | boolean, if false it's an error for `newname` to be occupied by an existing file. |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.Glob tf.compat.v1.gfile.Glob
=======================
Returns a list of files that match the given pattern(s).
```
tf.compat.v1.gfile.Glob(
filename
)
```
| Args |
| `filename` | string or iterable of strings. The glob pattern(s). |
| Returns |
| A list of strings containing filenames that match the given pattern(s). |
| Raises |
* errors.OpError: If there are filesystem / directory listing errors.
* errors.NotFoundError: If pattern to be matched is an invalid directory.
tensorflow tf.compat.v1.gfile.Remove tf.compat.v1.gfile.Remove
=========================
Deletes the file located at 'filename'.
```
tf.compat.v1.gfile.Remove(
filename
)
```
| Args |
| `filename` | string, a filename |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | Propagates any errors reported by the FileSystem API. E.g., `NotFoundError` if the file does not exist. |
tensorflow tf.compat.v1.gfile.DeleteRecursively tf.compat.v1.gfile.DeleteRecursively
====================================
Deletes everything under dirname recursively.
```
tf.compat.v1.gfile.DeleteRecursively(
dirname
)
```
| Args |
| `dirname` | string, a path to a directory |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.Stat tf.compat.v1.gfile.Stat
=======================
Returns file statistics for a given path.
```
tf.compat.v1.gfile.Stat(
filename
)
```
| Args |
| `filename` | string, path to a file |
| Returns |
| FileStatistics struct that contains information about the path |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.IsDirectory tf.compat.v1.gfile.IsDirectory
==============================
Returns whether the path is a directory or not.
```
tf.compat.v1.gfile.IsDirectory(
dirname
)
```
| Args |
| `dirname` | string, path to a potential directory |
| Returns |
| True, if the path is a directory; False otherwise |
tensorflow tf.compat.v1.gfile.MakeDirs tf.compat.v1.gfile.MakeDirs
===========================
Creates a directory and all parent/intermediate directories.
```
tf.compat.v1.gfile.MakeDirs(
dirname
)
```
It succeeds if dirname already exists and is writable.
| Args |
| `dirname` | string, name of the directory to be created |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.ListDirectory tf.compat.v1.gfile.ListDirectory
================================
Returns a list of entries contained within a directory.
```
tf.compat.v1.gfile.ListDirectory(
dirname
)
```
The list is in arbitrary order. It does not contain the special entries "." and "..".
| Args |
| `dirname` | string, path to a directory |
| Returns |
| [filename1, filename2, ... filenameN] as strings |
| Raises |
| errors.NotFoundError if directory doesn't exist |
tensorflow tf.compat.v1.gfile.MkDir tf.compat.v1.gfile.MkDir
========================
Creates a directory with the name `dirname`.
```
tf.compat.v1.gfile.MkDir(
dirname
)
```
| Args |
| `dirname` | string, name of the directory to be created |
Notes: The parent directories need to exist. Use [`tf.io.gfile.makedirs`](../../../io/gfile/makedirs) instead if there is the possibility that the parent dirs don't exist.
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.Copy tf.compat.v1.gfile.Copy
=======================
Copies data from `src` to `dst`.
```
tf.compat.v1.gfile.Copy(
oldpath, newpath, overwrite=False
)
```
```
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.exists("/tmp/x")
True
tf.io.gfile.copy("/tmp/x", "/tmp/y")
tf.io.gfile.exists("/tmp/y")
True
tf.io.gfile.remove("/tmp/y")
```
You can also specify the URI scheme for selecting a different filesystem:
```
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
tf.io.gfile.exists("/tmp/y")
True
tf.io.gfile.remove("/tmp/y")
```
Note that you need to always specify a file name, even if moving into a new directory. This is because some cloud filesystems don't have the concept of a directory.
```
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.mkdir("/tmp/new_dir")
tf.io.gfile.copy("/tmp/x", "/tmp/new_dir/y")
tf.io.gfile.exists("/tmp/new_dir/y")
True
tf.io.gfile.rmtree("/tmp/new_dir")
```
If you want to prevent errors if the path already exists, you can use `overwrite` argument:
```
with open("/tmp/x", "w") as f:
f.write("asdf")
4
tf.io.gfile.copy("/tmp/x", "file:///tmp/y")
tf.io.gfile.copy("/tmp/x", "file:///tmp/y", overwrite=True)
tf.io.gfile.remove("/tmp/y")
```
Note that the above will still result in an error if you try to overwrite a directory with a file.
Note that you cannot copy a directory, only file arguments are supported.
| Args |
| `src` | string, name of the file whose contents need to be copied |
| `dst` | string, name of the file to which to copy to |
| `overwrite` | boolean, if false it's an error for `dst` to be occupied by an existing file. |
| Raises |
| [`errors.OpError`](https://www.tensorflow.org/api_docs/python/tf/errors/OpError) | If the operation fails. |
tensorflow tf.compat.v1.gfile.FastGFile tf.compat.v1.gfile.FastGFile
============================
File I/O wrappers without thread locking.
```
tf.compat.v1.gfile.FastGFile(
name, mode='r'
)
```
Note, that this is somewhat like builtin Python file I/O, but there are semantic differences to make it more efficient for some backing filesystems. For example, a write mode file will not be opened until the first write call (to minimize RPC invocations in network filesystems).
| Attributes |
| `mode` | Returns the mode in which the file was opened. |
| `name` | Returns the file name. |
Methods
-------
### `close`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L221-L240)
```
close()
```
Closes the file.
Should be called for the WritableFile to be flushed.
In general, if you use the context manager pattern, you don't need to call this directly.
```
with tf.io.gfile.GFile("/tmp/x", "w") as f:
f.write("asdf\n")
f.write("qwer\n")
# implicit f.close() at the end of the block
```
For cloud filesystems, forgetting to call `close()` might result in data loss as last write might not have been replicated.
### `flush`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L211-L219)
```
flush()
```
Flushes the Writable file.
This only ensures that the data has made its way out of the process without any guarantees on whether it's written to disk. This means that the data would survive an application crash but not necessarily an OS crash.
### `next`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L208-L209)
```
next()
```
### `read`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L102-L119)
```
read(
n=-1
)
```
Returns the contents of a file as a string.
Starts reading from current position in file.
| Args |
| `n` | Read `n` bytes if `n != -1`. If `n = -1`, reads to end of file. |
| Returns |
| `n` bytes of the file (or whole file) in bytes mode or `n` bytes of the string if in string (regular) mode. |
### `readline`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L165-L168)
```
readline()
```
Reads the next line, keeping \n. At EOF, returns ''.
### `readlines`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L170-L179)
```
readlines()
```
Returns all lines from the file in a list.
### `seek`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L121-L163)
```
seek(
offset=None, whence=0, position=None
)
```
Seeks to the offset in the file. (deprecated arguments)
| Args |
| `offset` | The byte count relative to the whence argument. |
| `whence` | Valid values for whence are: 0: start of the file (default) 1: relative to the current position of the file 2: relative to the end of file. `offset` is usually negative. |
### `seekable`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L242-L244)
```
seekable()
```
Returns True as FileIO supports random access ops of seek()/tell()
### `size`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L93-L95)
```
size()
```
Returns the size of the file.
### `tell`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L181-L189)
```
tell()
```
Returns the current position in the file.
### `write`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L97-L100)
```
write(
file_content
)
```
Writes file\_content to the file. Appends to the end of the file.
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L191-L193)
```
__enter__()
```
Make usable with "with" statement.
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L195-L197)
```
__exit__(
unused_type, unused_value, unused_traceback
)
```
Make usable with "with" statement.
### `__iter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/lib/io/file_io.py#L199-L200)
```
__iter__()
```
tensorflow tf.compat.v1.gfile.Walk tf.compat.v1.gfile.Walk
=======================
Recursive directory tree generator for directories.
```
tf.compat.v1.gfile.Walk(
top, in_order=True
)
```
| Args |
| `top` | string, a Directory name |
| `in_order` | bool, Traverse in order if True, post order if False. Errors that happen while listing directories are ignored. |
| Yields |
| Each yield is a 3-tuple: the pathname of a directory, followed by lists of all its subdirectories and leaf files. That is, each yield looks like: `(dirname, [subdirname, subdirname, ...], [filename, filename, ...])`. Each item is a string. |
tensorflow tf.compat.v1.distribute.Strategy tf.compat.v1.distribute.Strategy
================================
A list of devices with a state & compute distribution policy.
```
tf.compat.v1.distribute.Strategy(
extended
)
```
See [the guide](https://www.tensorflow.org/guide/distribute_strategy) for overview and examples.
>
> **Note:** Not all [`tf.distribute.Strategy`](../../../distribute/strategy) implementations currently support TensorFlow's partitioned variables (where a single variable is split across multiple devices) at this time.
>
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1197-L1312)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow Module: tf.compat.v1.distribute.cluster_resolver Module: tf.compat.v1.distribute.cluster\_resolver
=================================================
Library imports for ClusterResolvers.
This library contains all implementations of ClusterResolvers. ClusterResolvers are a way of specifying cluster information for distributed execution. Built on top of existing `ClusterSpec` framework, ClusterResolvers are a way for TensorFlow to communicate with various cluster management systems (e.g. GCE, AWS, etc...).
Classes
-------
[`class ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver): Abstract class for all implementations of ClusterResolvers.
[`class GCEClusterResolver`](../../../distribute/cluster_resolver/gceclusterresolver): ClusterResolver for Google Compute Engine.
[`class KubernetesClusterResolver`](../../../distribute/cluster_resolver/kubernetesclusterresolver): ClusterResolver for Kubernetes.
[`class SimpleClusterResolver`](../../../distribute/cluster_resolver/simpleclusterresolver): Simple implementation of ClusterResolver that accepts all attributes.
[`class SlurmClusterResolver`](../../../distribute/cluster_resolver/slurmclusterresolver): ClusterResolver for system with Slurm workload manager.
[`class TFConfigClusterResolver`](../../../distribute/cluster_resolver/tfconfigclusterresolver): Implementation of a ClusterResolver which reads the TF\_CONFIG EnvVar.
[`class TPUClusterResolver`](../../../distribute/cluster_resolver/tpuclusterresolver): Cluster Resolver for Google Cloud TPUs.
[`class UnionResolver`](../../../distribute/cluster_resolver/unionresolver): Performs a union on underlying ClusterResolvers.
tensorflow tf.compat.v1.distribute.OneDeviceStrategy tf.compat.v1.distribute.OneDeviceStrategy
=========================================
A distribution strategy for running on a single device.
Inherits From: [`Strategy`](strategy)
```
tf.compat.v1.distribute.OneDeviceStrategy(
device
)
```
Using this strategy will place any variables created in its scope on the specified device. Input distributed through this strategy will be prefetched to the specified device. Moreover, any functions called via `strategy.run` will also be placed on the specified device as well.
Typical usage of this strategy could be testing your code with the tf.distribute.Strategy API before switching to other strategies which actually distribute to multiple devices/machines.
#### For example:
```
tf.enable_eager_execution()
strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0")
with strategy.scope():
v = tf.Variable(1.0)
print(v.device) # /job:localhost/replica:0/task:0/device:GPU:0
def step_fn(x):
return x * 2
result = 0
for i in range(10):
result += strategy.run(step_fn, args=(i,))
print(result) # 90
```
| Args |
| `device` | Device string identifier for the device on which the variables should be placed. See class docs for more details on how the device is used. Examples: "/cpu:0", "/gpu:0", "/device:CPU:0", "/device:GPU:0" |
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1197-L1312)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.distribute.MirroredStrategy tf.compat.v1.distribute.MirroredStrategy
========================================
Synchronous training across multiple replicas on one machine.
Inherits From: [`Strategy`](strategy)
```
tf.compat.v1.distribute.MirroredStrategy(
devices=None, cross_device_ops=None
)
```
This strategy is typically used for training on one machine with multiple GPUs. For TPUs, use [`tf.distribute.TPUStrategy`](../../../distribute/tpustrategy). To use `MirroredStrategy` with multiple workers, please refer to [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy).
For example, a variable created under a `MirroredStrategy` is a `MirroredVariable`. If no devices are specified in the constructor argument of the strategy then it will use all the available GPUs. If no GPUs are found, it will use the available CPUs. Note that TensorFlow treats all CPUs on a machine as a single device, and uses threads internally for parallelism.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
with strategy.scope():
x = tf.Variable(1.)
x
MirroredVariable:{
0: <tf.Variable ... shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable ... shape=() dtype=float32, numpy=1.0>
}
```
While using distribution strategies, all the variable creation should be done within the strategy's scope. This will replicate the variables across all the replicas and keep them in sync using an all-reduce algorithm.
Variables created inside a `MirroredStrategy` which is wrapped with a [`tf.function`](../../../function) are still `MirroredVariables`.
```
x = []
@tf.function # Wrap the function with tf.function.
def create_variable():
if not x:
x.append(tf.Variable(1.))
return x[0]
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
with strategy.scope():
_ = create_variable()
print(x[0])
MirroredVariable:{
0: <tf.Variable ... shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable ... shape=() dtype=float32, numpy=1.0>
}
```
`experimental_distribute_dataset` can be used to distribute the dataset across the replicas when writing your own training loop. If you are using `.fit` and `.compile` methods available in [`tf.keras`](../../../keras), then [`tf.keras`](../../../keras) will handle the distribution for you.
#### For example:
```
my_strategy = tf.distribute.MirroredStrategy()
with my_strategy.scope():
@tf.function
def distribute_train_epoch(dataset):
def replica_fn(input):
# process input and return result
return result
total_result = 0
for x in dataset:
per_replica_result = my_strategy.run(replica_fn, args=(x,))
total_result += my_strategy.reduce(tf.distribute.ReduceOp.SUM,
per_replica_result, axis=None)
return total_result
dist_dataset = my_strategy.experimental_distribute_dataset(dataset)
for _ in range(EPOCHS):
train_result = distribute_train_epoch(dist_dataset)
```
| Args |
| `devices` | a list of device strings such as `['/gpu:0', '/gpu:1']`. If `None`, all available GPUs are used. If no GPUs are found, CPU is used. |
| `cross_device_ops` | optional, a descedant of `CrossDeviceOps`. If this is not set, `NcclAllReduce()` will be used by default. One would customize this if NCCL isn't available or if a special implementation that exploits the particular hardware is available. |
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1197-L1312)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.distribute.StrategyExtended tf.compat.v1.distribute.StrategyExtended
========================================
Additional APIs for algorithms that need to be distribution-aware.
Inherits From: [`StrategyExtended`](../../../distribute/strategyextended)
```
tf.compat.v1.distribute.StrategyExtended(
container_strategy
)
```
>
> **Note:** For most usage of [`tf.distribute.Strategy`](../../../distribute/strategy), there should be no need to call these methods, since TensorFlow libraries (such as optimizers) already call these methods when needed on your behalf.
>
Some common use cases of functions on this page:
* *Locality*
[`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) can have the same *locality* as a *distributed variable*, which leads to a mirrored value residing on the same devices as the variable (as opposed to the compute devices). Such values may be passed to a call to [`tf.distribute.StrategyExtended.update`](../../../distribute/strategyextended#update) to update the value of a variable. You may use [`tf.distribute.StrategyExtended.colocate_vars_with`](../../../distribute/strategyextended#colocate_vars_with) to give a variable the same locality as another variable. You may convert a "PerReplica" value to a variable's locality by using [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to) or [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to).
* *How to update a distributed variable*
A distributed variable is variables created on multiple devices. As discussed in the [glossary](https://www.tensorflow.org/api_docs/python/tf/distribute), mirrored variable and SyncOnRead variable are two examples. The standard pattern for updating distributed variables is to:
1. In your function passed to [`tf.distribute.Strategy.run`](../../../distribute/strategy#run), compute a list of (update, variable) pairs. For example, the update might be a gradient of the loss with respect to the variable.
2. Switch to cross-replica mode by calling `tf.distribute.get_replica_context().merge_call()` with the updates and variables as arguments.
3. Call [`tf.distribute.StrategyExtended.reduce_to(VariableAggregation.SUM, t, v)`](../../../distribute/strategyextended#reduce_to) (for one variable) or [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to) (for a list of variables) to sum the updates.
4. Call [`tf.distribute.StrategyExtended.update(v)`](../../../distribute/strategyextended#update) for each variable to update its value.
Steps 2 through 4 are done automatically by class [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) if you call its [`tf.keras.optimizers.Optimizer.apply_gradients`](../../../keras/optimizers/optimizer#apply_gradients) method in a replica context.
In fact, a higher-level solution to update a distributed variable is by calling `assign` on the variable as you would do to a regular [`tf.Variable`](../../../variable). You can call the method in both *replica context* and *cross-replica context*. For a *mirrored variable*, calling `assign` in *replica context* requires you to specify the `aggregation` type in the variable constructor. In that case, the context switching and sync described in steps 2 through 4 are handled for you. If you call `assign` on *mirrored variable* in *cross-replica context*, you can only assign a single value or assign values from another mirrored variable or a mirrored [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues). For a *SyncOnRead variable*, in *replica context*, you can simply call `assign` on it and no aggregation happens under the hood. In *cross-replica context*, you can only assign a single value to a SyncOnRead variable. One example case is restoring from a checkpoint: if the `aggregation` type of the variable is [`tf.VariableAggregation.SUM`](../../../variableaggregation#SUM), it is assumed that replica values were added before checkpointing, so at the time of restoring, the value is divided by the number of replicas and then assigned to each replica; if the `aggregation` type is [`tf.VariableAggregation.MEAN`](../../../variableaggregation#MEAN), the value is assigned to each replica directly.
| Attributes |
| `experimental_between_graph` | Whether the strategy uses between-graph replication or not. This is expected to return a constant value that will not be changed throughout its life cycle. |
| `experimental_require_static_shapes` | Returns `True` if static shape is required; `False` otherwise. |
| `experimental_should_init` | Whether initialization is needed. |
| `parameter_devices` | Returns the tuple of all devices used to place variables. |
| `should_checkpoint` | Whether checkpointing is needed. |
| `should_save_summary` | Whether saving summaries is needed. |
| `worker_devices` | Returns the tuple of all devices used to for compute replica execution.
|
Methods
-------
### `batch_reduce_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2386-L2456)
```
batch_reduce_to(
reduce_op, value_destination_pairs, options=None
)
```
Combine multiple `reduce_to` calls into one for faster execution.
Similar to `reduce_to`, but accepts a list of (value, destinations) pairs. It's more efficient than reduce each value separately.
This API currently can only be called in cross-replica context. Other variants to reduce values across replicas are:
* [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to): the non-batch version of this API.
* [`tf.distribute.ReplicaContext.all_reduce`](../../../distribute/replicacontext#all_reduce): the counterpart of this API in replica context. It supports both batched and non-batched all-reduce.
* [`tf.distribute.Strategy.reduce`](../../../distribute/strategy#reduce): a more convenient method to reduce to the host in cross-replica context.
See `reduce_to` for more information.
```
@tf.function
def step_fn(var):
def merge_fn(strategy, value, var):
# All-reduce the value. Note that `value` here is a
# `tf.distribute.DistributedValues`.
reduced = strategy.extended.batch_reduce_to(
tf.distribute.ReduceOp.SUM, [(value, var)])[0]
strategy.extended.update(var, lambda var, value: var.assign(value),
args=(reduced,))
value = tf.identity(1.)
tf.distribute.get_replica_context().merge_call(merge_fn,
args=(value, var))
def run(strategy):
with strategy.scope():
v = tf.Variable(0.)
strategy.run(step_fn, args=(v,))
return v
run(tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]))
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=2.0>
}
run(tf.distribute.experimental.CentralStorageStrategy(
compute_devices=["GPU:0", "GPU:1"], parameter_device="CPU:0"))
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>
run(tf.distribute.OneDeviceStrategy("GPU:0"))
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value_destination_pairs` | a sequence of (value, destinations) pairs. See `tf.distribute.Strategy.reduce_to` for descriptions. |
| `options` | a [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions). Options to perform collective operations. This overrides the default options if the [`tf.distribute.Strategy`](../../../distribute/strategy) takes one in the constructor. See [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions) for details of the options. |
| Returns |
| A list of reduced values, one per pair in `value_destination_pairs`. |
### `broadcast_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2768-L2783)
```
broadcast_to(
tensor, destinations
)
```
Mirror a tensor on one device to all worker devices.
| Args |
| `tensor` | A Tensor value to broadcast. |
| `destinations` | A mirrored variable or device string specifying the destination devices to copy `tensor` to. |
| Returns |
| A value mirrored to `destinations` devices. |
### `call_for_each_replica`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2840-L2888)
```
call_for_each_replica(
fn, args=(), kwargs=None
)
```
Run `fn` once per replica.
`fn` may call `tf.get_replica_context()` to access methods such as `replica_id_in_sync_group` and `merge_call()`.
`merge_call()` is used to communicate between the replicas and re-enter the cross-replica context. All replicas pause their execution having encountered a `merge_call()` call. After that the `merge_fn`-function is executed. Its results are then unwrapped and given back to each replica call. After that execution resumes until `fn` is complete or encounters another `merge_call()`. Example:
```
# Called once in "cross-replica" context.
def merge_fn(distribution, three_plus_replica_id):
# sum the values across replicas
return sum(distribution.experimental_local_results(three_plus_replica_id))
# Called once per replica in `distribution`, in a "replica" context.
def fn(three):
replica_ctx = tf.get_replica_context()
v = three + replica_ctx.replica_id_in_sync_group
# Computes the sum of the `v` values across all replicas.
s = replica_ctx.merge_call(merge_fn, args=(v,))
return s + v
with distribution.scope():
# in "cross-replica" context
...
merged_results = distribution.run(fn, args=[3])
# merged_results has the values from every replica execution of `fn`.
# This statement prints a list:
print(distribution.experimental_local_results(merged_results))
```
| Args |
| `fn` | function to run (will be run once per replica). |
| `args` | Tuple or list with positional arguments for `fn`. |
| `kwargs` | Dict with keyword arguments for `fn`. |
| Returns |
| Merged return value of `fn` across all replicas. |
### `colocate_vars_with`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2227-L2272)
```
colocate_vars_with(
colocate_with_variable
)
```
Scope that controls which devices variables will be created on.
No operations should be added to the graph inside this scope, it should only be used when creating variables (some implementations work by changing variable creation, others work by using a tf.compat.v1.colocate\_with() scope).
This may only be used inside `self.scope()`.
#### Example usage:
```
with strategy.scope():
var1 = tf.Variable(...)
with strategy.extended.colocate_vars_with(var1):
# var2 and var3 will be created on the same device(s) as var1
var2 = tf.Variable(...)
var3 = tf.Variable(...)
def fn(v1, v2, v3):
# operates on v1 from var1, v2 from var2, and v3 from var3
# `fn` runs on every device `var1` is on, `var2` and `var3` will be there
# too.
strategy.extended.update(var1, fn, args=(var2, var3))
```
| Args |
| `colocate_with_variable` | A variable created in this strategy's `scope()`. Variables created while in the returned context manager will be on the same set of devices as `colocate_with_variable`. |
| Returns |
| A context manager. |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2745-L2763)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be distributed evenly across all replicas. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../data/dataset) representing `numpy_input`. |
### `experimental_run_steps_on_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2788-L2834)
```
experimental_run_steps_on_iterator(
fn, iterator, iterations=1, initial_loop_values=None
)
```
Run `fn` with input from `iterator` for `iterations` times.
This method can be used to run a step function for training a number of times using input from a dataset.
| Args |
| `fn` | function to run using this distribution strategy. The function must have the following signature: `def fn(context, inputs)`. `context` is an instance of `MultiStepContext` that will be passed when `fn` is run. `context` can be used to specify the outputs to be returned from `fn` by calling `context.set_last_step_output`. It can also be used to capture non tensor outputs by `context.set_non_tensor_output`. See `MultiStepContext` documentation for more information. `inputs` will have same type/structure as `iterator.get_next()`. Typically, `fn` will use `call_for_each_replica` method of the strategy to distribute the computation over multiple replicas. |
| `iterator` | Iterator of a dataset that represents the input for `fn`. The caller is responsible for initializing the iterator as needed. |
| `iterations` | (Optional) Number of iterations that `fn` should be run. Defaults to 1. |
| `initial_loop_values` | (Optional) Initial values to be passed into the loop that runs `fn`. Defaults to `None`. initial\_loop\_values argument when we have a mechanism to infer the outputs of `fn`. |
| Returns |
| Returns the `MultiStepContext` object which has the following properties, among other things: * run\_op: An op that runs `fn` `iterations` times.
* last\_step\_outputs: A dictionary containing tensors set using `context.set_last_step_output`. Evaluating this returns the value of the tensors after the last iteration.
* non\_tensor\_outputs: A dictionary containing anything that was set by `fn` by calling `context.set_non_tensor_output`.
|
### `non_slot_devices`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2938-L2957)
```
non_slot_devices(
var_list
)
```
Device(s) for non-slot variables.
This method returns non-slot devices where non-slot variables are placed. Users can create non-slot variables on these devices by using a block:
```
with tf.distribute.StrategyExtended.colocate_vars_with(tf.distribute.StrategyExtended.non_slot_devices(...)):
...
```
| Args |
| `var_list` | The list of variables being optimized, needed with the default [`tf.distribute.Strategy`](../../../distribute/strategy). |
| Returns |
| A sequence of devices for non-slot variables. |
### `read_var`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2893-L2906)
```
read_var(
v
)
```
Reads the value of a variable.
Returns the aggregate value of a replica-local variable, or the (read-only) value of any other variable.
| Args |
| `v` | A variable allocated within the scope of this [`tf.distribute.Strategy`](../../../distribute/strategy). |
| Returns |
| A tensor representing the value of `v`, aggregated across replicas if necessary. |
### `reduce_to`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2298-L2381)
```
reduce_to(
reduce_op, value, destinations, options=None
)
```
Combine (via e.g. sum or mean) values across replicas.
`reduce_to` aggregates [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues) and distributed variables. It supports both dense values and [`tf.IndexedSlices`](../../../indexedslices).
This API currently can only be called in cross-replica context. Other variants to reduce values across replicas are:
* [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to): the batch version of this API.
* [`tf.distribute.ReplicaContext.all_reduce`](../../../distribute/replicacontext#all_reduce): the counterpart of this API in replica context. It supports both batched and non-batched all-reduce.
* [`tf.distribute.Strategy.reduce`](../../../distribute/strategy#reduce): a more convenient method to reduce to the host in cross-replica context.
`destinations` specifies where to reduce the value to, e.g. "GPU:0". You can also pass in a `Tensor`, and the destinations will be the device of that tensor. For all-reduce, pass the same to `value` and `destinations`.
It can be used in [`tf.distribute.ReplicaContext.merge_call`](../../../distribute/replicacontext#merge_call) to write code that works for all [`tf.distribute.Strategy`](../../../distribute/strategy).
```
@tf.function
def step_fn(var):
def merge_fn(strategy, value, var):
# All-reduce the value. Note that `value` here is a
# `tf.distribute.DistributedValues`.
reduced = strategy.extended.reduce_to(tf.distribute.ReduceOp.SUM,
value, destinations=var)
strategy.extended.update(var, lambda var, value: var.assign(value),
args=(reduced,))
value = tf.identity(1.)
tf.distribute.get_replica_context().merge_call(merge_fn,
args=(value, var))
def run(strategy):
with strategy.scope():
v = tf.Variable(0.)
strategy.run(step_fn, args=(v,))
return v
run(tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"]))
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=2.0>
}
run(tf.distribute.experimental.CentralStorageStrategy(
compute_devices=["GPU:0", "GPU:1"], parameter_device="CPU:0"))
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>
run(tf.distribute.OneDeviceStrategy("GPU:0"))
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), or a [`tf.Tensor`](../../../tensor) like object. |
| `destinations` | a [`tf.distribute.DistributedValues`](../../../distribute/distributedvalues), a [`tf.Variable`](../../../variable), a [`tf.Tensor`](../../../tensor) alike object, or a device string. It specifies the devices to reduce to. To perform an all-reduce, pass the same to `value` and `destinations`. Note that if it's a [`tf.Variable`](../../../variable), the value is reduced to the devices of that variable, and this method doesn't update the variable. |
| `options` | a [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions). Options to perform collective operations. This overrides the default options if the [`tf.distribute.Strategy`](../../../distribute/strategy) takes one in the constructor. See [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions) for details of the options. |
| Returns |
| A tensor or value reduced to `destinations`. |
### `update`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2557-L2633)
```
update(
var, fn, args=(), kwargs=None, group=True
)
```
Run `fn` to update `var` using inputs mirrored to the same devices.
[`tf.distribute.StrategyExtended.update`](../../../distribute/strategyextended#update) takes a distributed variable `var` to be updated, an update function `fn`, and `args` and `kwargs` for `fn`. It applies `fn` to each component variable of `var` and passes corresponding values from `args` and `kwargs`. Neither `args` nor `kwargs` may contain per-replica values. If they contain mirrored values, they will be unwrapped before calling `fn`. For example, `fn` can be `assign_add` and `args` can be a mirrored DistributedValues where each component contains the value to be added to this mirrored variable `var`. Calling `update` will call `assign_add` on each component variable of `var` with the corresponding tensor value on that device.
#### Example usage:
```
strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1']) # With 2
devices
with strategy.scope():
v = tf.Variable(5.0, aggregation=tf.VariableAggregation.SUM)
def update_fn(v):
return v.assign(1.0)
result = strategy.extended.update(v, update_fn)
# result is
# Mirrored:{
# 0: tf.Tensor(1.0, shape=(), dtype=float32),
# 1: tf.Tensor(1.0, shape=(), dtype=float32)
# }
```
If `var` is mirrored across multiple devices, then this method implements logic as following:
```
results = {}
for device, v in var:
with tf.device(device):
# args and kwargs will be unwrapped if they are mirrored.
results[device] = fn(v, *args, **kwargs)
return merged(results)
```
Otherwise, this method returns `fn(var, *args, **kwargs)` colocated with `var`.
| Args |
| `var` | Variable, possibly mirrored to multiple devices, to operate on. |
| `fn` | Function to call. Should take the variable as the first argument. |
| `args` | Tuple or list. Additional positional arguments to pass to `fn()`. |
| `kwargs` | Dict with keyword arguments to pass to `fn()`. |
| `group` | Boolean. Defaults to True. If False, the return value will be unwrapped. |
| Returns |
| By default, the merged return value of `fn` across all replicas. The merged result has dependencies to make sure that if it is evaluated at all, the side effects (updates) will happen on every replica. If instead "group=False" is specified, this function will return a nest of lists where each list has an element per replica, and the caller is responsible for ensuring all elements are executed. |
### `update_non_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2908-L2933)
```
update_non_slot(
colocate_with, fn, args=(), kwargs=None, group=True
)
```
Runs `fn(*args, **kwargs)` on `colocate_with` devices.
Used to update non-slot variables.
| Args |
| `colocate_with` | Devices returned by `non_slot_devices()`. |
| `fn` | Function to execute. |
| `args` | Tuple or list. Positional arguments to pass to `fn()`. |
| `kwargs` | Dict with keyword arguments to pass to `fn()`. |
| `group` | Boolean. Defaults to True. If False, the return value will be unwrapped. |
| Returns |
| Return value of `fn`, possibly merged across devices. |
### `value_container`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2659-L2672)
```
value_container(
value
)
```
Returns the container that this per-replica `value` belongs to.
| Args |
| `value` | A value returned by `run()` or a variable created in `scope()`. |
| Returns |
| A container that `value` belongs to. If value does not belong to any container (including the case of container having been destroyed), returns the value itself. `value in experimental_local_results(value_container(value))` will always be true. |
### `variable_created_in_scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2201-L2225)
```
variable_created_in_scope(
v
)
```
Tests whether `v` was created while this strategy scope was active.
Variables created inside the strategy scope are "owned" by it:
```
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
v = tf.Variable(1.)
strategy.extended.variable_created_in_scope(v)
True
```
Variables created outside the strategy are not owned by it:
```
strategy = tf.distribute.MirroredStrategy()
v = tf.Variable(1.)
strategy.extended.variable_created_in_scope(v)
False
```
| Args |
| `v` | A [`tf.Variable`](../../../variable) instance. |
| Returns |
| True if `v` was created inside the scope, False if not. |
| programming_docs |
tensorflow tf.compat.v1.distribute.get_loss_reduction tf.compat.v1.distribute.get\_loss\_reduction
============================================
[`tf.distribute.ReduceOp`](../../../distribute/reduceop) corresponding to the last loss reduction.
```
tf.compat.v1.distribute.get_loss_reduction()
```
This is used to decide whether loss should be scaled in optimizer (used only for estimator + v1 optimizer use case).
| Returns |
| [`tf.distribute.ReduceOp`](../../../distribute/reduceop) corresponding to the last loss reduction for estimator and v1 optimizer use case. [`tf.distribute.ReduceOp.SUM`](../../../distribute/reduceop#SUM) otherwise. |
tensorflow Module: tf.compat.v1.distribute.experimental Module: tf.compat.v1.distribute.experimental
============================================
Experimental Distribution Strategy library.
Classes
-------
[`class CentralStorageStrategy`](experimental/centralstoragestrategy): A one-machine strategy that puts all variables on a single device.
[`class CollectiveCommunication`](../../../distribute/experimental/communicationimplementation): Cross device communication implementation.
[`class CollectiveHints`](../../../distribute/experimental/collectivehints): Hints for collective operations like AllReduce.
[`class CommunicationImplementation`](../../../distribute/experimental/communicationimplementation): Cross device communication implementation.
[`class CommunicationOptions`](../../../distribute/experimental/communicationoptions): Options for cross device communications like All-reduce.
[`class MultiWorkerMirroredStrategy`](experimental/multiworkermirroredstrategy): A distribution strategy for synchronous training on multiple workers.
[`class ParameterServerStrategy`](experimental/parameterserverstrategy): An asynchronous multi-worker parameter server tf.distribute strategy.
[`class TPUStrategy`](experimental/tpustrategy): TPU distribution strategy implementation.
tensorflow tf.compat.v1.distribute.ReplicaContext tf.compat.v1.distribute.ReplicaContext
======================================
A class with a collection of APIs that can be called in a replica context.
```
tf.compat.v1.distribute.ReplicaContext(
strategy, replica_id_in_sync_group
)
```
You can use [`tf.distribute.get_replica_context`](../../../distribute/get_replica_context) to get an instance of `ReplicaContext`, which can only be called inside the function passed to [`tf.distribute.Strategy.run`](../../../distribute/strategy#run).
```
strategy = tf.distribute.MirroredStrategy(['GPU:0', 'GPU:1'])
def func():
replica_context = tf.distribute.get_replica_context()
return replica_context.replica_id_in_sync_group
strategy.run(func)
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=0>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `strategy` | A [`tf.distribute.Strategy`](../../../distribute/strategy). |
| `replica_id_in_sync_group` | An integer, a `Tensor` or None. Prefer an integer whenever possible to avoid issues with nested [`tf.function`](../../../function). It accepts a `Tensor` only to be compatible with `tpu.replicate`. |
| Attributes |
| `devices` | Returns the devices this replica is to be executed on, as a tuple of strings. (deprecated)
**Note:** For [`tf.distribute.MirroredStrategy`](../../../distribute/mirroredstrategy) and [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../distribute/experimental/multiworkermirroredstrategy), this returns a nested list of device strings, e.g, [["GPU:0"]].
|
| `num_replicas_in_sync` | Returns number of replicas that are kept in sync. |
| `replica_id_in_sync_group` | Returns the id of the replica. This identifies the replica among all replicas that are kept in sync. The value of the replica id can range from 0 to [`tf.distribute.ReplicaContext.num_replicas_in_sync`](../../../distribute/replicacontext#num_replicas_in_sync) - 1.
**Note:** This is not guaranteed to be the same ID as the XLA replica ID use for low-level operations such as collective\_permute.
|
| `strategy` | The current [`tf.distribute.Strategy`](../../../distribute/strategy) object. |
Methods
-------
### `all_reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L3171-L3281)
```
all_reduce(
reduce_op, value, options=None
)
```
All-reduces `value` across all replicas.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
ctx = tf.distribute.get_replica_context()
value = tf.identity(1.)
return ctx.all_reduce(tf.distribute.ReduceOp.SUM, value)
strategy.experimental_local_results(strategy.run(step_fn))
(<tf.Tensor: shape=(), dtype=float32, numpy=2.0>,
<tf.Tensor: shape=(), dtype=float32, numpy=2.0>)
```
It supports batched operations. You can pass a list of values and it attempts to batch them when possible. You can also specify `options` to indicate the desired batching behavior, e.g. batch the values into multiple packs so that they can better overlap with computations.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
ctx = tf.distribute.get_replica_context()
value1 = tf.identity(1.)
value2 = tf.identity(2.)
return ctx.all_reduce(tf.distribute.ReduceOp.SUM, [value1, value2])
strategy.experimental_local_results(strategy.run(step_fn))
([<tf.Tensor: shape=(), dtype=float32, numpy=2.0>,
<tf.Tensor: shape=(), dtype=float32, numpy=4.0>],
[<tf.Tensor: shape=(), dtype=float32, numpy=2.0>,
<tf.Tensor: shape=(), dtype=float32, numpy=4.0>])
```
Note that all replicas need to participate in the all-reduce, otherwise this operation hangs. Note that if there're multiple all-reduces, they need to execute in the same order on all replicas. Dispatching all-reduce based on conditions is usually error-prone.
Known limitation: if `value` contains [`tf.IndexedSlices`](../../../indexedslices), attempting to compute gradient w.r.t `value` would result in an error.
This API currently can only be called in the replica context. Other variants to reduce values across replicas are:
* [`tf.distribute.StrategyExtended.reduce_to`](../../../distribute/strategyextended#reduce_to): the reduce and all-reduce API in the cross-replica context.
* [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../distribute/strategyextended#batch_reduce_to): the batched reduce and all-reduce API in the cross-replica context.
* [`tf.distribute.Strategy.reduce`](../../../distribute/strategy#reduce): a more convenient method to reduce to the host in cross-replica context.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a potentially nested structure of [`tf.Tensor`](../../../tensor) or [`tf.IndexedSlices`](../../../indexedslices) which [`tf.nest.flatten`](../../../nest/flatten) accepts. The structure and the shapes of `value` need to be same on all replicas. |
| `options` | a [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions). Options to perform collective operations. This overrides the default options if the [`tf.distribute.Strategy`](../../../distribute/strategy) takes one in the constructor. See [`tf.distribute.experimental.CommunicationOptions`](../../../distribute/experimental/communicationoptions) for details of the options. |
| Returns |
| A nested structure of [`tf.Tensor`](../../../tensor) with the reduced values. The structure is the same as `value`. |
### `merge_call`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L3070-L3103)
```
merge_call(
merge_fn, args=(), kwargs=None
)
```
Merge args across replicas and run `merge_fn` in a cross-replica context.
This allows communication and coordination when there are multiple calls to the step\_fn triggered by a call to `strategy.run(step_fn, ...)`.
See [`tf.distribute.Strategy.run`](../../../distribute/strategy#run) for an explanation.
If not inside a distributed scope, this is equivalent to:
```
strategy = tf.distribute.get_strategy()
with cross-replica-context(strategy):
return merge_fn(strategy, *args, **kwargs)
```
| Args |
| `merge_fn` | Function that joins arguments from threads that are given as PerReplica. It accepts [`tf.distribute.Strategy`](../../../distribute/strategy) object as the first argument. |
| `args` | List or tuple with positional per-thread arguments for `merge_fn`. |
| `kwargs` | Dict with keyword per-thread arguments for `merge_fn`. |
| Returns |
| The return value of `merge_fn`, except for `PerReplica` values which are unpacked. |
tensorflow tf.compat.v1.distribute.experimental.ParameterServerStrategy tf.compat.v1.distribute.experimental.ParameterServerStrategy
============================================================
An asynchronous multi-worker parameter server tf.distribute strategy.
Inherits From: [`Strategy`](../strategy)
```
tf.compat.v1.distribute.experimental.ParameterServerStrategy(
cluster_resolver=None
)
```
This strategy requires two roles: workers and parameter servers. Variables and updates to those variables will be assigned to parameter servers and other operations are assigned to workers.
When each worker has more than one GPU, operations will be replicated on all GPUs. Even though operations may be replicated, variables are not and each worker shares a common view for which parameter server a variable is assigned to.
By default it uses `TFConfigClusterResolver` to detect configurations for multi-worker training. This requires a 'TF\_CONFIG' environment variable and the 'TF\_CONFIG' must have a cluster spec.
This class assumes each worker is running the same code independently, but parameter servers are running a standard server. This means that while each worker will synchronously compute a single gradient update across all GPUs, updates between workers proceed asynchronously. Operations that occur only on the first replica (such as incrementing the global step), will occur on the first replica *of every worker*.
It is expected to call `call_for_each_replica(fn, ...)` for any operations which potentially can be replicated across replicas (i.e. multiple GPUs) even if there is only CPU or one GPU. When defining the `fn`, extra caution needs to be taken:
1) It is generally not recommended to open a device scope under the strategy's scope. A device scope (i.e. calling [`tf.device`](../../../../device)) will be merged with or override the device for operations but will not change the device for variables.
2) It is also not recommended to open a colocation scope (i.e. calling [`tf.compat.v1.colocate_with`](../../colocate_with)) under the strategy's scope. For colocating variables, use `strategy.extended.colocate_vars_with` instead. Colocation of ops will possibly create device assignment conflicts.
>
> **Note:** This strategy only works with the Estimator API. Pass an instance of this strategy to the `experimental_distribute` argument when you create the `RunConfig`. This instance of `RunConfig` should then be passed to the `Estimator` instance on which `train_and_evaluate` is called.
>
#### For Example:
```
strategy = tf.distribute.experimental.ParameterServerStrategy()
run_config = tf.estimator.RunConfig(
experimental_distribute.train_distribute=strategy)
estimator = tf.estimator.Estimator(config=run_config)
tf.estimator.train_and_evaluate(estimator,...)
```
| Args |
| `cluster_resolver` | Optional [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) object. Defaults to a [`tf.distribute.cluster_resolver.TFConfigClusterResolver`](../../../../distribute/cluster_resolver/tfconfigclusterresolver). |
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/parameter_server_strategy.py#L131-L141)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/parameter_server_strategy.py#L118-L129)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/parameter_server_strategy.py#L143-L146)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/parameter_server_strategy.py#L148-L150)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.distribute.experimental.TPUStrategy tf.compat.v1.distribute.experimental.TPUStrategy
================================================
TPU distribution strategy implementation.
Inherits From: [`Strategy`](../strategy)
```
tf.compat.v1.distribute.experimental.TPUStrategy(
tpu_cluster_resolver=None, steps_per_run=None, device_assignment=None
)
```
| Args |
| `tpu_cluster_resolver` | A tf.distribute.cluster\_resolver.TPUClusterResolver, which provides information about the TPU cluster. |
| `steps_per_run` | Number of steps to run on device before returning to the host. Note that this can have side-effects on performance, hooks, metrics, summaries etc. This parameter is only used when Distribution Strategy is used with estimator or keras. |
| `device_assignment` | Optional [`tf.tpu.experimental.DeviceAssignment`](../../../../tpu/experimental/deviceassignment) to specify the placement of replicas on the TPU cluster. Currently only supports the usecase of using a single core within a TPU cluster. |
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
| `steps_per_run` | DEPRECATED: use .extended.steps\_per\_run instead. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/tpu_strategy.py#L778-L835)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Run `fn` on each replica, with the given arguments.
Executes ops specified by `fn` on each replica. If `args` or `kwargs` have "per-replica" values, such as those produced by a "distributed `Dataset`", when `fn` is executed on a particular replica, it will be executed with the component of those "per-replica" values that correspond to that replica.
`fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `all_reduce`.
All arguments in `args` or `kwargs` should either be nest of tensors or per-replica objects containing tensors or composite tensors.
Users can pass strategy specific options to `options` argument. An example to enable bucketizing dynamic shapes in [`TPUStrategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/TPUStrategy#run) is:
```
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tf.config.experimental_connect_to_cluster(resolver)
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)
```
```
options = tf.distribute.RunOptions(
experimental_bucketizing_dynamic_shape=True)
```
```
dataset = tf.data.Dataset.range(
strategy.num_replicas_in_sync, output_type=dtypes.float32).batch(
strategy.num_replicas_in_sync, drop_remainder=True)
input_iterator = iter(strategy.experimental_distribute_dataset(dataset))
```
```
@tf.function()
def step_fn(inputs):
output = tf.reduce_sum(inputs)
return output
```
```
strategy.run(step_fn, args=(next(input_iterator),), options=options)
```
| Args |
| `fn` | The function to run. The output must be a [`tf.nest`](../../../../nest) of `Tensor`s. |
| `args` | (Optional) Positional arguments to `fn`. |
| `kwargs` | (Optional) Keyword arguments to `fn`. |
| `options` | (Optional) An instance of [`tf.distribute.RunOptions`](../../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be "per-replica" `Tensor` objects or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.distribute.experimental.MultiWorkerMirroredStrategy tf.compat.v1.distribute.experimental.MultiWorkerMirroredStrategy
================================================================
A distribution strategy for synchronous training on multiple workers.
Inherits From: [`Strategy`](../strategy)
```
tf.compat.v1.distribute.experimental.MultiWorkerMirroredStrategy(
communication=tf.distribute.experimental.CollectiveCommunication.AUTO,
cluster_resolver=None
)
```
This strategy implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to [`tf.distribute.MirroredStrategy`](../../../../distribute/mirroredstrategy), it replicates all variables and computations to each local device. The difference is that it uses a distributed collective implementation (e.g. all-reduce), so that multiple workers can work together.
You need to launch your program on each worker and configure `cluster_resolver` correctly. For example, if you are using [`tf.distribute.cluster_resolver.TFConfigClusterResolver`](../../../../distribute/cluster_resolver/tfconfigclusterresolver), each worker needs to have its corresponding `task_type` and `task_id` set in the `TF_CONFIG` environment variable. An example TF\_CONFIG on worker-0 of a two worker cluster is:
```
TF_CONFIG = '{"cluster": {"worker": ["localhost:12345", "localhost:23456"]}, "task": {"type": "worker", "index": 0} }'
```
Your program runs on each worker as-is. Note that collectives require each worker to participate. All [`tf.distribute`](../../../../distribute) and non [`tf.distribute`](../../../../distribute) API may use collectives internally, e.g. checkpointing and saving since reading a [`tf.Variable`](../../../../variable) with [`tf.VariableSynchronization.ON_READ`](../../../../variablesynchronization#ON_READ) all-reduces the value. Therefore it's recommended to run exactly the same program on each worker. Dispatching based on `task_type` or `task_id` of the worker is error-prone.
`cluster_resolver.num_accelerators()` determines the number of GPUs the strategy uses. If it's zero, the strategy uses the CPU. All workers need to use the same number of devices, otherwise the behavior is undefined.
This strategy is not intended for TPU. Use [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy) instead.
After setting up TF\_CONFIG, using this strategy is similar to using [`tf.distribute.MirroredStrategy`](../../../../distribute/mirroredstrategy) and [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy).
```
strategy = tf.distribute.MultiWorkerMirroredStrategy()
with strategy.scope():
model = tf.keras.Sequential([
tf.keras.layers.Dense(2, input_shape=(5,)),
])
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
def dataset_fn(ctx):
x = np.random.random((2, 5)).astype(np.float32)
y = np.random.randint(2, size=(2, 1))
dataset = tf.data.Dataset.from_tensor_slices((x, y))
return dataset.repeat().batch(1, drop_remainder=True)
dist_dataset = strategy.distribute_datasets_from_function(dataset_fn)
model.compile()
model.fit(dist_dataset)
```
You can also write your own training loop:
```
@tf.function
def train_step(iterator):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features, training=True)
loss = tf.keras.losses.sparse_categorical_crossentropy(
labels, logits)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
strategy.run(step_fn, args=(next(iterator),))
for _ in range(NUM_STEP):
train_step(iterator)
```
See [Multi-worker training with Keras](https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras) for a detailed tutorial.
**Saving**
You need to save and checkpoint on all workers instead of just one. This is because variables whose synchronization=ON\_READ triggers aggregation during saving. It's recommended to save to a different path on each worker to avoid race conditions. Each worker saves the same thing. See [Multi-worker training with Keras](https://www.tensorflow.org/tutorials/distribute/multi_worker_with_keras#model_saving_and_loading) tutorial for examples.
**Known Issues**
* [`tf.distribute.cluster_resolver.TFConfigClusterResolver`](../../../../distribute/cluster_resolver/tfconfigclusterresolver) does not return the correct number of accelerators. The strategy uses all available GPUs if `cluster_resolver` is [`tf.distribute.cluster_resolver.TFConfigClusterResolver`](../../../../distribute/cluster_resolver/tfconfigclusterresolver) or `None`.
* In eager mode, the strategy needs to be created before calling any other Tensorflow API.
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1197-L1312)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.distribute.experimental.CentralStorageStrategy tf.compat.v1.distribute.experimental.CentralStorageStrategy
===========================================================
A one-machine strategy that puts all variables on a single device.
Inherits From: [`Strategy`](../strategy)
```
tf.compat.v1.distribute.experimental.CentralStorageStrategy(
compute_devices=None, parameter_device=None
)
```
Variables are assigned to local CPU or the only GPU. If there is more than one GPU, compute operations (other than variable update operations) will be replicated across all GPUs.
#### For Example:
```
strategy = tf.distribute.experimental.CentralStorageStrategy()
# Create a dataset
ds = tf.data.Dataset.range(5).batch(2)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(ds)
with strategy.scope():
@tf.function
def train_step(val):
return val + 1
# Iterate over the distributed dataset
for x in dist_dataset:
# process dataset elements
strategy.run(train_step, args=(x,))
```
| Attributes |
| `cluster_resolver` | Returns the cluster resolver associated with this strategy. In general, when using a multi-worker [`tf.distribute`](../../../../distribute) strategy such as [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy()`](../../../../distribute/tpustrategy), there is a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) associated with the strategy used, and such an instance is returned by this property. Strategies that intend to have an associated [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) must set the relevant attribute, or override this property; otherwise, `None` is returned by default. Those strategies should also provide information regarding what is returned by this property. Single-worker strategies usually do not have a [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver), and in those cases this property will return `None`. The [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver) may be useful when the user needs to access information such as the cluster spec, task type or task id. For example,
```
os.environ['TF_CONFIG'] = json.dumps({
'cluster': {
'worker': ["localhost:12345", "localhost:23456"],
'ps': ["localhost:34567"]
},
'task': {'type': 'worker', 'index': 0}
})
# This implicitly uses TF_CONFIG for the cluster and current task info.
strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
...
if strategy.cluster_resolver.task_type == 'worker':
# Perform something that's only applicable on workers. Since we set this
# as a worker above, this block will run on this particular instance.
elif strategy.cluster_resolver.task_type == 'ps':
# Perform something that's only applicable on parameter servers. Since we
# set this as a worker above, this block will not run on this particular
# instance.
```
For more information, please see [`tf.distribute.cluster_resolver.ClusterResolver`](../../../../distribute/cluster_resolver/clusterresolver)'s API docstring. |
| `extended` | [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) with additional methods. |
| `num_replicas_in_sync` | Returns number of replicas over which gradients are aggregated. |
Methods
-------
### `distribute_datasets_from_function`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1110-L1187)
```
distribute_datasets_from_function(
dataset_fn, options=None
)
```
Distributes [`tf.data.Dataset`](../../../../data/dataset) instances created by calls to `dataset_fn`.
The argument `dataset_fn` that users pass in is an input function that has a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) argument and returns a [`tf.data.Dataset`](../../../../data/dataset) instance. It is expected that the returned dataset from `dataset_fn` is already batched by per-replica batch size (i.e. global batch size divided by the number of replicas in sync) and sharded. [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) does not batch or shard the [`tf.data.Dataset`](../../../../data/dataset) instance returned from the input function. `dataset_fn` will be called on the CPU device of each of the workers and each generates a dataset where every replica on that worker will dequeue one batch of inputs (i.e. if a worker has two replicas, two batches will be dequeued from the `Dataset` every step).
This method can be used for several purposes. First, it allows you to specify your own batching and sharding logic. (In contrast, `tf.distribute.experimental_distribute_dataset` does batching and sharding for you.) For example, where `experimental_distribute_dataset` is unable to shard the input files, this method might be used to manually shard the dataset (avoiding the slow fallback behavior in `experimental_distribute_dataset`). In cases where the dataset is infinite, this sharding can be done by creating dataset replicas that differ only in their random seed.
The `dataset_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance where information about batching and input replication can be accessed.
You can use `element_spec` property of the [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) returned by this API to query the [`tf.TypeSpec`](../../../../typespec) of the elements returned by the iterator. This can be used to set the `input_signature` property of a [`tf.function`](../../../../function). Follow [`tf.distribute.DistributedDataset.element_spec`](../../../../distribute/distributeddataset#element_spec) to see an example.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_datasets_from_function)). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) instance and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_distribute_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L989-L1108)
```
experimental_distribute_dataset(
dataset, options=None
)
```
Creates [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.data.Dataset`](../../../../data/dataset).
The returned [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) can be iterated over similar to regular datasets. NOTE: The user cannot add any more transformations to a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). You can only create an iterator or examine the [`tf.TypeSpec`](../../../../typespec) of the data generated by it. See API docs of [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) to learn more.
The following is an example:
```
global_batch_size = 2
# Passing the devices is optional.
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
# Create a dataset
dataset = tf.data.Dataset.range(4).batch(global_batch_size)
# Distribute that dataset
dist_dataset = strategy.experimental_distribute_dataset(dataset)
@tf.function
def replica_fn(input):
return input*2
result = []
# Iterate over the `tf.distribute.DistributedDataset`
for x in dist_dataset:
# process dataset elements
result.append(strategy.run(replica_fn, args=(x,)))
print(result)
[PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([0])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([2])>
}, PerReplica:{
0: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([4])>,
1: <tf.Tensor: shape=(1,), dtype=int64, numpy=array([6])>
}]
```
Three key actions happening under the hood of this method are batching, sharding, and prefetching.
In the code snippet above, `dataset` is batched by `global_batch_size`, and calling `experimental_distribute_dataset` on it rebatches `dataset` to a new batch size that is equal to the global batch size divided by the number of replicas in sync. We iterate through it using a Pythonic for loop. `x` is a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing data for all replicas, and each replica gets data of the new batch size. [`tf.distribute.Strategy.run`](../../../../distribute/strategy#run) will take care of feeding the right per-replica data in `x` to the right `replica_fn` executed on each replica.
Sharding contains autosharding across multiple workers and within every worker. First, in multi-worker distributed training (i.e. when you use [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy) or [`tf.distribute.TPUStrategy`](../../../../distribute/tpustrategy)), autosharding a dataset over a set of workers means that each worker is assigned a subset of the entire dataset (if the right [`tf.data.experimental.AutoShardPolicy`](../../../../data/experimental/autoshardpolicy) is set). This is to ensure that at each step, a global batch size of non-overlapping dataset elements will be processed by each worker. Autosharding has a couple of different options that can be specified using [`tf.data.experimental.DistributeOptions`](../../../../data/experimental/distributeoptions). Then, sharding within each worker means the method will split the data among all the worker devices (if more than one a present). This will happen regardless of multi-worker autosharding.
>
> **Note:** for autosharding across multiple workers, the default mode is [`tf.data.experimental.AutoShardPolicy.AUTO`](../../../../data/experimental/autoshardpolicy#AUTO). This mode will attempt to shard the input dataset by files if the dataset is being created out of reader datasets (e.g. [`tf.data.TFRecordDataset`](../../../../data/tfrecorddataset), [`tf.data.TextLineDataset`](../../../../data/textlinedataset), etc.) or otherwise shard the dataset by data, where each of the workers will read the entire dataset and only process the shard assigned to it. However, if you have less than one input file per worker, we suggest that you disable dataset autosharding across workers by setting the [`tf.data.experimental.DistributeOptions.auto_shard_policy`](../../../../data/experimental/distributeoptions#auto_shard_policy) to be [`tf.data.experimental.AutoShardPolicy.OFF`](../../../../data/experimental/autoshardpolicy#OFF).
>
By default, this method adds a prefetch transformation at the end of the user provided [`tf.data.Dataset`](../../../../data/dataset) instance. The argument to the prefetch transformation which is `buffer_size` is equal to the number of replicas in sync.
If the above batch splitting and dataset sharding logic is undesirable, please use [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) instead, which does not do any automatic batching or sharding for you.
>
> **Note:** If you are using TPUStrategy, the order in which the data is processed by the workers when using [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function) is not guaranteed. This is typically required if you are using [`tf.distribute`](../../../../distribute) to scale prediction. You can however insert an index for each element in the batch and order outputs accordingly. Refer to [this snippet](https://www.tensorflow.org/tutorials/distribute/input#caveats) for an example of how to order outputs.
>
>
> **Note:** Stateful dataset transformations are currently not supported with `tf.distribute.experimental_distribute_dataset` or `tf.distribute.distribute_datasets_from_function`. Any stateful ops that the dataset may have are currently ignored. For example, if your dataset has a `map_fn` that uses [`tf.random.uniform`](../../../../random/uniform) to rotate an image, then you have a dataset graph that depends on state (i.e the random seed) on the local machine where the python process is being executed.
>
For a tutorial on more usage and properties of this method, refer to the [tutorial on distributed input](https://www.tensorflow.org/tutorials/distribute/input#tfdistributestrategyexperimental_distribute_dataset). If you are interested in last partial batch handling, read [this section](https://www.tensorflow.org/tutorials/distribute/input#partial_batches).
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be sharded across all replicas using the rules stated above. |
| `options` | [`tf.distribute.InputOptions`](../../../../distribute/inputoptions) used to control options on how this dataset is distributed. |
| Returns |
| A [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset). |
### `experimental_local_results`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1541-L1559)
```
experimental_local_results(
value
)
```
Returns the list of all local per-replica values contained in `value`.
>
> **Note:** This only returns values on the worker initiated by this client. When using a [`tf.distribute.Strategy`](../../../../distribute/strategy) like [`tf.distribute.experimental.MultiWorkerMirroredStrategy`](../../../../distribute/experimental/multiworkermirroredstrategy), each worker will be its own client, and this function will only return values computed on that worker.
>
| Args |
| `value` | A value returned by `experimental_run()`, `run(), or a variable created in`scope`. |
| Returns |
| A tuple of values contained in `value` where ith element corresponds to ith replica. If `value` represents a single value, this returns `(value,).` |
### `experimental_make_numpy_dataset`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1942-L1971)
```
experimental_make_numpy_dataset(
numpy_input, session=None
)
```
Makes a tf.data.Dataset for input provided via a numpy array.
This avoids adding `numpy_input` as a large constant in the graph, and copies the data to the machine or machines that will be processing the input.
Note that you will likely need to use tf.distribute.Strategy.experimental\_distribute\_dataset with the returned dataset to further distribute it with the strategy.
#### Example:
```
numpy_input = np.ones([10], dtype=np.float32)
dataset = strategy.experimental_make_numpy_dataset(numpy_input)
dist_dataset = strategy.experimental_distribute_dataset(dataset)
```
| Args |
| `numpy_input` | A nest of NumPy input arrays that will be converted into a dataset. Note that lists of Numpy arrays are stacked, as that is normal [`tf.data.Dataset`](../../../../data/dataset) behavior. |
| `session` | (TensorFlow v1.x graph execution only) A session used for initialization. |
| Returns |
| A [`tf.data.Dataset`](../../../../data/dataset) representing `numpy_input`. |
### `experimental_run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1973-L2010)
```
experimental_run(
fn, input_iterator=None
)
```
Runs ops in `fn` on each replica, with inputs from `input_iterator`. (deprecated)
When eager execution is enabled, executes ops specified by `fn` on each replica. Otherwise, builds a graph to execute the ops on each replica.
Each replica will take a single, different input from the inputs provided by one `get_next` call on the input iterator.
`fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `replica_id_in_sync_group`.
| Args |
| `fn` | The function to run. The inputs to the function must match the outputs of `input_iterator.get_next()`. The output must be a [`tf.nest`](../../../../nest) of `Tensor`s. |
| `input_iterator` | (Optional) input iterator from which the inputs are taken. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be `PerReplica` (if the values are unsynchronized), `Mirrored` (if the values are kept in sync), or `Tensor` (if running on a single replica). |
### `make_dataset_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1874-L1898)
```
make_dataset_iterator(
dataset
)
```
Makes an iterator for input provided via `dataset`.
Data from the given dataset will be distributed evenly across all the compute replicas. We will assume that the input dataset is batched by the global batch size. With this assumption, we will make a best effort to divide each batch across all the replicas (one or more workers). If this effort fails, an error will be thrown, and the user should instead use `make_input_fn_iterator` which provides more control to the user, and does not try to divide a batch across replicas.
The user could also use `make_input_fn_iterator` if they want to customize which input is fed to which replica/worker etc.
| Args |
| `dataset` | [`tf.data.Dataset`](../../../../data/dataset) that will be distributed evenly across all replicas. |
| Returns |
| An `tf.distribute.InputIterator` which returns inputs for each step of the computation. User should call `initialize` on the returned iterator. |
### `make_input_fn_iterator`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1900-L1940)
```
make_input_fn_iterator(
input_fn,
replication_mode=tf.distribute.InputReplicationMode.PER_WORKER
)
```
Returns an iterator split across replicas created from an input function.
The `input_fn` should take an [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object where information about batching and input sharding can be accessed:
```
def input_fn(input_context):
batch_size = input_context.get_per_replica_batch_size(global_batch_size)
d = tf.data.Dataset.from_tensors([[1.]]).repeat().batch(batch_size)
return d.shard(input_context.num_input_pipelines,
input_context.input_pipeline_id)
with strategy.scope():
iterator = strategy.make_input_fn_iterator(input_fn)
replica_results = strategy.experimental_run(replica_fn, iterator)
```
The [`tf.data.Dataset`](../../../../data/dataset) returned by `input_fn` should have a per-replica batch size, which may be computed using `input_context.get_per_replica_batch_size`.
| Args |
| `input_fn` | A function taking a [`tf.distribute.InputContext`](../../../../distribute/inputcontext) object and returning a [`tf.data.Dataset`](../../../../data/dataset). |
| `replication_mode` | an enum value of [`tf.distribute.InputReplicationMode`](../../../../distribute/inputreplicationmode). Only `PER_WORKER` is supported currently, which means there will be a single call to `input_fn` per worker. Replicas will dequeue from the local [`tf.data.Dataset`](../../../../data/dataset) on their worker. |
| Returns |
| An iterator object that should first be `.initialize()`-ed. It may then either be passed to `strategy.experimental_run()` or you can `iterator.get_next()` to get the next value to pass to `strategy.extended.call_for_each_replica()`. |
### `reduce`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2012-L2013)
```
reduce(
reduce_op, value, axis=None
)
```
Reduce `value` across replicas and return result on current device.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
total = strategy.reduce("SUM", per_replica_result, axis=None)
total
<tf.Tensor: shape=(), dtype=int32, numpy=1>
```
To see how this would look with multiple replicas, consider the same example with MirroredStrategy with 2 GPUs:
```
strategy = tf.distribute.MirroredStrategy(devices=["GPU:0", "GPU:1"])
def step_fn():
i = tf.distribute.get_replica_context().replica_id_in_sync_group
return tf.identity(i)
per_replica_result = strategy.run(step_fn)
# Check devices on which per replica result is:
strategy.experimental_local_results(per_replica_result)[0].device
# /job:localhost/replica:0/task:0/device:GPU:0
strategy.experimental_local_results(per_replica_result)[1].device
# /job:localhost/replica:0/task:0/device:GPU:1
total = strategy.reduce("SUM", per_replica_result, axis=None)
# Check device on which reduced result is:
total.device
# /job:localhost/replica:0/task:0/device:CPU:0
```
This API is typically used for aggregating the results returned from different replicas, for reporting etc. For example, loss computed from different replicas can be averaged using this API before printing.
>
> **Note:** The result is copied to the "current" device - which would typically be the CPU of the worker on which the program is running. For `TPUStrategy`, it is the first TPU host. For multi client `MultiWorkerMirroredStrategy`, this is CPU of each worker.
>
There are a number of different tf.distribute APIs for reducing values across replicas:
* [`tf.distribute.ReplicaContext.all_reduce`](../../../../distribute/replicacontext#all_reduce): This differs from [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) in that it is for replica context and does not copy the results to the host device. `all_reduce` should be typically used for reductions inside the training step such as gradients.
* [`tf.distribute.StrategyExtended.reduce_to`](../../../../distribute/strategyextended#reduce_to) and [`tf.distribute.StrategyExtended.batch_reduce_to`](../../../../distribute/strategyextended#batch_reduce_to): These APIs are more advanced versions of [`Strategy.reduce`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#reduce) as they allow customizing the destination of the result. They are also called in cross replica context.
*What should axis be?*
Given a per-replica value returned by `run`, say a per-example loss, the batch will be divided across all the replicas. This function allows you to aggregate across replicas and optionally also across batch elements by specifying the axis parameter accordingly.
For example, if you have a global batch size of 8 and 2 replicas, values for examples `[0, 1, 2, 3]` will be on replica 0 and `[4, 5, 6, 7]` will be on replica 1. With `axis=None`, `reduce` will aggregate only across replicas, returning `[0+4, 1+5, 2+6, 3+7]`. This is useful when each replica is computing a scalar or some other value that doesn't have a "batch" dimension (like a gradient or loss).
```
strategy.reduce("sum", per_replica_result, axis=None)
```
Sometimes, you will want to aggregate across both the global batch *and* all replicas. You can get this behavior by specifying the batch dimension as the `axis`, typically `axis=0`. In this case it would return a scalar `0+1+2+3+4+5+6+7`.
```
strategy.reduce("sum", per_replica_result, axis=0)
```
If there is a last partial batch, you will need to specify an axis so that the resulting shape is consistent across replicas. So if the last batch has size 6 and it is divided into [0, 1, 2, 3] and [4, 5], you would get a shape mismatch unless you specify `axis=0`. If you specify [`tf.distribute.ReduceOp.MEAN`](../../../../distribute/reduceop#MEAN), using `axis=0` will use the correct denominator of 6. Contrast this with computing `reduce_mean` to get a scalar value on each replica and this function to average those means, which will weigh some values `1/8` and others `1/4`.
| Args |
| `reduce_op` | a [`tf.distribute.ReduceOp`](../../../../distribute/reduceop) value specifying how values should be combined. Allows using string representation of the enum such as "SUM", "MEAN". |
| `value` | a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) instance, e.g. returned by [`Strategy.run`](https://www.tensorflow.org/api_docs/python/tf/distribute/MirroredStrategy#run), to be combined into a single tensor. It can also be a regular tensor when used with `OneDeviceStrategy` or default strategy. |
| `axis` | specifies the dimension to reduce along within each replica's tensor. Should typically be set to the batch dimension, or `None` to only reduce across replicas (e.g. if the tensor has no batch dimension). |
| Returns |
| A `Tensor`. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L1197-L1312)
```
run(
fn, args=(), kwargs=None, options=None
)
```
Invokes `fn` on each replica, with the given arguments.
This method is the primary way to distribute your computation with a tf.distribute object. It invokes `fn` on each replica. If `args` or `kwargs` have [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), such as those produced by a [`tf.distribute.DistributedDataset`](../../../../distribute/distributeddataset) from [`tf.distribute.Strategy.experimental_distribute_dataset`](../../../../distribute/strategy#experimental_distribute_dataset) or [`tf.distribute.Strategy.distribute_datasets_from_function`](../../../../distribute/strategy#distribute_datasets_from_function), when `fn` is executed on a particular replica, it will be executed with the component of [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) that correspond to that replica.
`fn` is invoked under a replica context. `fn` may call [`tf.distribute.get_replica_context()`](../../../../distribute/get_replica_context) to access members such as `all_reduce`. Please see the module-level docstring of tf.distribute for the concept of replica context.
All arguments in `args` or `kwargs` can be a nested structure of tensors, e.g. a list of tensors, in which case `args` and `kwargs` will be passed to the `fn` invoked on each replica. Or `args` or `kwargs` can be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) containing tensors or composite tensors, i.e. [`tf.compat.v1.TensorInfo.CompositeTensor`](../../tensorinfo/compositetensor), in which case each `fn` call will get the component of a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues) corresponding to its replica. Note that arbitrary Python values that are not of the types above are not supported.
#### Example usage:
1. Constant tensor input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
tensor_input = tf.constant(3.0)
@tf.function
def replica_fn(input):
return input*2.0
result = strategy.run(replica_fn, args=(tensor_input,))
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>,
1: <tf.Tensor: shape=(), dtype=float32, numpy=6.0>
}
```
1. DistributedValues input.
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
@tf.function
def run():
def value_fn(value_context):
return value_context.num_replicas_in_sync
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn2(input):
return input*2
return strategy.run(replica_fn2, args=(distributed_values,))
result = run()
result
<tf.Tensor: shape=(), dtype=int32, numpy=4>
```
1. Use [`tf.distribute.ReplicaContext`](../../../../distribute/replicacontext) to allreduce values.
```
strategy = tf.distribute.MirroredStrategy(["gpu:0", "gpu:1"])
@tf.function
def run():
def value_fn(value_context):
return tf.constant(value_context.replica_id_in_sync_group)
distributed_values = (
strategy.experimental_distribute_values_from_function(
value_fn))
def replica_fn(input):
return tf.distribute.get_replica_context().all_reduce("sum", input)
return strategy.run(replica_fn, args=(distributed_values,))
result = run()
result
PerReplica:{
0: <tf.Tensor: shape=(), dtype=int32, numpy=1>,
1: <tf.Tensor: shape=(), dtype=int32, numpy=1>
}
```
| Args |
| `fn` | The function to run on each replica. |
| `args` | Optional positional arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `kwargs` | Optional keyword arguments to `fn`. Its element can be a tensor, a nested structure of tensors or a [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues). |
| `options` | An optional instance of [`tf.distribute.RunOptions`](../../../../distribute/runoptions) specifying the options to run `fn`. |
| Returns |
| Merged return value of `fn` across replicas. The structure of the return value is the same as the return value from `fn`. Each element in the structure can either be [`tf.distribute.DistributedValues`](../../../../distribute/distributedvalues), `Tensor` objects, or `Tensor`s (for example, if running on a single replica). |
### `scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L863-L955)
```
scope()
```
Context manager to make the strategy current and distribute variables.
This method returns a context manager, and is used as follows:
```
strategy = tf.distribute.MirroredStrategy(["GPU:0", "GPU:1"])
# Variable created inside scope:
with strategy.scope():
mirrored_variable = tf.Variable(1.)
mirrored_variable
MirroredVariable:{
0: <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>,
1: <tf.Variable 'Variable/replica_1:0' shape=() dtype=float32, numpy=1.0>
}
# Variable created outside scope:
regular_variable = tf.Variable(1.)
regular_variable
<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=1.0>
```
*What happens when Strategy.scope is entered?*
* `strategy` is installed in the global context as the "current" strategy. Inside this scope, [`tf.distribute.get_strategy()`](../../../../distribute/get_strategy) will now return this strategy. Outside this scope, it returns the default no-op strategy.
* Entering the scope also enters the "cross-replica context". See [`tf.distribute.StrategyExtended`](../../../../distribute/strategyextended) for an explanation on cross-replica and replica contexts.
* Variable creation inside `scope` is intercepted by the strategy. Each strategy defines how it wants to affect the variable creation. Sync strategies like `MirroredStrategy`, `TPUStrategy` and `MultiWorkerMiroredStrategy` create variables replicated on each replica, whereas `ParameterServerStrategy` creates variables on the parameter servers. This is done using a custom [`tf.variable_creator_scope`](../../../../variable_creator_scope).
* In some strategies, a default device scope may also be entered: in `MultiWorkerMiroredStrategy`, a default device scope of "/CPU:0" is entered on each worker.
>
> **Note:** Entering a scope does not automatically distribute a computation, except in the case of high level training framework like keras `model.fit`. If you're not using `model.fit`, you need to use `strategy.run` API to explicitly distribute that computation. See an example in the [custom training loop tutorial](https://www.tensorflow.org/tutorials/distribute/custom_training).
>
*What should be in scope and what should be outside?*
There are a number of requirements on what needs to happen inside the scope. However, in places where we have information about which strategy is in use, we often enter the scope for the user, so they don't have to do it explicitly (i.e. calling those either inside or outside the scope is OK).
* Anything that creates variables that should be distributed variables must be called in a `strategy.scope`. This can be accomplished either by directly calling the variable creating function within the scope context, or by relying on another API like `strategy.run` or [`keras.Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) to automatically enter it for you. Any variable that is created outside scope will not be distributed and may have performance implications. Some common objects that create variables in TF are Models, Optimizers, Metrics. Such objects should always be initialized in the scope, and any functions that may lazily create variables (e.g., `Model.__call__()`, tracing a [`tf.function`](../../../../function), etc.) should similarly be called within scope. Another source of variable creation can be a checkpoint restore - when variables are created lazily. Note that any variable created inside a strategy captures the strategy information. So reading and writing to these variables outside the `strategy.scope` can also work seamlessly, without the user having to enter the scope.
* Some strategy APIs (such as `strategy.run` and `strategy.reduce`) which require to be in a strategy's scope, enter the scope automatically, which means when using those APIs you don't need to explicitly enter the scope yourself.
* When a [`tf.keras.Model`](../../../../keras/model) is created inside a `strategy.scope`, the Model object captures the scope information. When high level training framework methods such as `model.compile`, `model.fit`, etc. are then called, the captured scope will be automatically entered, and the associated strategy will be used to distribute the training etc. See a detailed example in [distributed keras tutorial](https://www.tensorflow.org/tutorials/distribute/keras). WARNING: Simply calling `model(..)` does not automatically enter the captured scope -- only high level training framework APIs support this behavior: `model.compile`, `model.fit`, `model.evaluate`, `model.predict` and `model.save` can all be called inside or outside the scope.
* The following can be either inside or outside the scope:
+ Creating the input datasets
+ Defining [`tf.function`](../../../../function)s that represent your training step
+ Saving APIs such as [`tf.saved_model.save`](../../../../saved_model/save). Loading creates variables, so that should go inside the scope if you want to train the model in a distributed way.
+ Checkpoint saving. As mentioned above - `checkpoint.restore` may sometimes need to be inside scope if it creates variables.
| Returns |
| A context manager. |
### `update_config_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/distribute/distribute_lib.py#L2017-L2032)
```
update_config_proto(
config_proto
)
```
Returns a copy of `config_proto` modified for use with this strategy.
The updated config has something needed to run a strategy, e.g. configuration to run collective ops, or device filters to improve distributed training performance.
| Args |
| `config_proto` | a `tf.ConfigProto` object. |
| Returns |
| The updated copy of the `config_proto`. |
| programming_docs |
tensorflow tf.compat.v1.SummaryMetadata.PluginData tf.compat.v1.SummaryMetadata.PluginData
=======================================
A ProtocolMessage
| Attributes |
| `content` | `bytes content` |
| `plugin_name` | `string plugin_name` |
tensorflow tf.compat.v1.train.input_producer tf.compat.v1.train.input\_producer
==================================
Output the rows of `input_tensor` to a queue for an input pipeline. (deprecated)
```
tf.compat.v1.train.input_producer(
input_tensor,
element_shape=None,
num_epochs=None,
shuffle=True,
seed=None,
capacity=32,
shared_name=None,
summary_name=None,
name=None,
cancel_op=None
)
```
>
> **Note:** if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables.
>
| Args |
| `input_tensor` | A tensor with the rows to produce. Must be at least one-dimensional. Must either have a fully-defined shape, or `element_shape` must be defined. |
| `element_shape` | (Optional.) A `TensorShape` representing the shape of a row of `input_tensor`, if it cannot be inferred. |
| `num_epochs` | (Optional.) An integer. If specified `input_producer` produces each row of `input_tensor` `num_epochs` times before generating an `OutOfRange` error. If not specified, `input_producer` can cycle through the rows of `input_tensor` an unlimited number of times. |
| `shuffle` | (Optional.) A boolean. If true, the rows are randomly shuffled within each epoch. |
| `seed` | (Optional.) An integer. The seed to use if `shuffle` is true. |
| `capacity` | (Optional.) The capacity of the queue to be used for buffering the input. |
| `shared_name` | (Optional.) If set, this queue will be shared under the given name across multiple sessions. |
| `summary_name` | (Optional.) If set, a scalar summary for the current queue size will be generated, using this name as part of the tag. |
| `name` | (Optional.) A name for queue. |
| `cancel_op` | (Optional.) Cancel op for the queue |
| Returns |
| A queue with the output rows. A `QueueRunner` for the queue is added to the current `QUEUE_RUNNER` collection of the current graph. |
| Raises |
| `ValueError` | If the shape of the input cannot be inferred from the arguments. |
| `RuntimeError` | If called with eager execution enabled. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.string_input_producer tf.compat.v1.train.string\_input\_producer
==========================================
Output strings (e.g. filenames) to a queue for an input pipeline. (deprecated)
```
tf.compat.v1.train.string_input_producer(
string_tensor,
num_epochs=None,
shuffle=True,
seed=None,
capacity=32,
shared_name=None,
name=None,
cancel_op=None
)
```
>
> **Note:** if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables.
>
| Args |
| `string_tensor` | A 1-D string tensor with the strings to produce. |
| `num_epochs` | An integer (optional). If specified, `string_input_producer` produces each string from `string_tensor` `num_epochs` times before generating an `OutOfRange` error. If not specified, `string_input_producer` can cycle through the strings in `string_tensor` an unlimited number of times. |
| `shuffle` | Boolean. If true, the strings are randomly shuffled within each epoch. |
| `seed` | An integer (optional). Seed used if shuffle == True. |
| `capacity` | An integer. Sets the queue capacity. |
| `shared_name` | (optional). If set, this queue will be shared under the given name across multiple sessions. All sessions open to the device which has this queue will be able to access it via the shared\_name. Using this in a distributed setting means each name will only be seen by one of the sessions which has access to this operation. |
| `name` | A name for the operations (optional). |
| `cancel_op` | Cancel op for the queue (optional). |
| Returns |
| A queue with the output strings. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. |
| Raises |
| `ValueError` | If the string\_tensor is a null Python list. At runtime, will fail with an assertion if string\_tensor becomes a null tensor. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.ProximalGradientDescentOptimizer tf.compat.v1.train.ProximalGradientDescentOptimizer
===================================================
Optimizer that implements the proximal gradient descent algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.ProximalGradientDescentOptimizer(
learning_rate,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0,
use_locking=False,
name='ProximalGradientDescent'
)
```
#### References:
Efficient Learning using Forward-Backward Splitting: [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting) ([pdf](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf))
| 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". |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.maybe_batch tf.compat.v1.train.maybe\_batch
===============================
Conditionally creates batches of tensors based on `keep_input`. (deprecated)
```
tf.compat.v1.train.maybe_batch(
tensors,
keep_input,
batch_size,
num_threads=1,
capacity=32,
enqueue_many=False,
shapes=None,
dynamic_pad=False,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
See docstring in `batch` for more details.
| Args |
| `tensors` | The list or dictionary of tensors to enqueue. |
| `keep_input` | A `bool` Tensor. This tensor controls whether the input is added to the queue or not. If it is a scalar and evaluates `True`, then `tensors` are all added to the queue. If it is a vector and `enqueue_many` is `True`, then each example is added to the queue only if the corresponding value in `keep_input` is `True`. This tensor essentially acts as a filtering mechanism. |
| `batch_size` | The new batch size pulled from the queue. |
| `num_threads` | The number of threads enqueuing `tensors`. The batching will be nondeterministic if `num_threads > 1`. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `enqueue_many` | Whether each tensor in `tensors` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors`. |
| `dynamic_pad` | Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same types as `tensors`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`. |
tensorflow tf.compat.v1.train.limit_epochs tf.compat.v1.train.limit\_epochs
================================
Returns tensor `num_epochs` times and then raises an `OutOfRange` error. (deprecated)
```
tf.compat.v1.train.limit_epochs(
tensor, num_epochs=None, name=None
)
```
>
> **Note:** creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables.
>
| Args |
| `tensor` | Any `Tensor`. |
| `num_epochs` | A positive integer (optional). If specified, limits the number of steps the output tensor may be evaluated. |
| `name` | A name for the operations (optional). |
| Returns |
| tensor or `OutOfRange`. |
| Raises |
| `ValueError` | if `num_epochs` is invalid. |
tensorflow tf.compat.v1.train.do_quantize_training_on_graphdef tf.compat.v1.train.do\_quantize\_training\_on\_graphdef
=======================================================
A general quantization scheme is being developed in `tf.contrib.quantize`. (deprecated)
```
tf.compat.v1.train.do_quantize_training_on_graphdef(
input_graph, num_bits
)
```
Consider using that instead, though since it is in the tf.contrib namespace, it is not subject to backward compatibility guarantees.
| Args |
| `input_graph` | A `GraphDef`. |
| `num_bits` | The number of bits for quantize training. |
| Returns |
| The graph with quantize training done. |
tensorflow tf.compat.v1.train.shuffle_batch_join tf.compat.v1.train.shuffle\_batch\_join
=======================================
Create batches by randomly shuffling tensors. (deprecated)
```
tf.compat.v1.train.shuffle_batch_join(
tensors_list,
batch_size,
capacity,
min_after_dequeue,
seed=None,
enqueue_many=False,
shapes=None,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
The `tensors_list` argument is a list of tuples of tensors, or a list of dictionaries of tensors. Each element in the list is treated similarly to the `tensors` argument of [`tf.compat.v1.train.shuffle_batch()`](shuffle_batch).
This version enqueues a different list of tensors in different threads. It adds the following to the current `Graph`:
* A shuffling queue into which tensors from `tensors_list` are enqueued.
* A `dequeue_many` operation to create batches from the queue.
* A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors from `tensors_list`.
`len(tensors_list)` threads will be started, with thread `i` enqueuing the tensors from `tensors_list[i]`. `tensors_list[i1][j]` must match `tensors_list[i2][j]` in type and shape, except in the first dimension if `enqueue_many` is true.
If `enqueue_many` is `False`, each `tensors_list[i]` is assumed to represent a single example. An input tensor with shape `[x, y, z]` will be output as a tensor with shape `[batch_size, x, y, z]`.
If `enqueue_many` is `True`, `tensors_list[i]` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors_list[i]` should have the same size in the first dimension. If an input tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, y, z]`.
The `capacity` argument controls the how long the prefetching is allowed to grow the queues.
The returned operation is a dequeue operation and will throw [`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself.
If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `shape` property will have a first `Dimension` value of `None`, and operations that depend on fixed batch\_size would fail.
| Args |
| `tensors_list` | A list of tuples or dictionaries of tensors to enqueue. |
| `batch_size` | An integer. The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `min_after_dequeue` | Minimum number elements in the queue after a dequeue, used to ensure a level of mixing of elements. |
| `seed` | Seed for the random shuffling within the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors_list[i]`. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same number and types as `tensors_list[i]`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors_list`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
| programming_docs |
tensorflow tf.compat.v1.train.linear_cosine_decay tf.compat.v1.train.linear\_cosine\_decay
========================================
Applies linear cosine decay to the learning rate.
```
tf.compat.v1.train.linear_cosine_decay(
learning_rate,
global_step,
decay_steps,
num_periods=0.5,
alpha=0.0,
beta=0.001,
name=None
)
```
Note that linear cosine decay is more aggressive than cosine decay and larger initial learning rates can typically be used.
When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies a linear cosine 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:
```
global_step = min(global_step, decay_steps)
linear_decay = (decay_steps - global_step) / decay_steps)
cosine_decay = 0.5 * (
1 + cos(pi * 2 * num_periods * global_step / decay_steps))
decayed = (alpha + linear_decay) * cosine_decay + beta
decayed_learning_rate = learning_rate * decayed
```
#### Example usage:
```
decay_steps = 1000
lr_decayed = linear_cosine_decay(learning_rate, global_step, decay_steps)
```
| 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. |
| `decay_steps` | A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. |
| `num_periods` | Number of periods in the cosine part of the decay. See computation above. |
| `alpha` | See computation above. |
| `beta` | See computation above. |
| `name` | String. Optional name of the operation. Defaults to 'LinearCosineDecay'. |
| Returns |
| A scalar `Tensor` of the same type as `learning_rate`. The decayed learning rate. |
| Raises |
| `ValueError` | if `global_step` is not supplied. |
#### References:
Neural Optimizer Search with Reinforcement Learning: [Bello et al., 2017](http://proceedings.mlr.press/v70/bello17a.html) ([pdf](http://proceedings.mlr.press/v70/bello17a/bello17a.pdf)) Stochastic Gradient Descent with Warm Restarts: [Loshchilov et al., 2017](https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) ([pdf](https://openreview.net/pdf?id=Skq89Scxx))
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.batch_join tf.compat.v1.train.batch\_join
==============================
Runs a list of tensors to fill a queue to create batches of examples. (deprecated)
```
tf.compat.v1.train.batch_join(
tensors_list,
batch_size,
capacity=32,
enqueue_many=False,
shapes=None,
dynamic_pad=False,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
The `tensors_list` argument is a list of tuples of tensors, or a list of dictionaries of tensors. Each element in the list is treated similarly to the `tensors` argument of [`tf.compat.v1.train.batch()`](batch).
Enqueues a different list of tensors in different threads. Implemented using a queue -- a `QueueRunner` for the queue is added to the current `Graph`'s `QUEUE_RUNNER` collection.
`len(tensors_list)` threads will be started, with thread `i` enqueuing the tensors from `tensors_list[i]`. `tensors_list[i1][j]` must match `tensors_list[i2][j]` in type and shape, except in the first dimension if `enqueue_many` is true.
If `enqueue_many` is `False`, each `tensors_list[i]` is assumed to represent a single example. An input tensor `x` will be output as a tensor with shape `[batch_size] + x.shape`.
If `enqueue_many` is `True`, `tensors_list[i]` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors_list[i]` should have the same size in the first dimension. The slices of any input tensor `x` are treated as examples, and the output tensors will have shape `[batch_size] + x.shape[1:]`.
The `capacity` argument controls the how long the prefetching is allowed to grow the queues.
The returned operation is a dequeue operation and will throw [`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself.
>
> **Note:** If `dynamic_pad` is `False`, you must ensure that either (i) the `shapes` argument is passed, or (ii) all of the tensors in `tensors_list` must have fully-defined shapes. `ValueError` will be raised if neither of these conditions holds.
>
If `dynamic_pad` is `True`, it is sufficient that the *rank* of the tensors is known, but individual dimensions may have value `None`. In this case, for each enqueue the dimensions with value `None` may have a variable length; upon dequeue, the output tensors will be padded on the right to the maximum shape of the tensors in the current minibatch. For numbers, this padding takes value 0. For strings, this padding is the empty string. See `PaddingFIFOQueue` for more info.
If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `shape` property will have a first `Dimension` value of `None`, and operations that depend on fixed batch\_size would fail.
| Args |
| `tensors_list` | A list of tuples or dictionaries of tensors to enqueue. |
| `batch_size` | An integer. The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensor_list_list[i]`. |
| `dynamic_pad` | Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional) If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same number and types as `tensors_list[i]`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensor_list_list`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.shuffle_batch tf.compat.v1.train.shuffle\_batch
=================================
Creates batches by randomly shuffling tensors. (deprecated)
```
tf.compat.v1.train.shuffle_batch(
tensors,
batch_size,
capacity,
min_after_dequeue,
num_threads=1,
seed=None,
enqueue_many=False,
shapes=None,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
This function adds the following to the current `Graph`:
* A shuffling queue into which tensors from `tensors` are enqueued.
* A `dequeue_many` operation to create batches from the queue.
* A `QueueRunner` to `QUEUE_RUNNER` collection, to enqueue the tensors from `tensors`.
If `enqueue_many` is `False`, `tensors` is assumed to represent a single example. An input tensor with shape `[x, y, z]` will be output as a tensor with shape `[batch_size, x, y, z]`.
If `enqueue_many` is `True`, `tensors` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors` should have the same size in the first dimension. If an input tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, y, z]`.
The `capacity` argument controls the how long the prefetching is allowed to grow the queues.
The returned operation is a dequeue operation and will throw [`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself.
#### For example:
```
# Creates batches of 32 images and 32 labels.
image_batch, label_batch = tf.compat.v1.train.shuffle_batch(
[single_image, single_label],
batch_size=32,
num_threads=4,
capacity=50000,
min_after_dequeue=10000)
```
>
> **Note:** You must ensure that either (i) the `shapes` argument is passed, or (ii) all of the tensors in `tensors` must have fully-defined shapes. `ValueError` will be raised if neither of these conditions holds.
>
If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `shape` property will have a first `Dimension` value of `None`, and operations that depend on fixed batch\_size would fail.
| Args |
| `tensors` | The list or dictionary of tensors to enqueue. |
| `batch_size` | The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `min_after_dequeue` | Minimum number elements in the queue after a dequeue, used to ensure a level of mixing of elements. |
| `num_threads` | The number of threads enqueuing `tensor_list`. |
| `seed` | Seed for the random shuffling within the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensor_list`. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional) If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the types as `tensors`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.Scaffold tf.compat.v1.train.Scaffold
===========================
Structure to create or gather pieces commonly needed to train a model.
```
tf.compat.v1.train.Scaffold(
init_op=None,
init_feed_dict=None,
init_fn=None,
ready_op=None,
ready_for_local_init_op=None,
local_init_op=None,
summary_op=None,
saver=None,
copy_from_scaffold=None,
local_init_feed_dict=None
)
```
When you build a model for training you usually need ops to initialize variables, a `Saver` to checkpoint them, an op to collect summaries for the visualizer, and so on.
Various libraries built on top of the core TensorFlow library take care of creating some or all of these pieces and storing them in well known collections in the graph. The `Scaffold` class helps pick these pieces from the graph collections, creating and adding them to the collections if needed.
If you call the scaffold constructor without any arguments, it will pick pieces from the collections, creating default ones if needed when `scaffold.finalize()` is called. You can pass arguments to the constructor to provide your own pieces. Pieces that you pass to the constructor are not added to the graph collections.
The following pieces are directly accessible as attributes of the `Scaffold` object:
* `saver`: A [`tf.compat.v1.train.Saver`](saver) object taking care of saving the variables. Picked from and stored into the `SAVERS` collection in the graph by default.
* `init_op`: An op to run to initialize the variables. Picked from and stored into the `INIT_OP` collection in the graph by default.
* `ready_op`: An op to verify that the variables are initialized. Picked from and stored into the `READY_OP` collection in the graph by default.
* `ready_for_local_init_op`: An op to verify that global state has been initialized and it is alright to run `local_init_op`. Picked from and stored into the `READY_FOR_LOCAL_INIT_OP` collection in the graph by default. This is needed when the initialization of local variables depends on the values of global variables.
* `local_init_op`: An op to initialize the local variables. Picked from and stored into the `LOCAL_INIT_OP` collection in the graph by default.
* `summary_op`: An op to run and merge the summaries in the graph. Picked from and stored into the `SUMMARY_OP` collection in the graph by default.
You can also pass the following additional pieces to the constructor:
* `init_feed_dict`: A session feed dictionary that should be used when running the init op.
* `init_fn`: A callable to run after the init op to perform additional initializations. The callable will be called as `init_fn(scaffold, session)`.
| Args |
| `init_op` | Optional op for initializing variables. |
| `init_feed_dict` | Optional session feed dictionary to use when running the init\_op. |
| `init_fn` | Optional function to use to initialize the model after running the init\_op. Will be called as `init_fn(scaffold, session)`. |
| `ready_op` | Optional op to verify that the variables are initialized. Must return an empty 1D string tensor when the variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized variables. |
| `ready_for_local_init_op` | Optional op to verify that the global variables are initialized and `local_init_op` can be run. Must return an empty 1D string tensor when the global variables are initialized, or a non-empty 1D string tensor listing the names of the non-initialized global variables. |
| `local_init_op` | Optional op to initialize local variables. |
| `summary_op` | Optional op to gather all summaries. Must return a scalar string tensor containing a serialized `Summary` proto. |
| `saver` | Optional [`tf.compat.v1.train.Saver`](saver) object to use to save and restore variables. May also be a [`tf.train.Checkpoint`](../../../train/checkpoint) object, in which case object-based checkpoints are saved. This will also load some object-based checkpoints saved from elsewhere, but that loading may be fragile since it uses fixed keys rather than performing a full graph-based match. For example if a variable has two paths from the `Checkpoint` object because two `Model` objects share the `Layer` object that owns it, removing one `Model` may change the keys and break checkpoint loading through this API, whereas a graph-based match would match the variable through the other `Model`. |
| `copy_from_scaffold` | Optional scaffold object to copy fields from. Its fields will be overwritten by the provided fields in this function. |
| `local_init_feed_dict` | Optional session feed dictionary to use when running the local\_init\_op. |
| Attributes |
| `init_feed_dict` | |
| `init_fn` | |
| `init_op` | |
| `local_init_feed_dict` | |
| `local_init_op` | |
| `ready_for_local_init_op` | |
| `ready_op` | |
| `saver` | |
| `summary_op` | |
Methods
-------
### `default_local_init_op`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L299-L315)
```
@staticmethod
default_local_init_op()
```
Returns an op that groups the default local init ops.
This op is used during session initialization when a Scaffold is initialized without specifying the local\_init\_op arg. It includes [`tf.compat.v1.local_variables_initializer`](../local_variables_initializer), [`tf.compat.v1.tables_initializer`](../tables_initializer), and also initializes local session resources.
| Returns |
| The default Scaffold local init op. |
### `finalize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L186-L244)
```
finalize()
```
Creates operations if needed and finalizes the graph.
### `get_or_default`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L282-L297)
```
@staticmethod
get_or_default(
arg_name, collection_key, default_constructor
)
```
Get from cache or create a default operation.
tensorflow Module: tf.compat.v1.train.queue_runner Module: tf.compat.v1.train.queue\_runner
========================================
Public API for tf.train.queue\_runner namespace.
Classes
-------
[`class QueueRunner`](queuerunner): Holds a list of enqueue operations for a queue, each to be run in a thread.
Functions
---------
[`add_queue_runner(...)`](add_queue_runner): Adds a `QueueRunner` to a collection in the graph. (deprecated)
[`start_queue_runners(...)`](start_queue_runners): Starts all queue runners collected in the graph. (deprecated)
tensorflow tf.compat.v1.train.exponential_decay tf.compat.v1.train.exponential\_decay
=====================================
Applies exponential decay to the learning rate.
```
tf.compat.v1.train.exponential_decay(
learning_rate,
global_step,
decay_steps,
decay_rate,
staircase=False,
name=None
)
```
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:
```
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:
```
...
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
learning_rate = tf.compat.v1.train.exponential_decay(starter_learning_rate,
global_step,
100000, 0.96, staircase=True)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.compat.v1.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step)
)
```
| 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. |
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
| programming_docs |
tensorflow tf.compat.v1.train.maybe_shuffle_batch_join tf.compat.v1.train.maybe\_shuffle\_batch\_join
==============================================
Create batches by randomly shuffling conditionally-enqueued tensors. (deprecated)
```
tf.compat.v1.train.maybe_shuffle_batch_join(
tensors_list,
batch_size,
capacity,
min_after_dequeue,
keep_input,
seed=None,
enqueue_many=False,
shapes=None,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
See docstring in `shuffle_batch_join` for more details.
| Args |
| `tensors_list` | A list of tuples or dictionaries of tensors to enqueue. |
| `batch_size` | An integer. The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `min_after_dequeue` | Minimum number elements in the queue after a dequeue, used to ensure a level of mixing of elements. |
| `keep_input` | A `bool` Tensor. This tensor controls whether the input is added to the queue or not. If it is a scalar and evaluates `True`, then `tensors` are all added to the queue. If it is a vector and `enqueue_many` is `True`, then each example is added to the queue only if the corresponding value in `keep_input` is `True`. This tensor essentially acts as a filtering mechanism. |
| `seed` | Seed for the random shuffling within the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors_list[i]`. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same number and types as `tensors_list[i]`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors_list`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.slice_input_producer tf.compat.v1.train.slice\_input\_producer
=========================================
Produces a slice of each `Tensor` in `tensor_list`. (deprecated)
```
tf.compat.v1.train.slice_input_producer(
tensor_list,
num_epochs=None,
shuffle=True,
seed=None,
capacity=32,
shared_name=None,
name=None
)
```
Implemented using a Queue -- a `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection.
| Args |
| `tensor_list` | A list of `Tensor` objects. Every `Tensor` in `tensor_list` must have the same size in the first dimension. |
| `num_epochs` | An integer (optional). If specified, `slice_input_producer` produces each slice `num_epochs` times before generating an `OutOfRange` error. If not specified, `slice_input_producer` can cycle through the slices an unlimited number of times. |
| `shuffle` | Boolean. If true, the integers are randomly shuffled within each epoch. |
| `seed` | An integer (optional). Seed used if shuffle == True. |
| `capacity` | An integer. Sets the queue capacity. |
| `shared_name` | (optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | A name for the operations (optional). |
| Returns |
| A list of tensors, one for each element of `tensor_list`. If the tensor in `tensor_list` has shape `[N, a, b, .., z]`, then the corresponding output tensor will have shape `[a, b, ..., z]`. |
| Raises |
| `ValueError` | if `slice_input_producer` produces nothing from `tensor_list`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.ChiefSessionCreator tf.compat.v1.train.ChiefSessionCreator
======================================
Creates a tf.compat.v1.Session for a chief.
Inherits From: [`SessionCreator`](sessioncreator)
```
tf.compat.v1.train.ChiefSessionCreator(
scaffold=None,
master='',
config=None,
checkpoint_dir=None,
checkpoint_filename_with_path=None
)
```
| Args |
| `scaffold` | A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. |
| `master` | `String` representation of the TensorFlow master to use. |
| `config` | `ConfigProto` proto used to configure the session. |
| `checkpoint_dir` | A string. Optional path to a directory where to restore variables. |
| `checkpoint_filename_with_path` | Full file name path to the checkpoint file. |
Methods
-------
### `create_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L667-L677)
```
create_session()
```
tensorflow tf.compat.v1.train.remove_checkpoint tf.compat.v1.train.remove\_checkpoint
=====================================
Removes a checkpoint given by `checkpoint_prefix`. (deprecated)
```
tf.compat.v1.train.remove_checkpoint(
checkpoint_prefix,
checkpoint_format_version=saver_pb2.SaverDef.V2,
meta_graph_suffix='meta'
)
```
| Args |
| `checkpoint_prefix` | The prefix of a V1 or V2 checkpoint. Typically the result of `Saver.save()` or that of [`tf.train.latest_checkpoint()`](../../../train/latest_checkpoint), regardless of sharded/non-sharded or V1/V2. |
| `checkpoint_format_version` | `SaverDef.CheckpointFormatVersion`, defaults to `SaverDef.V2`. |
| `meta_graph_suffix` | Suffix for `MetaGraphDef` file. Defaults to 'meta'. |
tensorflow tf.compat.v1.train.maybe_batch_join tf.compat.v1.train.maybe\_batch\_join
=====================================
Runs a list of tensors to conditionally fill a queue to create batches. (deprecated)
```
tf.compat.v1.train.maybe_batch_join(
tensors_list,
keep_input,
batch_size,
capacity=32,
enqueue_many=False,
shapes=None,
dynamic_pad=False,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
See docstring in `batch_join` for more details.
| Args |
| `tensors_list` | A list of tuples or dictionaries of tensors to enqueue. |
| `keep_input` | A `bool` Tensor. This tensor controls whether the input is added to the queue or not. If it is a scalar and evaluates `True`, then `tensors` are all added to the queue. If it is a vector and `enqueue_many` is `True`, then each example is added to the queue only if the corresponding value in `keep_input` is `True`. This tensor essentially acts as a filtering mechanism. |
| `batch_size` | An integer. The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensor_list_list[i]`. |
| `dynamic_pad` | Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional) If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same number and types as `tensors_list[i]`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensor_list_list`. |
tensorflow tf.compat.v1.train.basic_train_loop tf.compat.v1.train.basic\_train\_loop
=====================================
Basic loop to train a model.
```
tf.compat.v1.train.basic_train_loop(
supervisor, train_step_fn, args=None, kwargs=None, master=''
)
```
Calls `train_step_fn` in a loop to train a model. The function is called as:
```
train_step_fn(session, *args, **kwargs)
```
It is passed a [`tf.compat.v1.Session`](../session) in addition to `args` and `kwargs`. The function typically runs one training step in the session.
| Args |
| `supervisor` | [`tf.compat.v1.train.Supervisor`](supervisor) to run the training services. |
| `train_step_fn` | Callable to execute one training step. Called repeatedly as `train_step_fn(session, *args **kwargs)`. |
| `args` | Optional positional arguments passed to `train_step_fn`. |
| `kwargs` | Optional keyword arguments passed to `train_step_fn`. |
| `master` | Master to use to create the training session. Defaults to `""` which causes the session to be created in the local process. |
tensorflow tf.compat.v1.train.piecewise_constant tf.compat.v1.train.piecewise\_constant
======================================
Piecewise constant from boundaries and interval values.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.piecewise_constant_decay`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/piecewise_constant)
```
tf.compat.v1.train.piecewise_constant(
x, boundaries, values, name=None
)
```
Example: use a learning rate that's 1.0 for the first 100001 steps, 0.5 for the next 10000 steps, and 0.1 for any additional steps.
```
global_step = tf.Variable(0, trainable=False)
boundaries = [100000, 110000]
values = [1.0, 0.5, 0.1]
learning_rate = tf.compat.v1.train.piecewise_constant(global_step, 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: `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`. |
| `boundaries` | A list of `Tensor`s or `int`s or `float`s with strictly increasing entries, and with all elements having the same type as `x`. |
| `values` | A list of `Tensor`s or `float`s or `int`s that specifies the values for the intervals defined by `boundaries`. It should have one more element than `boundaries`, 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] when `x > boundaries[-1]`. |
| Raises |
| `ValueError` | if types of `x` and `boundaries` do not match, or types of all `values` do not match or the number of elements in the lists does not match. |
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.generate_checkpoint_state_proto tf.compat.v1.train.generate\_checkpoint\_state\_proto
=====================================================
Generates a checkpoint state proto.
```
tf.compat.v1.train.generate_checkpoint_state_proto(
save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None,
all_model_checkpoint_timestamps=None,
last_preserved_timestamp=None
)
```
| Args |
| `save_dir` | Directory where the model was saved. |
| `model_checkpoint_path` | The checkpoint file. |
| `all_model_checkpoint_paths` | List of strings. Paths to all not-yet-deleted checkpoints, sorted from oldest to newest. If this is a non-empty list, the last element must be equal to model\_checkpoint\_path. These paths are also saved in the CheckpointState proto. |
| `all_model_checkpoint_timestamps` | A list of floats, indicating the number of seconds since the Epoch when each checkpoint was generated. |
| `last_preserved_timestamp` | A float, indicating the number of seconds since the Epoch when the last preserved checkpoint was written, e.g. due to a `keep_checkpoint_every_n_hours` parameter (see [`tf.train.CheckpointManager`](../../../train/checkpointmanager) for an implementation). |
| Returns |
| CheckpointState proto with model\_checkpoint\_path and all\_model\_checkpoint\_paths updated to either absolute paths or relative paths to the current save\_dir. |
| Raises |
| `ValueError` | If `all_model_checkpoint_timestamps` was provided but its length does not match `all_model_checkpoint_paths`. |
tensorflow tf.compat.v1.train.range_input_producer tf.compat.v1.train.range\_input\_producer
=========================================
Produces the integers from 0 to limit-1 in a queue. (deprecated)
```
tf.compat.v1.train.range_input_producer(
limit,
num_epochs=None,
shuffle=True,
seed=None,
capacity=32,
shared_name=None,
name=None
)
```
>
> **Note:** if `num_epochs` is not `None`, this function creates local counter `epochs`. Use `local_variables_initializer()` to initialize local variables.
>
| Args |
| `limit` | An int32 scalar tensor. |
| `num_epochs` | An integer (optional). If specified, `range_input_producer` produces each integer `num_epochs` times before generating an OutOfRange error. If not specified, `range_input_producer` can cycle through the integers an unlimited number of times. |
| `shuffle` | Boolean. If true, the integers are randomly shuffled within each epoch. |
| `seed` | An integer (optional). Seed used if shuffle == True. |
| `capacity` | An integer. Sets the queue capacity. |
| `shared_name` | (optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | A name for the operations (optional). |
| Returns |
| A Queue with the output integers. A `QueueRunner` for the Queue is added to the current `Graph`'s `QUEUE_RUNNER` collection. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.AdagradDAOptimizer tf.compat.v1.train.AdagradDAOptimizer
=====================================
Adagrad Dual Averaging algorithm for sparse linear models.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.AdagradDAOptimizer(
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'
)
```
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.
#### References:
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization :[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf))
| 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. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
| programming_docs |
tensorflow tf.compat.v1.train.add_queue_runner tf.compat.v1.train.add\_queue\_runner
=====================================
Adds a `QueueRunner` to a collection in the graph. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.queue_runner.add_queue_runner`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/add_queue_runner)
```
tf.compat.v1.train.add_queue_runner(
qr, collection=ops.GraphKeys.QUEUE_RUNNERS
)
```
Migrate to TF2
--------------
QueueRunners are not compatible with eager execution. Instead, please use [tf.data](https://www.tensorflow.org/guide/data) to get data into your model.
Description
-----------
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`. |
tensorflow tf.compat.v1.train.MonitoredTrainingSession tf.compat.v1.train.MonitoredTrainingSession
===========================================
Creates a `MonitoredSession` for training.
```
tf.compat.v1.train.MonitoredTrainingSession(
master='',
is_chief=True,
checkpoint_dir=None,
scaffold=None,
hooks=None,
chief_only_hooks=None,
save_checkpoint_secs=USE_DEFAULT,
save_summaries_steps=USE_DEFAULT,
save_summaries_secs=USE_DEFAULT,
config=None,
stop_grace_period_secs=120,
log_step_count_steps=100,
max_wait_secs=7200,
save_checkpoint_steps=USE_DEFAULT,
summary_dir=None,
save_graph_def=True
)
```
Migrate to TF2
--------------
This API is not compatible with eager execution and [`tf.function`](../../../function). To migrate to TF2, rewrite the code to be compatible with eager execution. Check the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls. In Keras, session hooks can be replaced by Callbacks e.g. [logging hook notebook](https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) For more details please read [Better performance with tf.function](https://www.tensorflow.org/guide/function).
Description
-----------
For a chief, this utility sets proper session initializer/restorer. It also creates hooks related to checkpoint and summary saving. For workers, this utility sets proper session creator which waits for the chief to initialize/restore. Please check [`tf.compat.v1.train.MonitoredSession`](monitoredsession) for more information.
| Args |
| `master` | `String` the TensorFlow master to use. |
| `is_chief` | If `True`, it will take care of initialization and recovery the underlying TensorFlow session. If `False`, it will wait on a chief to initialize or recover the TensorFlow session. |
| `checkpoint_dir` | A string. Optional path to a directory where to restore variables. |
| `scaffold` | A `Scaffold` used for gathering or building supportive ops. If not specified, a default one is created. It's used to finalize the graph. |
| `hooks` | Optional list of `SessionRunHook` objects. |
| `chief_only_hooks` | list of `SessionRunHook` objects. Activate these hooks if `is_chief==True`, ignore otherwise. |
| `save_checkpoint_secs` | The frequency, in seconds, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default 600. |
| `save_summaries_steps` | The frequency, in number of global steps, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default 100. |
| `save_summaries_secs` | The frequency, in secs, that the summaries are written to disk using a default summary saver. If both `save_summaries_steps` and `save_summaries_secs` are set to `None`, then the default summary saver isn't used. Default not enabled. |
| `config` | an instance of [`tf.compat.v1.ConfigProto`](../configproto) proto used to configure the session. It's the `config` argument of constructor of [`tf.compat.v1.Session`](../session). |
| `stop_grace_period_secs` | Number of seconds given to threads to stop after `close()` has been called. |
| `log_step_count_steps` | The frequency, in number of global steps, that the global step/sec is logged. |
| `max_wait_secs` | Maximum time workers should wait for the session to become available. This should be kept relatively short to help detect incorrect code, but sometimes may need to be increased if the chief takes a while to start up. |
| `save_checkpoint_steps` | The frequency, in number of global steps, that a checkpoint is saved using a default checkpoint saver. If both `save_checkpoint_steps` and `save_checkpoint_secs` are set to `None`, then the default checkpoint saver isn't used. If both are provided, then only `save_checkpoint_secs` is used. Default not enabled. |
| `summary_dir` | A string. Optional path to a directory where to save summaries. If None, checkpoint\_dir is used instead. |
| `save_graph_def` | Whether to save the GraphDef and MetaGraphDef to `checkpoint_dir`. The GraphDef is saved after the session is created as `graph.pbtxt`. MetaGraphDefs are saved out for every checkpoint as `model.ckpt-*.meta`. |
| Returns |
| A `MonitoredSession` object. |
tensorflow tf.compat.v1.train.Optimizer tf.compat.v1.train.Optimizer
============================
Base class for optimizers.
```
tf.compat.v1.train.Optimizer(
use_locking, name
)
```
Migrate to TF2
--------------
[`tf.compat.v1.train.Optimizer`](optimizer) can be used in eager mode and [`tf.function`](../../../function), but it is not recommended. Please use the subclasses of [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) instead in TF2. Please see [Basic training loops](https://www.tensorflow.org/guide/basic_training_loops) or [Writing a training loop from scratch](https://www.tensorflow.org/guide/keras/writing_a_training_loop_from_scratch) for examples.
If your TF1 code contains a [`tf.compat.v1.train.Optimizer`](optimizer) symbol, whether it is used with or without a [`tf.estimator.Estimator`](../../../estimator/estimator), you cannot simply replace that with the corresponding [`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer)s. To migrate to TF2, it is advised the whole training program used with `Estimator` to be migrated to Keras [`Model.fit`](https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit) based or TF2 custom training loops.
#### Structural Mapping to Native TF2
Before:
```
sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0)
opt_op = sgd_op.minimize(cost, global_step, [var0, var1])
opt_op.run(session=session)
```
After:
```
sgd = tf.keras.optimizers.SGD(3.0)
sgd.minimize(cost_fn, [var0, var1])
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `use_locking` | Not supported | - |
| `name` | `name.` | - |
#### Before & After Usage Example
Before:
```
g = tf.compat.v1.Graph()
with g.as_default():
var0 = tf.compat.v1.Variable([1.0, 2.0])
var1 = tf.compat.v1.Variable([3.0, 4.0])
cost = 5 * var0 + 3 * var1
global_step = tf.compat.v1.Variable(
tf.compat.v1.zeros([], tf.compat.v1.int64), name='global_step')
init_op = tf.compat.v1.initialize_all_variables()
sgd_op = tf.compat.v1.train.GradientDescentOptimizer(3.0)
opt_op = sgd_op.minimize(cost, global_step, [var0, var1])
session = tf.compat.v1.Session(graph=g)
session.run(init_op)
opt_op.run(session=session)
print(session.run(var0))
[-14. -13.]
```
After:
```
>>> var0 = tf.Variable([1.0, 2.0])
>>> var1 = tf.Variable([3.0, 4.0])
>>> cost_fn = lambda: 5 * var0 + 3 * var1
>>> sgd = tf.keras.optimizers.SGD(3.0)
>>> sgd.minimize(cost_fn, [var0, var1])
>>> print(var0.numpy())
[-14. -13.]
```
Description
-----------
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 as `GradientDescentOptimizer`, `AdagradOptimizer`, or `MomentumOptimizer`.
### Usage
```
# 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.
opt_op = opt.minimize(cost, var_list=<list of variables>)
```
In the training program you will just have to run the returned Op.
```
# 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:
```
# Create an optimizer.
opt = GradientDescentOptimizer(learning_rate=0.1)
# Compute the gradients for a list of variables.
grads_and_vars = opt.compute_gradients(loss, <list of variables>)
# grads_and_vars is a list of tuples (gradient, variable). Do whatever you
# need to the 'gradient' part, for example cap them, etc.
capped_grads_and_vars = [(MyCapper(gv[0]), gv[1]) for gv in grads_and_vars]
# Ask the optimizer to apply the capped gradients.
opt.apply_gradients(capped_grads_and_vars)
```
### 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_NONE`, `GATE_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 inputs *before* 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.
| 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. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.sdca_shrink_l1 tf.compat.v1.train.sdca\_shrink\_l1
===================================
Applies L1 regularization shrink step on the parameters.
```
tf.compat.v1.train.sdca_shrink_l1(
weights, l1, l2, name=None
)
```
| Args |
| `weights` | A list of `Tensor` objects with type mutable `float32`. a list of vectors where each value is the weight associated with a feature group. |
| `l1` | A `float`. Symmetric l1 regularization strength. |
| `l2` | A `float`. Symmetric l2 regularization strength. Should be a positive float. |
| `name` | A name for the operation (optional). |
| Returns |
| The created Operation. |
| programming_docs |
tensorflow tf.compat.v1.train.import_meta_graph tf.compat.v1.train.import\_meta\_graph
======================================
Recreates a Graph saved in a `MetaGraphDef` proto.
```
tf.compat.v1.train.import_meta_graph(
meta_graph_or_file, clear_devices=False, import_scope=None, **kwargs
)
```
This function takes a `MetaGraphDef` protocol buffer as input. If the argument is a file containing a `MetaGraphDef` protocol buffer , it constructs a protocol buffer from the file content. The function then adds all the nodes from the `graph_def` field to the current graph, recreates all the collections, and returns a saver constructed from the `saver_def` field.
In combination with `export_meta_graph()`, this function can be used to
* Serialize a graph along with other Python objects such as `QueueRunner`, `Variable` into a `MetaGraphDef`.
* Restart training from a saved graph and checkpoints.
* Run inference from a saved graph and checkpoints.
```
...
# Create a saver.
saver = tf.compat.v1.train.Saver(...variables...)
# Remember the training_op we want to run by adding it to a collection.
tf.compat.v1.add_to_collection('train_op', train_op)
sess = tf.compat.v1.Session()
for step in range(1000000):
sess.run(train_op)
if step % 1000 == 0:
# Saves checkpoint, which by default also exports a meta_graph
# named 'my-model-global_step.meta'.
saver.save(sess, 'my-model', global_step=step)
```
Later we can continue training from this saved `meta_graph` without building the model from scratch.
```
with tf.Session() as sess:
new_saver =
tf.train.import_meta_graph('my-save-dir/my-model-10000.meta')
new_saver.restore(sess, 'my-save-dir/my-model-10000')
# tf.get_collection() returns a list. In this example we only want
# the first one.
train_op = tf.get_collection('train_op')[0]
for step in range(1000000):
sess.run(train_op)
```
>
> **Note:** Restarting training from saved `meta_graph` only works if the device assignments have not changed.
>
#### Example:
Variables, placeholders, and independent operations can also be stored, as shown in the following example.
```
# Saving contents and operations.
v1 = tf.placeholder(tf.float32, name="v1")
v2 = tf.placeholder(tf.float32, name="v2")
v3 = tf.math.multiply(v1, v2)
vx = tf.Variable(10.0, name="vx")
v4 = tf.add(v3, vx, name="v4")
saver = tf.train.Saver([vx])
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(vx.assign(tf.add(vx, vx)))
result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
print(result)
saver.save(sess, "./model_ex1")
```
Later this model can be restored and contents loaded.
```
# Restoring variables and running operations.
saver = tf.train.import_meta_graph("./model_ex1.meta")
sess = tf.Session()
saver.restore(sess, "./model_ex1")
result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 3.3})
print(result)
```
| Args |
| `meta_graph_or_file` | `MetaGraphDef` protocol buffer or filename (including the path) containing a `MetaGraphDef`. |
| `clear_devices` | Whether or not to clear the device field for an `Operation` or `Tensor` during import. |
| `import_scope` | Optional `string`. Name scope to add. Only used when initializing from protocol buffer. |
| `**kwargs` | Optional keyed arguments. |
| Returns |
| A saver constructed from `saver_def` in `MetaGraphDef` or None. A None value is returned if no variables exist in the `MetaGraphDef` (i.e., there are no variables to restore). |
| Raises |
| `RuntimeError` | If called with eager execution enabled. |
eager compatibility
-------------------
Exporting/importing meta graphs is not supported. No graph exists when eager execution is enabled.
tensorflow tf.compat.v1.train.create_global_step tf.compat.v1.train.create\_global\_step
=======================================
Create global step tensor in graph.
```
tf.compat.v1.train.create_global_step(
graph=None
)
```
Migrate to TF2
--------------
With the deprecation of global graphs, TF no longer tracks variables in collections. In other words, there are no global variables in TF2. Thus, the global step functions have been removed (`get_or_create_global_step`, `create_global_step`, `get_global_step`) . You have two options for migrating:
1. Create a Keras optimizer, which generates an `iterations` variable. This variable is automatically incremented when calling `apply_gradients`.
2. Manually create and increment a [`tf.Variable`](../../../variable).
Below is an example of migrating away from using a global step to using a Keras optimizer:
Define a dummy model and loss:
```
def compute_loss(x):
v = tf.Variable(3.0)
y = x * v
loss = x * 5 - x * v
return loss, [v]
```
Before migrating:
```
g = tf.Graph()
with g.as_default():
x = tf.compat.v1.placeholder(tf.float32, [])
loss, var_list = compute_loss(x)
global_step = tf.compat.v1.train.create_global_step()
global_init = tf.compat.v1.global_variables_initializer()
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
train_op = optimizer.minimize(loss, global_step, var_list)
sess = tf.compat.v1.Session(graph=g)
sess.run(global_init)
print("before training:", sess.run(global_step))
before training: 0
sess.run(train_op, feed_dict={x: 3})
print("after training:", sess.run(global_step))
after training: 1
```
Migrating to a Keras optimizer:
```
optimizer = tf.keras.optimizers.SGD(.01)
print("before training:", optimizer.iterations.numpy())
before training: 0
with tf.GradientTape() as tape:
loss, var_list = compute_loss(3)
grads = tape.gradient(loss, var_list)
optimizer.apply_gradients(zip(grads, var_list))
print("after training:", optimizer.iterations.numpy())
after training: 1
```
Description
-----------
| Args |
| `graph` | The graph in which to create the global step tensor. If missing, use default graph. |
| Returns |
| Global step tensor. |
| Raises |
| `ValueError` | if global step tensor is already defined. |
tensorflow tf.compat.v1.train.SyncReplicasOptimizer tf.compat.v1.train.SyncReplicasOptimizer
========================================
Class to synchronize, aggregate gradients and pass them to the optimizer.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.SyncReplicasOptimizer(
opt,
replicas_to_aggregate,
total_num_replicas=None,
variable_averages=None,
variables_to_average=None,
use_locking=False,
name='sync_replicas'
)
```
This class is deprecated. For synchronous training, please use [Distribution Strategies](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).
In a typical asynchronous training environment, it's common to have some stale gradients. For example, with a N-replica asynchronous training, gradients will be applied to the variables N times independently. Depending on each replica's training speed, some gradients might be calculated from copies of the variable from several steps back (N-1 steps on average). This optimizer avoids stale gradients by collecting gradients from all replicas, averaging them, then applying them to the variables in one shot, after which replicas can fetch the new variables and continue.
The following accumulators/queue are created:
* N `gradient accumulators`, one per variable to train. Gradients are pushed to them and the chief worker will wait until enough gradients are collected and then average them before applying to variables. The accumulator will drop all stale gradients (more details in the accumulator op).
* 1 `token` queue where the optimizer pushes the new global\_step value after all variables are updated.
The following local variable is created:
* `sync_rep_local_step`, one per replica. Compared against the global\_step in each accumulator to check for staleness of the gradients.
The optimizer adds nodes to the graph to collect gradients and pause the trainers until variables are updated. For the Parameter Server job:
1. An accumulator is created for each variable, and each replica pushes the gradients into the accumulators instead of directly applying them to the variables.
2. Each accumulator averages once enough gradients (replicas\_to\_aggregate) have been accumulated.
3. Apply the averaged gradients to the variables.
4. Only after all variables have been updated, increment the global step.
5. Only after step 4, pushes `global_step` in the `token_queue`, once for each worker replica. The workers can now fetch the global step, use it to update its local\_step variable and start the next batch. Please note that some workers can consume multiple minibatches, while some may not consume even one. This is because each worker fetches minibatches as long as a token exists. If one worker is stuck for some reason and does not consume a token, another worker can use it.
#### For the replicas:
1. Start a step: fetch variables and compute gradients.
2. Once the gradients have been computed, push them into gradient accumulators. Each accumulator will check the staleness and drop the stale.
3. After pushing all the gradients, dequeue an updated value of global\_step from the token queue and record that step to its local\_step variable. Note that this is effectively a barrier.
4. Start the next batch.
### Usage
```
# Create any optimizer to update the variables, say a simple SGD:
opt = GradientDescentOptimizer(learning_rate=0.1)
# Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each
# step the optimizer collects 50 gradients before applying to variables.
# Note that if you want to have 2 backup replicas, you can change
# total_num_replicas=52 and make sure this number matches how many physical
# replicas you started in your job.
opt = tf.compat.v1.train.SyncReplicasOptimizer(opt, replicas_to_aggregate=50,
total_num_replicas=50)
# Some models have startup_delays to help stabilize the model but when using
# sync_replicas training, set it to 0.
# Now you can call `minimize()` or `compute_gradients()` and
# `apply_gradients()` normally
training_op = opt.minimize(total_loss, global_step=self.global_step)
# You can create the hook which handles initialization and queues.
sync_replicas_hook = opt.make_session_run_hook(is_chief)
```
In the training program, every worker will run the train\_op as if not synchronized.
```
with training.MonitoredTrainingSession(
master=workers[worker_id].target, is_chief=is_chief,
hooks=[sync_replicas_hook]) as mon_sess:
while not mon_sess.should_stop():
mon_sess.run(training_op)
```
To use SyncReplicasOptimizer with an `Estimator`, you need to send sync\_replicas\_hook while calling the fit.
```
my_estimator = DNNClassifier(..., optimizer=opt)
my_estimator.fit(..., hooks=[sync_replicas_hook])
```
| Args |
| `opt` | The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. |
| `replicas_to_aggregate` | number of replicas to aggregate for each variable update. |
| `total_num_replicas` | Total number of tasks/workers/replicas, could be different from replicas\_to\_aggregate. If total\_num\_replicas > replicas\_to\_aggregate: it is backup\_replicas + replicas\_to\_aggregate. If total\_num\_replicas < replicas\_to\_aggregate: Replicas compute multiple batches per update to variables. |
| `variable_averages` | Optional `ExponentialMovingAverage` object, used to maintain moving averages for the variables passed in `variables_to_average`. |
| `variables_to_average` | a list of variables that need to be averaged. Only needed if variable\_averages is passed in. |
| `use_locking` | If True use locks for update operation. |
| `name` | string. Optional name of the returned operation. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L221-L344)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This contains most of the synchronization implementation and also wraps the apply\_gradients() from the real optimizer.
| 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 |
| `train_op` | The op to dequeue a token so the replicas can exit this batch and start the next one. This is executed by each replica. |
| Raises |
| `ValueError` | If the grads\_and\_vars is empty. |
| `ValueError` | If global step is not provided, the staleness cannot be checked. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L203-L219)
```
compute_gradients(
*args, **kwargs
)
```
Compute gradients of "loss" for the variables in "var\_list".
This simply wraps the compute\_gradients() from the real optimizer. The gradients will be aggregated in the apply\_gradients() so that user can modify the gradients like clipping with per replica global norm if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt the gradients from other replicas.
| Args |
| `*args` | Arguments for compute\_gradients(). |
| `**kwargs` | Keyword arguments for compute\_gradients(). |
| Returns |
| A list of (gradient, variable) pairs. |
### `get_chief_queue_runner`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L346-L364)
```
get_chief_queue_runner()
```
Returns the QueueRunner for the chief to execute.
This includes the operations to synchronize replicas: aggregate gradients, apply to variables, increment global step, insert tokens to token queue.
Note that this can only be called after calling apply\_gradients() which actually generates this queuerunner.
| Returns |
| A `QueueRunner` for chief to execute. |
| Raises |
| `ValueError` | If this is called before apply\_gradients(). |
### `get_init_tokens_op`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L405-L444)
```
get_init_tokens_op(
num_tokens=-1
)
```
Returns the op to fill the sync\_token\_queue with the tokens.
This is supposed to be executed in the beginning of the chief/sync thread so that even if the total\_num\_replicas is less than replicas\_to\_aggregate, the model can still proceed as the replicas can compute multiple steps per variable update. Make sure: `num_tokens >= replicas_to_aggregate - total_num_replicas`.
| Args |
| `num_tokens` | Number of tokens to add to the queue. |
| Returns |
| An op for the chief/sync replica to fill the token queue. |
| Raises |
| `ValueError` | If this is called before apply\_gradients(). |
| `ValueError` | If num\_tokens are smaller than replicas\_to\_aggregate - total\_num\_replicas. |
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L366-L378)
```
get_slot(
*args, **kwargs
)
```
Return a slot named "name" created for "var" by the Optimizer.
This simply wraps the get\_slot() from the actual optimizer.
| Args |
| `*args` | Arguments for get\_slot(). |
| `**kwargs` | Keyword arguments for get\_slot(). |
| Returns |
| The `Variable` for the slot if it was created, `None` otherwise. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L391-L403)
```
get_slot_names(
*args, **kwargs
)
```
Return a list of the names of slots created by the `Optimizer`.
This simply wraps the get\_slot\_names() from the actual optimizer.
| Args |
| `*args` | Arguments for get\_slot(). |
| `**kwargs` | Keyword arguments for get\_slot(). |
| Returns |
| A list of strings. |
### `make_session_run_hook`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L446-L448)
```
make_session_run_hook(
is_chief, num_tokens=-1
)
```
Creates a hook to handle SyncReplicasHook ops such as initialization.
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/sync_replicas_optimizer.py#L380-L389)
```
variables()
```
Fetches a list of optimizer variables in the default graph.
This wraps `variables()` from the actual optimizer. It does not include the `SyncReplicasOptimizer`'s local step.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.get_global_step tf.compat.v1.train.get\_global\_step
====================================
Get the global step tensor.
```
tf.compat.v1.train.get_global_step(
graph=None
)
```
Migrate to TF2
--------------
With the deprecation of global graphs, TF no longer tracks variables in collections. In other words, there are no global variables in TF2. Thus, the global step functions have been removed (`get_or_create_global_step`, `create_global_step`, `get_global_step`) . You have two options for migrating:
1. Create a Keras optimizer, which generates an `iterations` variable. This variable is automatically incremented when calling `apply_gradients`.
2. Manually create and increment a [`tf.Variable`](../../../variable).
Below is an example of migrating away from using a global step to using a Keras optimizer:
Define a dummy model and loss:
```
def compute_loss(x):
v = tf.Variable(3.0)
y = x * v
loss = x * 5 - x * v
return loss, [v]
```
Before migrating:
```
g = tf.Graph()
with g.as_default():
x = tf.compat.v1.placeholder(tf.float32, [])
loss, var_list = compute_loss(x)
global_step = tf.compat.v1.train.get_or_create_global_step()
global_init = tf.compat.v1.global_variables_initializer()
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
train_op = optimizer.minimize(loss, global_step, var_list)
sess = tf.compat.v1.Session(graph=g)
sess.run(global_init)
print("before training:", sess.run(global_step))
before training: 0
sess.run(train_op, feed_dict={x: 3})
print("after training:", sess.run(global_step))
after training: 1
```
Using `get_global_step`:
```
with g.as_default():
print(sess.run(tf.compat.v1.train.get_global_step()))
1
```
Migrating to a Keras optimizer:
```
optimizer = tf.keras.optimizers.SGD(.01)
print("before training:", optimizer.iterations.numpy())
before training: 0
with tf.GradientTape() as tape:
loss, var_list = compute_loss(3)
grads = tape.gradient(loss, var_list)
optimizer.apply_gradients(zip(grads, var_list))
print("after training:", optimizer.iterations.numpy())
after training: 1
```
Description
-----------
The global step tensor must be an integer variable. We first try to find it in the collection `GLOBAL_STEP`, or by name `global_step:0`.
| Args |
| `graph` | The graph to find the global step in. If missing, use default graph. |
| Returns |
| The global step variable, or `None` if none was found. |
| Raises |
| `TypeError` | If the global step tensor has a non-integer type, or if it is not a `Variable`. |
| programming_docs |
tensorflow tf.compat.v1.train.sdca_optimizer tf.compat.v1.train.sdca\_optimizer
==================================
Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for
```
tf.compat.v1.train.sdca_optimizer(
sparse_example_indices,
sparse_feature_indices,
sparse_feature_values,
dense_features,
example_weights,
example_labels,
sparse_indices,
sparse_weights,
dense_weights,
example_state_data,
loss_type,
l1,
l2,
num_loss_partitions,
num_inner_iterations,
adaptative=True,
name=None
)
```
linear models with L1 + L2 regularization. As global optimization objective is strongly-convex, the optimizer optimizes the dual objective at each step. The optimizer applies each update one example at a time. Examples are sampled uniformly, and the optimizer is learning rate free and enjoys linear convergence rate.
[Proximal Stochastic Dual Coordinate Ascent](http://arxiv.org/pdf/1211.2717v1.pdf).
Shai Shalev-Shwartz, Tong Zhang. 2012
\[Loss Objective = \sum f\_{i} (wx\_{i}) + (l2 / 2) \* |w|^2 + l1 \* |w|\]
[Adding vs. Averaging in Distributed Primal-Dual Optimization](http://arxiv.org/abs/1502.03508).
Chenxin Ma, Virginia Smith, Martin Jaggi, Michael I. Jordan, Peter Richtarik, Martin Takac. 2015
[Stochastic Dual Coordinate Ascent with Adaptive Probabilities](https://arxiv.org/abs/1502.08053).
Dominik Csiba, Zheng Qu, Peter Richtarik. 2015
| Args |
| `sparse_example_indices` | A list of `Tensor` objects with type `int64`. a list of vectors which contain example indices. |
| `sparse_feature_indices` | A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. a list of vectors which contain feature indices. |
| `sparse_feature_values` | A list of `Tensor` objects with type `float32`. a list of vectors which contains feature value associated with each feature group. |
| `dense_features` | A list of `Tensor` objects with type `float32`. a list of matrices which contains the dense feature values. |
| `example_weights` | A `Tensor` of type `float32`. a vector which contains the weight associated with each example. |
| `example_labels` | A `Tensor` of type `float32`. a vector which contains the label/target associated with each example. |
| `sparse_indices` | A list with the same length as `sparse_example_indices` of `Tensor` objects with type `int64`. a list of vectors where each value is the indices which has corresponding weights in sparse\_weights. This field maybe omitted for the dense approach. |
| `sparse_weights` | A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. a list of vectors where each value is the weight associated with a sparse feature group. |
| `dense_weights` | A list with the same length as `dense_features` of `Tensor` objects with type `float32`. a list of vectors where the values are the weights associated with a dense feature group. |
| `example_state_data` | A `Tensor` of type `float32`. a list of vectors containing the example state data. |
| `loss_type` | A `string` from: `"logistic_loss", "squared_loss", "hinge_loss", "smooth_hinge_loss", "poisson_loss"`. Type of the primal loss. Currently SdcaSolver supports logistic, squared and hinge losses. |
| `l1` | A `float`. Symmetric l1 regularization strength. |
| `l2` | A `float`. Symmetric l2 regularization strength. |
| `num_loss_partitions` | An `int` that is `>= 1`. Number of partitions of the global loss function. |
| `num_inner_iterations` | An `int` that is `>= 1`. Number of iterations per mini-batch. |
| `adaptative` | An optional `bool`. Defaults to `True`. Whether to use Adaptive SDCA for the inner loop. |
| `name` | A name for the operation (optional). |
| Returns |
| A tuple of `Tensor` objects (out\_example\_state\_data, out\_delta\_sparse\_weights, out\_delta\_dense\_weights). |
| `out_example_state_data` | A `Tensor` of type `float32`. |
| `out_delta_sparse_weights` | A list with the same length as `sparse_example_indices` of `Tensor` objects with type `float32`. |
| `out_delta_dense_weights` | A list with the same length as `dense_features` of `Tensor` objects with type `float32`. |
tensorflow tf.compat.v1.train.WorkerSessionCreator tf.compat.v1.train.WorkerSessionCreator
=======================================
Creates a tf.compat.v1.Session for a worker.
Inherits From: [`SessionCreator`](sessioncreator)
```
tf.compat.v1.train.WorkerSessionCreator(
scaffold=None, master='', config=None, max_wait_secs=(30 * 60)
)
```
| Args |
| `scaffold` | A `Scaffold` used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. |
| `master` | `String` representation of the TensorFlow master to use. |
| `config` | `ConfigProto` proto used to configure the session. |
| `max_wait_secs` | Maximum time to wait for the session to become available. |
Methods
-------
### `create_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L717-L720)
```
create_session()
```
tensorflow tf.compat.v1.train.update_checkpoint_state tf.compat.v1.train.update\_checkpoint\_state
============================================
Updates the content of the 'checkpoint' file. (deprecated)
```
tf.compat.v1.train.update_checkpoint_state(
save_dir,
model_checkpoint_path,
all_model_checkpoint_paths=None,
latest_filename=None,
all_model_checkpoint_timestamps=None,
last_preserved_timestamp=None
)
```
This updates the checkpoint file containing a CheckpointState proto.
| Args |
| `save_dir` | Directory where the model was saved. |
| `model_checkpoint_path` | The checkpoint file. |
| `all_model_checkpoint_paths` | List of strings. Paths to all not-yet-deleted checkpoints, sorted from oldest to newest. If this is a non-empty list, the last element must be equal to model\_checkpoint\_path. These paths are also saved in the CheckpointState proto. |
| `latest_filename` | Optional name of the checkpoint file. Default to 'checkpoint'. |
| `all_model_checkpoint_timestamps` | Optional list of timestamps (floats, seconds since the Epoch) indicating when the checkpoints in `all_model_checkpoint_paths` were created. |
| `last_preserved_timestamp` | A float, indicating the number of seconds since the Epoch when the last preserved checkpoint was written, e.g. due to a `keep_checkpoint_every_n_hours` parameter (see [`tf.train.CheckpointManager`](../../../train/checkpointmanager) for an implementation). |
| Raises |
| `RuntimeError` | If any of the model checkpoint paths conflict with the file containing CheckpointSate. |
tensorflow tf.compat.v1.train.ProximalAdagradOptimizer tf.compat.v1.train.ProximalAdagradOptimizer
===========================================
Optimizer that implements the Proximal Adagrad algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.ProximalAdagradOptimizer(
learning_rate,
initial_accumulator_value=0.1,
l1_regularization_strength=0.0,
l2_regularization_strength=0.0,
use_locking=False,
name='ProximalAdagrad'
)
```
#### References:
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization: [Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)) Efficient Learning using Forward-Backward Splitting: [Duchi et al., 2009](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting) ([pdf](http://papers.nips.cc/paper/3793-efficient-learning-using-forward-backward-splitting.pdf))
| 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. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.batch tf.compat.v1.train.batch
========================
Creates batches of tensors in `tensors`. (deprecated)
```
tf.compat.v1.train.batch(
tensors,
batch_size,
num_threads=1,
capacity=32,
enqueue_many=False,
shapes=None,
dynamic_pad=False,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
The argument `tensors` can be a list or a dictionary of tensors. The value returned by the function will be of the same type as `tensors`.
This function is implemented using a queue. A `QueueRunner` for the queue is added to the current `Graph`'s `QUEUE_RUNNER` collection.
If `enqueue_many` is `False`, `tensors` is assumed to represent a single example. An input tensor with shape `[x, y, z]` will be output as a tensor with shape `[batch_size, x, y, z]`.
If `enqueue_many` is `True`, `tensors` is assumed to represent a batch of examples, where the first dimension is indexed by example, and all members of `tensors` should have the same size in the first dimension. If an input tensor has shape `[*, x, y, z]`, the output will have shape `[batch_size, x, y, z]`. The `capacity` argument controls the how long the prefetching is allowed to grow the queues.
The returned operation is a dequeue operation and will throw [`tf.errors.OutOfRangeError`](../../../errors/outofrangeerror) if the input queue is exhausted. If this operation is feeding another input queue, its queue runner will catch this exception, however, if this operation is used in your main thread you are responsible for catching this yourself.
>
> **Note:** If `dynamic_pad` is `False`, you must ensure that either (i) the `shapes` argument is passed, or (ii) all of the tensors in `tensors` must have fully-defined shapes. `ValueError` will be raised if neither of these conditions holds.
>
If `dynamic_pad` is `True`, it is sufficient that the *rank* of the tensors is known, but individual dimensions may have shape `None`. In this case, for each enqueue the dimensions with value `None` may have a variable length; upon dequeue, the output tensors will be padded on the right to the maximum shape of the tensors in the current minibatch. For numbers, this padding takes value 0. For strings, this padding is the empty string. See `PaddingFIFOQueue` for more info.
If `allow_smaller_final_batch` is `True`, a smaller batch value than `batch_size` is returned when the queue is closed and there are not enough elements to fill the batch, otherwise the pending elements are discarded. In addition, all output tensors' static shapes, as accessed via the `shape` property will have a first `Dimension` value of `None`, and operations that depend on fixed batch\_size would fail.
| Args |
| `tensors` | The list or dictionary of tensors to enqueue. |
| `batch_size` | The new batch size pulled from the queue. |
| `num_threads` | The number of threads enqueuing `tensors`. The batching will be nondeterministic if `num_threads > 1`. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `enqueue_many` | Whether each tensor in `tensors` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensors`. |
| `dynamic_pad` | Boolean. Allow variable dimensions in input shapes. The given dimensions are padded upon dequeue so that tensors within a batch have the same shapes. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional). If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the same types as `tensors` (except if the input is a list of one element, then it returns a tensor, not a list). |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
| programming_docs |
tensorflow tf.compat.v1.train.start_queue_runners tf.compat.v1.train.start\_queue\_runners
========================================
Starts all queue runners collected in the graph. (deprecated)
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.queue_runner.start_queue_runners`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/start_queue_runners)
```
tf.compat.v1.train.start_queue_runners(
sess=None,
coord=None,
daemon=True,
start=True,
collection=ops.GraphKeys.QUEUE_RUNNERS
)
```
Migrate to TF2
--------------
QueueRunners are not compatible with eager execution. Instead, please use [tf.data](https://www.tensorflow.org/guide/data) to get data into your model.
Description
-----------
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 |
| `sess` | `Session` 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`. |
| Raises |
| `ValueError` | if `sess` is None and there isn't any default session. |
| `TypeError` | if `sess` is not a [`tf.compat.v1.Session`](../session) object. |
| Returns |
| A list of threads. |
| Raises |
| `RuntimeError` | If called with eager execution enabled. |
| `ValueError` | If called without a default [`tf.compat.v1.Session`](../session) registered. |
tensorflow tf.compat.v1.train.Saver tf.compat.v1.train.Saver
========================
Saves and restores variables.
```
tf.compat.v1.train.Saver(
var_list=None,
reshape=False,
sharded=False,
max_to_keep=5,
keep_checkpoint_every_n_hours=10000.0,
name=None,
restore_sequentially=False,
saver_def=None,
builder=None,
defer_build=False,
allow_empty=False,
write_version=saver_pb2.SaverDef.V2,
pad_step_number=False,
save_relative_paths=False,
filename=None
)
```
Migrate to TF2
--------------
[`tf.compat.v1.train.Saver`](saver) is not supported for saving and restoring checkpoints in TF2. Please switch to [`tf.train.Checkpoint`](../../../train/checkpoint) or [`tf.keras.Model.save_weights`](../../../keras/model#save_weights), which perform a more robust [object-based saving](https://www.tensorflow.org/guide/checkpoint#loading_mechanics).
### How to Rewrite Checkpoints
Please rewrite your checkpoints immediately using the object-based checkpoint APIs.
You can load a name-based checkpoint written by [`tf.compat.v1.train.Saver`](saver) using [`tf.train.Checkpoint.restore`](../../../train/checkpoint#restore) or [`tf.keras.Model.load_weights`](../../../keras/model#load_weights). However, you may have to change the names of the variables in your model to match the variable names in the name-based checkpoint, which can be viewed with [`tf.train.list_variables(path)`](../../../train/list_variables).
Another option is to create an `assignment_map` that maps the name of the variables in the name-based checkpoint to the variables in your model, eg:
```
{
'sequential/dense/bias': model.variables[0],
'sequential/dense/kernel': model.variables[1]
}
```
and use [`tf.compat.v1.train.init_from_checkpoint(path, assignment_map)`](init_from_checkpoint) to restore the name-based checkpoint.
After restoring, re-encode your checkpoint using [`tf.train.Checkpoint.save`](../../../train/checkpoint#save) or [`tf.keras.Model.save_weights`](../../../keras/model#save_weights).
See the [Checkpoint compatibility](https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) section of the migration guide for more details.
### Checkpoint Management in TF2
Use [`tf.train.CheckpointManager`](../../../train/checkpointmanager) to manage checkpoints in TF2. [`tf.train.CheckpointManager`](../../../train/checkpointmanager) offers equivalent `keep_checkpoint_every_n_hours` and `max_to_keep` parameters.
To recover the latest checkpoint,
```
checkpoint = tf.train.Checkpoint(model)
manager = tf.train.CheckpointManager(checkpoint)
status = checkpoint.restore(manager.latest_checkpoint)
```
[`tf.train.CheckpointManager`](../../../train/checkpointmanager) also writes a [`CheckpointState` proto](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/checkpoint_state.proto) which contains the timestamp when each checkpoint was created.
### Writing `MetaGraphDef`s in TF2
To replace, [`tf.compat.v1.train.Saver.save(write_meta_graph=True)`](saver#save), use [`tf.saved_model.save`](../../../saved_model/save) to write the `MetaGraphDef` (which is contained in `saved_model.pb`).
Description
-----------
See [Variables](https://tensorflow.org/guide/variables) for an overview of variables, saving and restoring.
The `Saver` class adds ops to save and restore variables to and from *checkpoints*. It also provides convenience methods to run these ops.
Checkpoints are binary files in a proprietary format which map variable names to tensor values. The best way to examine the contents of a checkpoint is to load it using a `Saver`.
Savers can automatically number checkpoint filenames with a provided counter. This lets you keep multiple checkpoints at different steps while training a model. For example you can number the checkpoint filenames with the training step number. To avoid filling up disks, savers manage checkpoint files automatically. For example, they can keep only the N most recent files, or one checkpoint for every N hours of training.
You number checkpoint filenames by passing a value to the optional `global_step` argument to `save()`:
```
saver.save(sess, 'my-model', global_step=0) ==> filename: 'my-model-0'
...
saver.save(sess, 'my-model', global_step=1000) ==> filename: 'my-model-1000'
```
Additionally, optional arguments to the `Saver()` constructor let you control the proliferation of checkpoint files on disk:
* `max_to_keep` indicates the maximum number of recent checkpoint files to keep. As new files are created, older files are deleted. If None or 0, no checkpoints are deleted from the filesystem but only the last one is kept in the `checkpoint` file. Defaults to 5 (that is, the 5 most recent checkpoint files are kept.)
* `keep_checkpoint_every_n_hours`: In addition to keeping the most recent `max_to_keep` checkpoint files, you might want to keep one checkpoint file for every N hours of training. This can be useful if you want to later analyze how a model progressed during a long training session. For example, passing `keep_checkpoint_every_n_hours=2` ensures that you keep one checkpoint file for every 2 hours of training. The default value of 10,000 hours effectively disables the feature.
Note that you still have to call the `save()` method to save the model. Passing these arguments to the constructor will not save variables automatically for you.
A training program that saves regularly looks like:
```
...
# Create a saver.
saver = tf.compat.v1.train.Saver(...variables...)
# Launch the graph and train, saving the model every 1,000 steps.
sess = tf.compat.v1.Session()
for step in range(1000000):
sess.run(..training_op..)
if step % 1000 == 0:
# Append the step number to the checkpoint name:
saver.save(sess, 'my-model', global_step=step)
```
In addition to checkpoint files, savers keep a protocol buffer on disk with the list of recent checkpoints. This is used to manage numbered checkpoint files and by `latest_checkpoint()`, which makes it easy to discover the path to the most recent checkpoint. That protocol buffer is stored in a file named 'checkpoint' next to the checkpoint files.
If you create several savers, you can specify a different filename for the protocol buffer file in the call to `save()`.
| Args |
| `var_list` | A list of `Variable`/`SaveableObject`, or a dictionary mapping names to `SaveableObject`s. If `None`, defaults to the list of all saveable objects. |
| `reshape` | If `True`, allows restoring parameters from a checkpoint where the variables have a different shape. |
| `sharded` | If `True`, shard the checkpoints, one per device. |
| `max_to_keep` | Maximum number of recent checkpoints to keep. Defaults to 5. |
| `keep_checkpoint_every_n_hours` | How often to keep checkpoints. Defaults to 10,000 hours. |
| `name` | String. Optional name to use as a prefix when adding operations. |
| `restore_sequentially` | A `Bool`, which if true, causes restore of different variables to happen sequentially within each device. This can lower memory usage when restoring very large models. |
| `saver_def` | Optional `SaverDef` proto to use instead of running the builder. This is only useful for specialty code that wants to recreate a `Saver` object for a previously built `Graph` that had a `Saver`. The `saver_def` proto should be the one returned by the `as_saver_def()` call of the `Saver` that was created for that `Graph`. |
| `builder` | Optional `SaverBuilder` to use if a `saver_def` was not provided. Defaults to `BulkSaverBuilder()`. |
| `defer_build` | If `True`, defer adding the save and restore ops to the `build()` call. In that case `build()` should be called before finalizing the graph or using the saver. |
| `allow_empty` | If `False` (default) raise an error if there are no variables in the graph. Otherwise, construct the saver anyway and make it a no-op. |
| `write_version` | controls what format to use when saving checkpoints. It also affects certain filepath matching logic. The V2 format is the recommended choice: it is much more optimized than V1 in terms of memory required and latency incurred during restore. Regardless of this flag, the Saver is able to restore from both V2 and V1 checkpoints. |
| `pad_step_number` | if True, pads the global step number in the checkpoint filepaths to some fixed width (8 by default). This is turned off by default. |
| `save_relative_paths` | If `True`, will write relative paths to the checkpoint state file. This is needed if the user wants to copy the checkpoint directory and reload from the copied directory. |
| `filename` | If known at graph construction time, filename used for variable loading/saving. |
| Raises |
| `TypeError` | If `var_list` is invalid. |
| `ValueError` | If any of the keys or values in `var_list` are not unique. |
| `RuntimeError` | If eager execution is enabled and`var_list` does not specify a list of variables to save. |
| Attributes |
| `last_checkpoints` | List of not-yet-deleted checkpoint filenames. You can pass any of the returned values to `restore()`. |
Methods
-------
### `as_saver_def`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1072-L1078)
```
as_saver_def()
```
Generates a `SaverDef` representation of this saver.
| Returns |
| A `SaverDef` proto. |
### `build`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L942-L945)
```
build()
```
### `export_meta_graph`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1337-L1381)
```
export_meta_graph(
filename=None,
collection_list=None,
as_text=False,
export_scope=None,
clear_devices=False,
clear_extraneous_savers=False,
strip_default_attrs=False,
save_debug_info=False
)
```
Writes `MetaGraphDef` to save\_path/filename.
| Args |
| `filename` | Optional meta\_graph filename including the path. |
| `collection_list` | List of string keys to collect. |
| `as_text` | If `True`, writes the meta\_graph as an ASCII proto. |
| `export_scope` | Optional `string`. Name scope to remove. |
| `clear_devices` | Whether or not to clear the device field for an `Operation` or `Tensor` during export. |
| `clear_extraneous_savers` | Remove any Saver-related information from the graph (both Save/Restore ops and SaverDefs) that are not associated with this Saver. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| `save_debug_info` | If `True`, save the GraphDebugInfo to a separate file, which in the same directory of filename and with `_debug` added before the file extension. |
| Returns |
| A `MetaGraphDef` proto. |
### `from_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1107-L1118)
```
@staticmethod
from_proto(
saver_def, import_scope=None
)
```
Returns a `Saver` object created from `saver_def`.
| Args |
| `saver_def` | a `SaverDef` protocol buffer. |
| `import_scope` | Optional `string`. Name scope to use. |
| Returns |
| A `Saver` built from saver\_def. |
### `recover_last_checkpoints`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1161-L1182)
```
recover_last_checkpoints(
checkpoint_paths
)
```
Recovers the internal saver state after a crash.
This method is useful for recovering the "self.\_last\_checkpoints" state.
Globs for the checkpoints pointed to by `checkpoint_paths`. If the files exist, use their mtime as the checkpoint timestamp.
| Args |
| `checkpoint_paths` | a list of checkpoint paths. |
### `restore`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1383-L1457)
```
restore(
sess, save_path
)
```
Restores previously saved variables.
This method runs the ops added by the constructor for restoring variables. It requires a session in which the graph was launched. The variables to restore do not have to have been initialized, as restoring is itself a way to initialize variables.
The `save_path` argument is typically a value previously returned from a `save()` call, or a call to `latest_checkpoint()`.
| Args |
| `sess` | A `Session` to use to restore the parameters. None in eager mode. |
| `save_path` | Path where parameters were previously saved. |
| Raises |
| `ValueError` | If save\_path is None or not a valid checkpoint. |
### `save`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1184-L1335)
```
save(
sess,
save_path,
global_step=None,
latest_filename=None,
meta_graph_suffix='meta',
write_meta_graph=True,
write_state=True,
strip_default_attrs=False,
save_debug_info=False
)
```
Saves variables.
This method runs the ops added by the constructor for saving variables. It requires a session in which the graph was launched. The variables to save must also have been initialized.
The method returns the path prefix of the newly created checkpoint files. This string can be passed directly to a call to `restore()`.
| Args |
| `sess` | A Session to use to save the variables. |
| `save_path` | String. Prefix of filenames created for the checkpoint. |
| `global_step` | If provided the global step number is appended to `save_path` to create the checkpoint filenames. The optional argument can be a `Tensor`, a `Tensor` name or an integer. |
| `latest_filename` | Optional name for the protocol buffer file that will contains the list of most recent checkpoints. That file, kept in the same directory as the checkpoint files, is automatically managed by the saver to keep track of recent checkpoints. Defaults to 'checkpoint'. |
| `meta_graph_suffix` | Suffix for `MetaGraphDef` file. Defaults to 'meta'. |
| `write_meta_graph` | `Boolean` indicating whether or not to write the meta graph file. |
| `write_state` | `Boolean` indicating whether or not to write the `CheckpointStateProto`. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| `save_debug_info` | If `True`, save the GraphDebugInfo to a separate file, which in the same directory of save\_path and with `_debug` added before the file extension. This is only enabled when `write_meta_graph` is `True` |
| Returns |
| A string: path prefix used for the checkpoint files. If the saver is sharded, this string ends with: '-?????-of-nnnnn' where 'nnnnn' is the number of shards created. If the saver is empty, returns None. |
| Raises |
| `TypeError` | If `sess` is not a `Session`. |
| `ValueError` | If `latest_filename` contains path components, or if it collides with `save_path`. |
| `RuntimeError` | If save and restore ops weren't built. |
### `set_last_checkpoints`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1131-L1146)
```
set_last_checkpoints(
last_checkpoints
)
```
Sets the list of old checkpoint filenames.
| Args |
| `last_checkpoints` | A list of checkpoint filenames. |
| Raises |
| `AssertionError` | If last\_checkpoints is not a list. |
### `set_last_checkpoints_with_time`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1148-L1159)
```
set_last_checkpoints_with_time(
last_checkpoints_with_time
)
```
Sets the list of old checkpoint filenames and timestamps.
| Args |
| `last_checkpoints_with_time` | A list of tuples of checkpoint filenames and timestamps. |
| Raises |
| `AssertionError` | If last\_checkpoints\_with\_time is not a list. |
### `to_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/saver.py#L1080-L1105)
```
to_proto(
export_scope=None
)
```
Converts this `Saver` to a `SaverDef` protocol buffer.
| Args |
| `export_scope` | Optional `string`. Name scope to remove. |
| Returns |
| A `SaverDef` protocol buffer. |
tensorflow tf.compat.v1.train.QueueRunner tf.compat.v1.train.QueueRunner
==============================
Holds a list of enqueue operations for a queue, each to be run in a thread.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.queue_runner.QueueRunner`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/QueueRunner)
```
tf.compat.v1.train.QueueRunner(
queue=None,
enqueue_ops=None,
close_op=None,
cancel_op=None,
queue_closed_exception_types=None,
queue_runner_def=None,
import_scope=None
)
```
Migrate to TF2
--------------
QueueRunners are not compatible with eager execution. Instead, please use [tf.data](https://www.tensorflow.org/guide/data) to get data into your model.
Description
-----------
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.
| 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`. |
| `RuntimeError` | If eager execution is enabled. |
| Attributes |
| `cancel_op` | |
| `close_op` | |
| `enqueue_ops` | |
| `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 to `create_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.
|
| `name` | The string name of the underlying Queue. |
| `queue` | |
| `queue_closed_exception_types` | |
Methods
-------
### `create_threads`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/queue_runner_impl.py#L298-L353)
```
create_threads(
sess, coord=None, daemon=False, start=False
)
```
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. |
### `from_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/queue_runner_impl.py#L384-L388)
```
@staticmethod
from_proto(
queue_runner_def, import_scope=None
)
```
Returns a `QueueRunner` object created from `queue_runner_def`.
### `to_proto`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/queue_runner_impl.py#L355-L382)
```
to_proto(
export_scope=None
)
```
Converts this `QueueRunner` to a `QueueRunnerDef` protocol buffer.
| Args |
| `export_scope` | Optional `string`. Name scope to remove. |
| Returns |
| A `QueueRunnerDef` protocol buffer, or `None` if the `Variable` is not in the specified name scope. |
| programming_docs |
tensorflow tf.compat.v1.train.SessionCreator tf.compat.v1.train.SessionCreator
=================================
A factory for tf.Session.
Methods
-------
### `create_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L620-L623)
```
@abc.abstractmethod
create_session()
```
tensorflow tf.compat.v1.train.get_or_create_global_step tf.compat.v1.train.get\_or\_create\_global\_step
================================================
Returns and create (if necessary) the global step tensor.
```
tf.compat.v1.train.get_or_create_global_step(
graph=None
)
```
Migrate to TF2
--------------
With the deprecation of global graphs, TF no longer tracks variables in collections. In other words, there are no global variables in TF2. Thus, the global step functions have been removed (`get_or_create_global_step`, `create_global_step`, `get_global_step`) . You have two options for migrating:
1. Create a Keras optimizer, which generates an `iterations` variable. This variable is automatically incremented when calling `apply_gradients`.
2. Manually create and increment a [`tf.Variable`](../../../variable).
Below is an example of migrating away from using a global step to using a Keras optimizer:
Define a dummy model and loss:
```
def compute_loss(x):
v = tf.Variable(3.0)
y = x * v
loss = x * 5 - x * v
return loss, [v]
```
Before migrating:
```
g = tf.Graph()
with g.as_default():
x = tf.compat.v1.placeholder(tf.float32, [])
loss, var_list = compute_loss(x)
global_step = tf.compat.v1.train.get_or_create_global_step()
global_init = tf.compat.v1.global_variables_initializer()
optimizer = tf.compat.v1.train.GradientDescentOptimizer(0.1)
train_op = optimizer.minimize(loss, global_step, var_list)
sess = tf.compat.v1.Session(graph=g)
sess.run(global_init)
print("before training:", sess.run(global_step))
before training: 0
sess.run(train_op, feed_dict={x: 3})
print("after training:", sess.run(global_step))
after training: 1
```
Migrating to a Keras optimizer:
```
optimizer = tf.keras.optimizers.SGD(.01)
print("before training:", optimizer.iterations.numpy())
before training: 0
with tf.GradientTape() as tape:
loss, var_list = compute_loss(3)
grads = tape.gradient(loss, var_list)
optimizer.apply_gradients(zip(grads, var_list))
print("after training:", optimizer.iterations.numpy())
after training: 1
```
Description
-----------
| Args |
| `graph` | The graph in which to create the global step tensor. If missing, use default graph. |
| Returns |
| The global step tensor. |
tensorflow tf.compat.v1.train.warm_start tf.compat.v1.train.warm\_start
==============================
Warm-starts a model using the given settings.
```
tf.compat.v1.train.warm_start(
ckpt_to_initialize_from,
vars_to_warm_start='.*',
var_name_to_vocab_info=None,
var_name_to_prev_var_name=None
)
```
If you are using a tf.estimator.Estimator, this will automatically be called during training.
| Args |
| `ckpt_to_initialize_from` | [Required] A string specifying the directory with checkpoint file(s) or path to checkpoint from which to warm-start the model parameters. |
| `vars_to_warm_start` | [Optional] One of the following: * A regular expression (string) that captures which variables to warm-start (see tf.compat.v1.get\_collection). This expression will only consider variables in the TRAINABLE\_VARIABLES collection -- if you need to warm-start non\_TRAINABLE vars (such as optimizer accumulators or batch norm statistics), please use the below option.
* A list of strings, each a regex scope provided to tf.compat.v1.get\_collection with GLOBAL\_VARIABLES (please see tf.compat.v1.get\_collection). For backwards compatibility reasons, this is separate from the single-string argument type.
* A list of Variables to warm-start. If you do not have access to the `Variable` objects at the call site, please use the above option.
* `None`, in which case only TRAINABLE variables specified in `var_name_to_vocab_info` will be warm-started.
Defaults to `'.*'`, which warm-starts all variables in the TRAINABLE\_VARIABLES collection. Note that this excludes variables such as accumulators and moving statistics from batch norm. |
| `var_name_to_vocab_info` | [Optional] Dict of variable names (strings) to [`tf.estimator.VocabInfo`](../../../estimator/vocabinfo). The variable names should be "full" variables, not the names of the partitions. If not explicitly provided, the variable is assumed to have no (changes to) vocabulary. |
| `var_name_to_prev_var_name` | [Optional] Dict of variable names (strings) to name of the previously-trained variable in `ckpt_to_initialize_from`. If not explicitly provided, the name of the variable is assumed to be same between previous checkpoint and current model. Note that this has no effect on the set of variables that is warm-started, and only controls name mapping (use `vars_to_warm_start` for controlling what variables to warm-start). |
| Raises |
| `ValueError` | If the WarmStartSettings contains prev\_var\_name or VocabInfo configuration for variable names that are not used. This is to ensure a stronger check for variable configuration than relying on users to examine the logs. |
tensorflow tf.compat.v1.train.SingularMonitoredSession tf.compat.v1.train.SingularMonitoredSession
===========================================
Session-like object that handles initialization, restoring, and hooks.
```
tf.compat.v1.train.SingularMonitoredSession(
hooks=None,
scaffold=None,
master='',
config=None,
checkpoint_dir=None,
stop_grace_period_secs=120,
checkpoint_filename_with_path=None
)
```
Migrate to TF2
--------------
This API is not compatible with eager execution and [`tf.function`](../../../function). To migrate to TF2, rewrite the code to be compatible with eager execution. Check the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls. In Keras, session hooks can be replaced by Callbacks e.g. [logging hook notebook](https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) For more details please read [Better performance with tf.function](https://www.tensorflow.org/guide/function).
Description
-----------
Please note that this utility is not recommended for distributed settings. For distributed settings, please use [`tf.compat.v1.train.MonitoredSession`](monitoredsession). The differences between `MonitoredSession` and `SingularMonitoredSession` are:
* `MonitoredSession` handles `AbortedError` and `UnavailableError` for distributed settings, but `SingularMonitoredSession` does not.
* `MonitoredSession` can be created in `chief` or `worker` modes. `SingularMonitoredSession` is always created as `chief`.
* You can access the raw [`tf.compat.v1.Session`](../session) object used by `SingularMonitoredSession`, whereas in MonitoredSession the raw session is private. This can be used:
+ To `run` without hooks.
+ To save and restore.
* All other functionality is identical.
#### Example usage:
```
saver_hook = CheckpointSaverHook(...)
summary_hook = SummarySaverHook(...)
with SingularMonitoredSession(hooks=[saver_hook, summary_hook]) as sess:
while not sess.should_stop():
sess.run(train_op)
```
Initialization: At creation time the hooked session does following things in given order:
* calls `hook.begin()` for each given hook
* finalizes the graph via `scaffold.finalize()`
* create session
* initializes the model via initialization ops provided by `Scaffold`
* restores variables if a checkpoint exists
* launches queue runners
Run: When `run()` is called, the hooked session does following things:
* calls `hook.before_run()`
* calls TensorFlow `session.run()` with merged fetches and feed\_dict
* calls `hook.after_run()`
* returns result of `session.run()` asked by user
Exit: At the `close()`, the hooked session does following things in order:
* calls `hook.end()`
* closes the queue runners and the session
* suppresses `OutOfRange` error which indicates that all inputs have been processed if the `SingularMonitoredSession` is used as a context.
| Args |
| `hooks` | An iterable of `SessionRunHook' objects. </td> </tr><tr> <td>`scaffold`</td> <td> A`Scaffold`used for gathering or building supportive ops. If not specified a default one is created. It's used to finalize the graph. </td> </tr><tr> <td>`master`</td> <td>`String`representation of the TensorFlow master to use. </td> </tr><tr> <td>`config`</td> <td>`ConfigProto`proto used to configure the session. </td> </tr><tr> <td>`checkpoint\_dir`</td> <td> A string. Optional path to a directory where to restore variables. </td> </tr><tr> <td>`stop\_grace\_period\_secs`</td> <td> Number of seconds given to threads to stop after`close()`has been called. </td> </tr><tr> <td>`checkpoint\_filename\_with\_path` | A string. Optional path to a checkpoint file from which to restore variables. |
| Attributes |
| `graph` | The graph that was launched in this session. |
Child Classes
-------------
[`class StepContext`](monitoredsession/stepcontext)
Methods
-------
### `close`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L884-L885)
```
close()
```
### `raw_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L1162-L1164)
```
raw_session()
```
Returns underlying `TensorFlow.Session` object.
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L768-L786)
```
run(
fetches, feed_dict=None, options=None, run_metadata=None
)
```
Run ops in the monitored session.
This method is completely compatible with the `tf.Session.run()` method.
| Args |
| `fetches` | Same as `tf.Session.run()`. |
| `feed_dict` | Same as `tf.Session.run()`. |
| `options` | Same as `tf.Session.run()`. |
| `run_metadata` | Same as `tf.Session.run()`. |
| Returns |
| Same as `tf.Session.run()`. |
### `run_step_fn`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L788-L842)
```
run_step_fn(
step_fn
)
```
Run ops using a step function.
| Args |
| `step_fn` | A function or a method with a single argument of type `StepContext`. The function may use methods of the argument to perform computations with access to a raw session. The returned value of the `step_fn` will be returned from `run_step_fn`, unless a stop is requested. In that case, the next `should_stop` call will return True. Example usage:
```
```python
with tf.Graph().as_default():
c = tf.compat.v1.placeholder(dtypes.float32)
v = tf.add(c, 4.0)
w = tf.add(c, 0.5)
def step_fn(step_context):
a = step_context.session.run(fetches=v, feed_dict={c: 0.5})
if a <= 4.5:
step_context.request_stop()
return step_context.run_with_hooks(fetches=w,
feed_dict={c: 0.1})
with tf.MonitoredSession() as session:
while not session.should_stop():
a = session.run_step_fn(step_fn)
```
Hooks interact with the `run_with_hooks()` call inside the
`step_fn` as they do with a `MonitoredSession.run` call.
```
|
| Returns |
| Returns the returned value of `step_fn`. |
| Raises |
| `StopIteration` | if `step_fn` has called `request_stop()`. It may be caught by `with tf.MonitoredSession()` to close the session. |
| `ValueError` | if `step_fn` doesn't have a single argument called `step_context`. It may also optionally have `self` for cases when it belongs to an object. |
### `should_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L881-L882)
```
should_stop()
```
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L887-L888)
```
__enter__()
```
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L890-L895)
```
__exit__(
exception_type, exception_value, traceback
)
```
tensorflow tf.compat.v1.train.export_meta_graph tf.compat.v1.train.export\_meta\_graph
======================================
Returns `MetaGraphDef` proto.
```
tf.compat.v1.train.export_meta_graph(
filename=None,
meta_info_def=None,
graph_def=None,
saver_def=None,
collection_list=None,
as_text=False,
graph=None,
export_scope=None,
clear_devices=False,
clear_extraneous_savers=False,
strip_default_attrs=False,
save_debug_info=False,
**kwargs
)
```
Optionally writes it to filename.
This function exports the graph, saver, and collection objects into `MetaGraphDef` protocol buffer with the intention of it being imported at a later time or location to restart training, run inference, or be a subgraph.
| Args |
| `filename` | Optional filename including the path for writing the generated `MetaGraphDef` protocol buffer. |
| `meta_info_def` | `MetaInfoDef` protocol buffer. |
| `graph_def` | `GraphDef` protocol buffer. |
| `saver_def` | `SaverDef` protocol buffer. |
| `collection_list` | List of string keys to collect. |
| `as_text` | If `True`, writes the `MetaGraphDef` as an ASCII proto. |
| `graph` | The `Graph` to export. If `None`, use the default graph. |
| `export_scope` | Optional `string`. Name scope under which to extract the subgraph. The scope name will be striped from the node definitions for easy import later into new name scopes. If `None`, the whole graph is exported. graph\_def and export\_scope cannot both be specified. |
| `clear_devices` | Whether or not to clear the device field for an `Operation` or `Tensor` during export. |
| `clear_extraneous_savers` | Remove any Saver-related information from the graph (both Save/Restore ops and SaverDefs) that are not associated with the provided SaverDef. |
| `strip_default_attrs` | Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. For a detailed guide, see [Stripping Default-Valued Attributes](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/saved_model/README.md#stripping-default-valued-attributes). |
| `save_debug_info` | If `True`, save the GraphDebugInfo to a separate file, which in the same directory of filename and with `_debug` added before the file extend. |
| `**kwargs` | Optional keyed arguments. |
| Returns |
| A `MetaGraphDef` proto. |
| Raises |
| `ValueError` | When the `GraphDef` is larger than 2GB. |
| `RuntimeError` | If called with eager execution enabled. |
eager compatibility
-------------------
Exporting/importing meta graphs is not supported unless both `graph_def` and `graph` are provided. No graph exists when eager execution is enabled.
tensorflow tf.compat.v1.train.inverse_time_decay tf.compat.v1.train.inverse\_time\_decay
=======================================
Applies inverse time decay to the initial learning rate.
```
tf.compat.v1.train.inverse_time_decay(
learning_rate,
global_step,
decay_steps,
decay_rate,
staircase=False,
name=None
)
```
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:
```
decayed_learning_rate = learning_rate / (1 + decay_rate * global_step /
decay_step)
```
or, if `staircase` is `True`, as:
```
decayed_learning_rate = learning_rate / (1 + decay_rate * floor(global_step /
decay_step))
```
Example: decay 1/t with a rate of 0.5:
```
...
global_step = tf.Variable(0, trainable=False)
learning_rate = 0.1
decay_steps = 1.0
decay_rate = 0.5
learning_rate = tf.compat.v1.train.inverse_time_decay(learning_rate,
global_step,
decay_steps, decay_rate)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.compat.v1.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step)
)
```
| 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. |
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow Module: tf.compat.v1.train.experimental Module: tf.compat.v1.train.experimental
=======================================
Public API for tf.train.experimental namespace.
Classes
-------
[`class DynamicLossScale`](../mixed_precision/dynamiclossscale): Loss scale that dynamically adjusts itself.
[`class FixedLossScale`](../mixed_precision/fixedlossscale): Loss scale with a fixed value.
[`class LossScale`](../mixed_precision/lossscale): Base class for all TF1 loss scales.
[`class MixedPrecisionLossScaleOptimizer`](../mixed_precision/mixedprecisionlossscaleoptimizer): An optimizer that applies loss scaling.
[`class PythonState`](../../../train/experimental/pythonstate): A mixin for putting Python state in an object-based checkpoint.
Functions
---------
[`disable_mixed_precision_graph_rewrite(...)`](../mixed_precision/disable_mixed_precision_graph_rewrite): Disables the mixed precision graph rewrite.
[`enable_mixed_precision_graph_rewrite(...)`](../mixed_precision/enable_mixed_precision_graph_rewrite): Enable mixed precision via a graph rewrite.
tensorflow tf.compat.v1.train.assert_global_step tf.compat.v1.train.assert\_global\_step
=======================================
Asserts `global_step_tensor` is a scalar int `Variable` or `Tensor`.
```
tf.compat.v1.train.assert_global_step(
global_step_tensor
)
```
| Args |
| `global_step_tensor` | `Tensor` to test. |
tensorflow tf.compat.v1.train.global_step tf.compat.v1.train.global\_step
===============================
Small helper to get the global step.
```
tf.compat.v1.train.global_step(
sess, global_step_tensor
)
```
```
# Create a variable to hold the global_step.
global_step_tensor = tf.Variable(10, trainable=False, name='global_step')
# Create a session.
sess = tf.compat.v1.Session()
# Initialize the variable
sess.run(global_step_tensor.initializer)
# Get the variable value.
print('global_step: %s' % tf.compat.v1.train.global_step(sess,
global_step_tensor))
global_step: 10
```
| Args |
| `sess` | A TensorFlow `Session` object. |
| `global_step_tensor` | `Tensor` or the `name` of the operation that contains the global step. |
| Returns |
| The global step value. |
tensorflow tf.compat.v1.train.MonitoredSession tf.compat.v1.train.MonitoredSession
===================================
Session-like object that handles initialization, recovery and hooks.
```
tf.compat.v1.train.MonitoredSession(
session_creator=None, hooks=None, stop_grace_period_secs=120
)
```
Migrate to TF2
--------------
This API is not compatible with eager execution and [`tf.function`](../../../function). To migrate to TF2, rewrite the code to be compatible with eager execution. Check the [migration guide](https://www.tensorflow.org/guide/migrate#1_replace_v1sessionrun_calls) on replacing `Session.run` calls. In Keras, session hooks can be replaced by Callbacks e.g. [logging hook notebook](https://github.com/tensorflow/docs/blob/master/site/en/guide/migrate/logging_stop_hook.ipynb) For more details please read [Better performance with tf.function](https://www.tensorflow.org/guide/function).
Description
-----------
#### Example usage:
```
saver_hook = CheckpointSaverHook(...)
summary_hook = SummarySaverHook(...)
with MonitoredSession(session_creator=ChiefSessionCreator(...),
hooks=[saver_hook, summary_hook]) as sess:
while not sess.should_stop():
sess.run(train_op)
```
Initialization: At creation time the monitored session does following things in given order:
* calls `hook.begin()` for each given hook
* finalizes the graph via `scaffold.finalize()`
* create session
* initializes the model via initialization ops provided by `Scaffold`
* restores variables if a checkpoint exists
* launches queue runners
* calls `hook.after_create_session()`
Run: When `run()` is called, the monitored session does following things:
* calls `hook.before_run()`
* calls TensorFlow `session.run()` with merged fetches and feed\_dict
* calls `hook.after_run()`
* returns result of `session.run()` asked by user
* if `AbortedError` or `UnavailableError` occurs, it recovers or reinitializes the session before executing the run() call again
Exit: At the `close()`, the monitored session does following things in order:
* calls `hook.end()`
* closes the queue runners and the session
* suppresses `OutOfRange` error which indicates that all inputs have been processed if the monitored\_session is used as a context
How to set [`tf.compat.v1.Session`](../session) arguments:
* In most cases you can set session arguments as follows:
```
MonitoredSession(
session_creator=ChiefSessionCreator(master=..., config=...))
```
* In distributed setting for a non-chief worker, you can use following:
```
MonitoredSession(
session_creator=WorkerSessionCreator(master=..., config=...))
```
See `MonitoredTrainingSession` for an example usage based on chief or worker.
>
> **Note:** This is not a [`tf.compat.v1.Session`](../session). For example, it cannot do following:
>
* it cannot be set as default session.
* it cannot be sent to saver.save.
* it cannot be sent to tf.train.start\_queue\_runners.
| Args |
| `session_creator` | A factory object to create session. Typically a `ChiefSessionCreator` which is the default one. |
| `hooks` | An iterable of `SessionRunHook' objects. |
| Returns |
| A MonitoredSession object. |
| Attributes |
| `graph` | The graph that was launched in this session. |
Child Classes
-------------
[`class StepContext`](monitoredsession/stepcontext)
Methods
-------
### `close`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L884-L885)
```
close()
```
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L768-L786)
```
run(
fetches, feed_dict=None, options=None, run_metadata=None
)
```
Run ops in the monitored session.
This method is completely compatible with the `tf.Session.run()` method.
| Args |
| `fetches` | Same as `tf.Session.run()`. |
| `feed_dict` | Same as `tf.Session.run()`. |
| `options` | Same as `tf.Session.run()`. |
| `run_metadata` | Same as `tf.Session.run()`. |
| Returns |
| Same as `tf.Session.run()`. |
### `run_step_fn`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L788-L842)
```
run_step_fn(
step_fn
)
```
Run ops using a step function.
| Args |
| `step_fn` | A function or a method with a single argument of type `StepContext`. The function may use methods of the argument to perform computations with access to a raw session. The returned value of the `step_fn` will be returned from `run_step_fn`, unless a stop is requested. In that case, the next `should_stop` call will return True. Example usage:
```
```python
with tf.Graph().as_default():
c = tf.compat.v1.placeholder(dtypes.float32)
v = tf.add(c, 4.0)
w = tf.add(c, 0.5)
def step_fn(step_context):
a = step_context.session.run(fetches=v, feed_dict={c: 0.5})
if a <= 4.5:
step_context.request_stop()
return step_context.run_with_hooks(fetches=w,
feed_dict={c: 0.1})
with tf.MonitoredSession() as session:
while not session.should_stop():
a = session.run_step_fn(step_fn)
```
Hooks interact with the `run_with_hooks()` call inside the
`step_fn` as they do with a `MonitoredSession.run` call.
```
|
| Returns |
| Returns the returned value of `step_fn`. |
| Raises |
| `StopIteration` | if `step_fn` has called `request_stop()`. It may be caught by `with tf.MonitoredSession()` to close the session. |
| `ValueError` | if `step_fn` doesn't have a single argument called `step_context`. It may also optionally have `self` for cases when it belongs to an object. |
### `should_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L881-L882)
```
should_stop()
```
### `__enter__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L887-L888)
```
__enter__()
```
### `__exit__`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L890-L895)
```
__exit__(
exception_type, exception_value, traceback
)
```
| programming_docs |
tensorflow tf.compat.v1.train.sdca_fprint tf.compat.v1.train.sdca\_fprint
===============================
Computes fingerprints of the input strings.
```
tf.compat.v1.train.sdca_fprint(
input, name=None
)
```
| Args |
| `input` | A `Tensor` of type `string`. vector of strings to compute fingerprints on. |
| `name` | A name for the operation (optional). |
| Returns |
| A `Tensor` of type `int64`. |
tensorflow tf.compat.v1.train.summary_iterator tf.compat.v1.train.summary\_iterator
====================================
Returns a iterator for reading `Event` protocol buffers from an event file.
```
tf.compat.v1.train.summary_iterator(
path
)
```
You can use this function to read events written to an event file. It returns a Python iterator that yields `Event` protocol buffers.
Example: Print the contents of an events file.
```
for e in tf.compat.v1.train.summary_iterator(path to events file):
print(e)
```
Example: Print selected summary values.
```
# This example supposes that the events file contains summaries with a
# summary value tag 'loss'. These could have been added by calling
# `add_summary()`, passing the output of a scalar summary op created with
# with: `tf.compat.v1.summary.scalar('loss', loss_tensor)`.
for e in tf.compat.v1.train.summary_iterator(path to events file):
for v in e.summary.value:
if v.tag == 'loss':
print(tf.make_ndarray(v.tensor))
```
Example: Continuously check for new summary values.
```
summaries = tf.compat.v1.train.summary_iterator(path to events file)
while True:
for e in summaries:
for v in e.summary.value:
if v.tag == 'loss':
print(tf.make_ndarray(v.tensor))
# Wait for a bit before checking the file for any new events
time.sleep(wait time)
```
See the protocol buffer definitions of [Event](https://www.tensorflow.org/code/tensorflow/core/util/event.proto) and [Summary](https://www.tensorflow.org/code/tensorflow/core/framework/summary.proto) for more information about their attributes.
| Args |
| `path` | The path to an event file created by a `SummaryWriter`. |
| Returns |
| A iterator that yields `Event` protocol buffers |
tensorflow tf.compat.v1.train.noisy_linear_cosine_decay tf.compat.v1.train.noisy\_linear\_cosine\_decay
===============================================
Applies noisy linear cosine decay to the learning rate.
```
tf.compat.v1.train.noisy_linear_cosine_decay(
learning_rate,
global_step,
decay_steps,
initial_variance=1.0,
variance_decay=0.55,
num_periods=0.5,
alpha=0.0,
beta=0.001,
name=None
)
```
Note that linear cosine decay is more aggressive than cosine decay and larger initial learning rates can typically be used.
When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies a noisy linear cosine 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:
```
global_step = min(global_step, decay_steps)
linear_decay = (decay_steps - global_step) / decay_steps)
cosine_decay = 0.5 * (
1 + cos(pi * 2 * num_periods * global_step / decay_steps))
decayed = (alpha + linear_decay + eps_t) * cosine_decay + beta
decayed_learning_rate = learning_rate * decayed
```
where eps\_t is 0-centered gaussian noise with variance initial\_variance / (1 + global\_step) \*\* variance\_decay
#### Example usage:
```
decay_steps = 1000
lr_decayed = noisy_linear_cosine_decay(
learning_rate, global_step, decay_steps)
```
| 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. |
| `decay_steps` | A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. |
| `initial_variance` | initial variance for the noise. See computation above. |
| `variance_decay` | decay for the noise's variance. See computation above. |
| `num_periods` | Number of periods in the cosine part of the decay. See computation above. |
| `alpha` | See computation above. |
| `beta` | See computation above. |
| `name` | String. Optional name of the operation. Defaults to 'NoisyLinearCosineDecay'. |
| Returns |
| A scalar `Tensor` of the same type as `learning_rate`. The decayed learning rate. |
| Raises |
| `ValueError` | if `global_step` is not supplied. |
#### References:
Neural Optimizer Search with Reinforcement Learning: [Bello et al., 2017](http://proceedings.mlr.press/v70/bello17a.html) ([pdf](http://proceedings.mlr.press/v70/bello17a/bello17a.pdf)) Stochastic Gradient Descent with Warm Restarts: [Loshchilov et al., 2017](https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) ([pdf](https://openreview.net/pdf?id=Skq89Scxx))
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.AdagradOptimizer tf.compat.v1.train.AdagradOptimizer
===================================
Optimizer that implements the Adagrad algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.AdagradOptimizer(
learning_rate,
initial_accumulator_value=0.1,
use_locking=False,
name='Adagrad'
)
```
Migrate to TF2
--------------
tf.compat.v1.train.AdagradOptimizer is compatible with eager mode and [`tf.function`](../../../function). When eager execution is enabled, `learning_rate`, `initial_accumulator_value`, and `epsilon` can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions.
To switch to native TF2 style, use [`tf.keras.optimizers.Adagrad`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adagrad) instead. Please notice that due to the implementation differences, [`tf.keras.optimizers.Adagrad`](../../../keras/optimizers/adagrad) and [`tf.compat.v1.train.AdagradOptimizer`](adagradoptimizer) may have slight differences in floating point numerics even though the formula used for the variable updates still matches.
#### Structural mapping to native TF2
Before:
```
optimizer = tf.compat.v1.train.AdagradOptimizer(
learning_rate=learning_rate,
initial_accumulator_value=initial_accumulator_value)
```
After:
```
optimizer = tf.keras.optimizers.Adagrad(
learning_rate=learning_rate,
initial_accumulator_value=initial_accumulator_value,
epsilon=1e-07)
```
#### How to map arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `learning_rate` | `learning_rate` | Be careful of setting learning\_rate tensor value computed from the global step. In TF1 this was usually meant to imply a dynamic learning rate and would recompute in each step. In TF2 (eager + function) it will treat it as a scalar value that only gets computed once instead of a symbolic placeholder to be computed each time. |
| `initial_accumulator_value` | `initial_accumulator_value` | The argument can be value of zero in TF2, which is not accepted in TF1.| |
| - | `epsilon` | `epsilon` is become configurable in TF2. The defualt value is changed from 1e-8 to 1e-7 |
| `use_locking` | - | Not applicable in TF2. |
#### Before & after usage example
Before:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.compat.v1.train.AdagradOptimizer(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
After:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.keras.optimizers.Adagrad(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
Description
-----------
#### References:
Adaptive Subgradient Methods for Online Learning and Stochastic Optimization :[Duchi et al., 2011](http://jmlr.org/papers/v12/duchi11a.html) ([pdf](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf))
| 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. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.SessionManager tf.compat.v1.train.SessionManager
=================================
Training helper that restores from checkpoint and creates session.
```
tf.compat.v1.train.SessionManager(
local_init_op=None,
ready_op=None,
ready_for_local_init_op=None,
graph=None,
recovery_wait_secs=30,
local_init_run_options=None,
local_init_feed_dict=None
)
```
This class is a small wrapper that takes care of session creation and checkpoint recovery. It also provides functions that to facilitate coordination among multiple training threads or processes.
* Checkpointing trained variables as the training progresses.
* Initializing variables on startup, restoring them from the most recent checkpoint after a crash, or wait for checkpoints to become available.
### Usage:
```
with tf.Graph().as_default():
...add operations to the graph...
# Create a SessionManager that will checkpoint the model in '/tmp/mydir'.
sm = SessionManager()
sess = sm.prepare_session(master, init_op, saver, checkpoint_dir)
# Use the session to train the graph.
while True:
sess.run(<my_train_op>)
```
`prepare_session()` initializes or restores a model. It requires `init_op` and `saver` as an argument.
A second process could wait for the model to be ready by doing the following:
```
with tf.Graph().as_default():
...add operations to the graph...
# Create a SessionManager that will wait for the model to become ready.
sm = SessionManager()
sess = sm.wait_for_session(master)
# Use the session to train the graph.
while True:
sess.run(<my_train_op>)
```
`wait_for_session()` waits for a model to be initialized by other processes.
| Args |
| `local_init_op` | An `Operation` run immediately after session creation. Usually used to initialize tables and local variables. |
| `ready_op` | An `Operation` to check if the model is initialized. |
| `ready_for_local_init_op` | An `Operation` to check if the model is ready to run local\_init\_op. |
| `graph` | The `Graph` that the model will use. |
| `recovery_wait_secs` | Seconds between checks for the model to be ready. |
| `local_init_run_options` | RunOptions to be passed to session.run when executing the local\_init\_op. |
| `local_init_feed_dict` | Optional session feed dictionary to use when running the local\_init\_op. |
| Raises |
| `ValueError` | If ready\_for\_local\_init\_op is not None but local\_init\_op is None |
Methods
-------
### `prepare_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/session_manager.py#L251-L341)
```
prepare_session(
master,
init_op=None,
saver=None,
checkpoint_dir=None,
checkpoint_filename_with_path=None,
wait_for_checkpoint=False,
max_wait_secs=7200,
config=None,
init_feed_dict=None,
init_fn=None
)
```
Creates a `Session`. Makes sure the model is ready to be used.
Creates a `Session` on 'master'. If a `saver` object is passed in, and `checkpoint_dir` points to a directory containing valid checkpoint files, then it will try to recover the model from checkpoint. If no checkpoint files are available, and `wait_for_checkpoint` is `True`, then the process would check every `recovery_wait_secs`, up to `max_wait_secs`, for recovery to succeed.
If the model cannot be recovered successfully then it is initialized by running the `init_op` and calling `init_fn` if they are provided. The `local_init_op` is also run after init\_op and init\_fn, regardless of whether the model was recovered successfully, but only if `ready_for_local_init_op` passes.
If the model is recovered from a checkpoint it is assumed that all global variables have been initialized, in particular neither `init_op` nor `init_fn` will be executed.
It is an error if the model cannot be recovered and no `init_op` or `init_fn` or `local_init_op` are passed.
| Args |
| `master` | `String` representation of the TensorFlow master to use. |
| `init_op` | Optional `Operation` used to initialize the model. |
| `saver` | A `Saver` object used to restore a model. |
| `checkpoint_dir` | Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. |
| `checkpoint_filename_with_path` | Full file name path to the checkpoint file. |
| `wait_for_checkpoint` | Whether to wait for checkpoint to become available. |
| `max_wait_secs` | Maximum time to wait for checkpoints to become available. |
| `config` | Optional `ConfigProto` proto used to configure the session. |
| `init_feed_dict` | Optional dictionary that maps `Tensor` objects to feed values. This feed dictionary is passed to the session `run()` call when running the init op. |
| `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 |
| A `Session` object that can be used to drive the model. |
| Raises |
| `RuntimeError` | If the model cannot be initialized or recovered. |
| `ValueError` | If both checkpoint\_dir and checkpoint\_filename\_with\_path are set. |
### `recover_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/session_manager.py#L343-L405)
```
recover_session(
master,
saver=None,
checkpoint_dir=None,
checkpoint_filename_with_path=None,
wait_for_checkpoint=False,
max_wait_secs=7200,
config=None
)
```
Creates a `Session`, recovering if possible.
Creates a new session on 'master'. If the session is not initialized and can be recovered from a checkpoint, recover it.
| Args |
| `master` | `String` representation of the TensorFlow master to use. |
| `saver` | A `Saver` object used to restore a model. |
| `checkpoint_dir` | Path to the checkpoint files. The latest checkpoint in the dir will be used to restore. |
| `checkpoint_filename_with_path` | Full file name path to the checkpoint file. |
| `wait_for_checkpoint` | Whether to wait for checkpoint to become available. |
| `max_wait_secs` | Maximum time to wait for checkpoints to become available. |
| `config` | Optional `ConfigProto` proto used to configure the session. |
| Returns |
| A pair (sess, initialized) where 'initialized' is `True` if the session could be recovered and initialized, `False` otherwise. |
| Raises |
| `ValueError` | If both checkpoint\_dir and checkpoint\_filename\_with\_path are set. |
### `wait_for_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/session_manager.py#L407-L464)
```
wait_for_session(
master, config=None, max_wait_secs=float('Inf')
)
```
Creates a new `Session` and waits for model to be ready.
Creates a new `Session` on 'master'. Waits for the model to be initialized or recovered from a checkpoint. It's expected that another thread or process will make the model ready, and that this is intended to be used by threads/processes that participate in a distributed training configuration where a different thread/process is responsible for initializing or recovering the model being trained.
>
> **Note:** The amount of time this method waits for the session is bounded by max\_wait\_secs. By default, this function will wait indefinitely.
>
| Args |
| `master` | `String` representation of the TensorFlow master to use. |
| `config` | Optional ConfigProto proto used to configure the session. |
| `max_wait_secs` | Maximum time to wait for the session to become available. |
| Returns |
| A `Session`. May be None if the operation exceeds the timeout specified by config.operation\_timeout\_in\_ms. |
| Raises |
| `tf.DeadlineExceededError` | if the session is not available after max\_wait\_secs. |
| programming_docs |
tensorflow tf.compat.v1.train.maybe_shuffle_batch tf.compat.v1.train.maybe\_shuffle\_batch
========================================
Creates batches by randomly shuffling conditionally-enqueued tensors. (deprecated)
```
tf.compat.v1.train.maybe_shuffle_batch(
tensors,
batch_size,
capacity,
min_after_dequeue,
keep_input,
num_threads=1,
seed=None,
enqueue_many=False,
shapes=None,
allow_smaller_final_batch=False,
shared_name=None,
name=None
)
```
See docstring in `shuffle_batch` for more details.
| Args |
| `tensors` | The list or dictionary of tensors to enqueue. |
| `batch_size` | The new batch size pulled from the queue. |
| `capacity` | An integer. The maximum number of elements in the queue. |
| `min_after_dequeue` | Minimum number elements in the queue after a dequeue, used to ensure a level of mixing of elements. |
| `keep_input` | A `bool` Tensor. This tensor controls whether the input is added to the queue or not. If it is a scalar and evaluates `True`, then `tensors` are all added to the queue. If it is a vector and `enqueue_many` is `True`, then each example is added to the queue only if the corresponding value in `keep_input` is `True`. This tensor essentially acts as a filtering mechanism. |
| `num_threads` | The number of threads enqueuing `tensor_list`. |
| `seed` | Seed for the random shuffling within the queue. |
| `enqueue_many` | Whether each tensor in `tensor_list` is a single example. |
| `shapes` | (Optional) The shapes for each example. Defaults to the inferred shapes for `tensor_list`. |
| `allow_smaller_final_batch` | (Optional) Boolean. If `True`, allow the final batch to be smaller if there are insufficient items left in the queue. |
| `shared_name` | (Optional) If set, this queue will be shared under the given name across multiple sessions. |
| `name` | (Optional) A name for the operations. |
| Returns |
| A list or dictionary of tensors with the types as `tensors`. |
| Raises |
| `ValueError` | If the `shapes` are not specified, and cannot be inferred from the elements of `tensors`. |
eager compatibility
-------------------
Input pipelines based on Queues are not supported when eager execution is enabled. Please use the [`tf.data`](../../../data) API to ingest data under eager execution.
tensorflow tf.compat.v1.train.natural_exp_decay tf.compat.v1.train.natural\_exp\_decay
======================================
Applies natural exponential decay to the initial learning rate.
```
tf.compat.v1.train.natural_exp_decay(
learning_rate,
global_step,
decay_steps,
decay_rate,
staircase=False,
name=None
)
```
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:
```
decayed_learning_rate = learning_rate * exp(-decay_rate * global_step /
decay_step)
```
or, if `staircase` is `True`, as:
```
decayed_learning_rate = learning_rate * exp(-decay_rate * floor(global_step /
decay_step))
```
Example: decay exponentially with a base of 0.96:
```
...
global_step = tf.Variable(0, trainable=False)
learning_rate = 0.1
decay_steps = 5
k = 0.5
learning_rate = tf.compat.v1.train.natural_exp_decay(learning_rate,
global_step,
decay_steps, k)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.compat.v1.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step)
)
```
| 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. |
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.cosine_decay tf.compat.v1.train.cosine\_decay
================================
Applies cosine decay to the learning rate.
```
tf.compat.v1.train.cosine_decay(
learning_rate, global_step, decay_steps, alpha=0.0, name=None
)
```
When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies a cosine 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:
```
global_step = min(global_step, decay_steps)
cosine_decay = 0.5 * (1 + cos(pi * global_step / decay_steps))
decayed = (1 - alpha) * cosine_decay + alpha
decayed_learning_rate = learning_rate * decayed
```
#### Example usage:
```
decay_steps = 1000
lr_decayed = cosine_decay(learning_rate, global_step, decay_steps)
```
| 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. |
| `decay_steps` | A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. |
| `alpha` | A scalar `float32` or `float64` Tensor or a Python number. Minimum learning rate value as a fraction of learning\_rate. |
| `name` | String. Optional name of the operation. Defaults to 'CosineDecay'. |
| Returns |
| A scalar `Tensor` of the same type as `learning_rate`. The decayed learning rate. |
| Raises |
| `ValueError` | if `global_step` is not supplied. |
#### References:
Stochastic Gradient Descent with Warm Restarts: [Loshchilov et al., 2017](https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) ([pdf](https://openreview.net/pdf?id=Skq89Scxx))
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.LooperThread tf.compat.v1.train.LooperThread
===============================
A thread that runs code repeatedly, optionally on a timer.
```
tf.compat.v1.train.LooperThread(
coord, timer_interval_secs, target=None, args=None, kwargs=None
)
```
This thread class is intended to be used with a `Coordinator`. It repeatedly runs code specified either as `target` and `args` or by the `run_loop()` method.
Before each run the thread checks if the coordinator has requested stop. In that case the looper thread terminates immediately.
If the code being run raises an exception, that exception is reported to the coordinator and the thread terminates. The coordinator will then request all the other threads it coordinates to stop.
You typically pass looper threads to the supervisor `Join()` method.
| Args |
| `coord` | A Coordinator. |
| `timer_interval_secs` | Time boundaries at which to call Run(), or None if it should be called back to back. |
| `target` | Optional callable object that will be executed in the thread. |
| `args` | Optional arguments to pass to `target` when calling it. |
| `kwargs` | Optional keyword arguments to pass to `target` when calling it. |
| Raises |
| `ValueError` | If one of the arguments is invalid. |
| Attributes |
| `daemon` | A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when only daemon threads are left. |
| `ident` | Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the get\_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. |
| `name` | A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. |
Methods
-------
### `getName`
```
getName()
```
### `isAlive`
```
isAlive()
```
Return whether the thread is alive.
This method is deprecated, use is\_alive() instead.
### `isDaemon`
```
isDaemon()
```
### `is_alive`
```
is_alive()
```
Return whether the thread is alive.
This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads.
### `join`
```
join(
timeout=None
)
```
Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call is\_alive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out.
When the timeout argument is not present or None, the operation will block until the thread terminates.
A thread can be join()ed many times.
join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception.
### `loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/coordinator.py#L455-L477)
```
@staticmethod
loop(
coord, timer_interval_secs, target, args=None, kwargs=None
)
```
Start a LooperThread that calls a function periodically.
If `timer_interval_secs` is None the thread calls `target(args)` repeatedly. Otherwise `target(args)` is called every `timer_interval_secs` seconds. The thread terminates when a stop of the coordinator is requested.
| Args |
| `coord` | A Coordinator. |
| `timer_interval_secs` | Number. Time boundaries at which to call `target`. |
| `target` | A callable object. |
| `args` | Optional arguments to pass to `target` when calling it. |
| `kwargs` | Optional keyword arguments to pass to `target` when calling it. |
| Returns |
| The started thread. |
### `run`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/coordinator.py#L479-L492)
```
run()
```
Method representing the thread's activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
### `run_loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/coordinator.py#L502-L505)
```
run_loop()
```
Called at 'timer\_interval\_secs' boundaries.
### `setDaemon`
```
setDaemon(
daemonic
)
```
### `setName`
```
setName(
name
)
```
### `start`
```
start()
```
Start the thread's activity.
It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the same thread object.
### `start_loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/coordinator.py#L494-L496)
```
start_loop()
```
Called when the thread starts.
### `stop_loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/coordinator.py#L498-L500)
```
stop_loop()
```
Called when the thread stops.
tensorflow tf.compat.v1.train.replica_device_setter tf.compat.v1.train.replica\_device\_setter
==========================================
Return a `device function` to use when building a Graph for replicas.
```
tf.compat.v1.train.replica_device_setter(
ps_tasks=0,
ps_device='/job:ps',
worker_device='/job:worker',
merge_devices=True,
cluster=None,
ps_ops=None,
ps_strategy=None
)
```
Device Functions are used in `with tf.device(device_function):` statement to automatically assign devices to `Operation` objects as they are constructed, Device constraints are added from the inner-most context first, working outwards. The merging behavior adds constraints to fields that are yet unset by a more inner context. Currently the fields are (job, task, cpu/gpu).
If `cluster` is `None`, and `ps_tasks` is 0, the returned function is a no-op. Otherwise, the value of `ps_tasks` is derived from `cluster`.
By default, only Variable ops are placed on ps tasks, and the placement strategy is round-robin over all ps tasks. A custom `ps_strategy` may be used to do more intelligent placement, such as `tf.contrib.training.GreedyLoadBalancingStrategy`.
For example,
```
# To build a cluster with two ps jobs on hosts ps0 and ps1, and 3 worker
# jobs on hosts worker0, worker1 and worker2.
cluster_spec = {
"ps": ["ps0:2222", "ps1:2222"],
"worker": ["worker0:2222", "worker1:2222", "worker2:2222"]}
with
tf.compat.v1.device(tf.compat.v1.train.replica_device_setter(cluster=cluster_spec)):
# Build your graph
v1 = tf.Variable(...) # assigned to /job:ps/task:0
v2 = tf.Variable(...) # assigned to /job:ps/task:1
v3 = tf.Variable(...) # assigned to /job:ps/task:0
# Run compute
```
| Args |
| `ps_tasks` | Number of tasks in the `ps` job. Ignored if `cluster` is provided. |
| `ps_device` | String. Device of the `ps` job. If empty no `ps` job is used. Defaults to `ps`. |
| `worker_device` | String. Device of the `worker` job. If empty no `worker` job is used. |
| `merge_devices` | `Boolean`. If `True`, merges or only sets a device if the device constraint is completely unset. merges device specification rather than overriding them. |
| `cluster` | `ClusterDef` proto or `ClusterSpec`. |
| `ps_ops` | List of strings representing `Operation` types that need to be placed on `ps` devices. If `None`, defaults to `STANDARD_PS_OPS`. |
| `ps_strategy` | A callable invoked for every ps `Operation` (i.e. matched by `ps_ops`), that takes the `Operation` and returns the ps task index to use. If `None`, defaults to a round-robin strategy across all `ps` devices. |
| Returns |
| A function to pass to [`tf.device()`](../../../device). |
| Raises |
| TypeError if `cluster` is not a dictionary or `ClusterDef` protocol buffer, or if `ps_strategy` is provided but not a callable. |
tensorflow tf.compat.v1.train.AdamOptimizer tf.compat.v1.train.AdamOptimizer
================================
Optimizer that implements the Adam algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.AdamOptimizer(
learning_rate=0.001,
beta1=0.9,
beta2=0.999,
epsilon=1e-08,
use_locking=False,
name='Adam'
)
```
Migrate to TF2
--------------
tf.compat.v1.train.AdamOptimizer is compatible with eager mode and [`tf.function`](../../../function). When eager execution is enabled, `learning_rate`, `beta1`, `beta2`, and `epsilon` can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions.
To switch to native TF2 style, use [`tf.keras.optimizers.Adam`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam) instead. Please notice that due to the implementation differences, [`tf.keras.optimizers.Adam`](../../../keras/optimizers/adam) and [`tf.compat.v1.train.AdamOptimizer`](adamoptimizer) may have slight differences in floating point numerics even though the formula used for the variable updates still matches.
#### Structural Mapping to Native TF2
Before:
```
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)
```
After:
```
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
```
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| learning\_rate | learning\_rate | Be careful of setting learning\_rate as a tensor value computed from the global step. In TF1 this was usually meant to imply a dynamic learning rate and would recompute in each step. In TF2 (eager + function) it will treat it as a scalar value that only gets computed once instead of a symbolic placeholder to be computed each time. |
| beta1 | beta\_1 | |
| beta2 | beta\_2 | |
| epsilon | epsilon | Default value is 1e-08 in TF1, but 1e-07 in TF2. |
| use\_locking | N/A | Not applicable in TF2. |
#### Before & After Usage Example
Before:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
After:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
Description
-----------
#### References:
Adam - A Method for Stochastic Optimization: [Kingma et al., 2015](https://arxiv.org/abs/1412.6980) ([pdf](https://arxiv.org/pdf/1412.6980.pdf))
| 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. This epsilon is "epsilon hat" in the Kingma and Ba paper (in the formula just before Section 2.1), not the epsilon in Algorithm 1 of the paper. |
| `use_locking` | If True use locks for update operations. |
| `name` | Optional name for the operations created when applying gradients. Defaults to "Adam". |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
| programming_docs |
tensorflow tf.compat.v1.train.AdadeltaOptimizer tf.compat.v1.train.AdadeltaOptimizer
====================================
Optimizer that implements the Adadelta algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.AdadeltaOptimizer(
learning_rate=0.001,
rho=0.95,
epsilon=1e-08,
use_locking=False,
name='Adadelta'
)
```
Migrate to TF2
--------------
tf.compat.v1.train.AdadeltaOptimizer is compatible with eager mode and [`tf.function`](../../../function). When eager execution is enabled, `learning_rate`, `rho`, and `epsilon` can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions.
To switch to native TF2 style, use [`tf.keras.optimizers.Adadelta`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adadelta) instead. Please notice that due to the implementation differences, [`tf.keras.optimizers.Adadelta`](../../../keras/optimizers/adadelta) and [`tf.compat.v1.train.AdadeltaOptimizer`](adadeltaoptimizer) may have slight differences in floating point numerics even though the formula used for the variable updates still matches.
#### Structural mapping to native TF2
Before:
```
optimizer = tf.compat.v1.train.AdadeltaOptimizer(
learning_rate=learning_rate,
rho=rho,
epsilon=epsilon)
```
After:
```
optimizer = tf.keras.optimizers.Adadelta(
learning_rate=learning_rate,
rho=rho,
epsilon=epsilon)
```
#### How to map arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `learning_rate` | `learning_rate` | Be careful of setting learning\_rate tensor value computed from the global step. In TF1 this was usually meant to imply a dynamic learning rate and would recompute in each step. In TF2 (eager + function) it will treat it as a scalar value that only gets computed once instead of a symbolic placeholder to be computed each time. |
| `rho` | `rho` | - |
| `epsilon` | `epsilon` | Default value is 1e-08 in TF1, but 1e-07 in TF2. |
| `use_locking` | - | Not applicable in TF2. |
#### Before & after usage example
Before:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.compat.v1.train.AdadeltaOptimizer(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
After:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.keras.optimizers.Adadelta(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
Description
-----------
#### References:
ADADELTA - An Adaptive Learning Rate Method: [Zeiler, 2012](http://arxiv.org/abs/1212.5701) ([pdf](http://arxiv.org/pdf/1212.5701v1.pdf))
| Args |
| `learning_rate` | A `Tensor` or a floating point value. The learning rate. To match the exact form in the original paper use 1.0. |
| `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". |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.GradientDescentOptimizer tf.compat.v1.train.GradientDescentOptimizer
===========================================
Optimizer that implements the gradient descent algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.GradientDescentOptimizer(
learning_rate, use_locking=False, name='GradientDescent'
)
```
| 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". |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.Supervisor tf.compat.v1.train.Supervisor
=============================
A training helper that checkpoints models and computes summaries.
```
tf.compat.v1.train.Supervisor(
graph=None,
ready_op=USE_DEFAULT,
ready_for_local_init_op=USE_DEFAULT,
is_chief=True,
init_op=USE_DEFAULT,
init_feed_dict=None,
local_init_op=USE_DEFAULT,
logdir=None,
summary_op=USE_DEFAULT,
saver=USE_DEFAULT,
global_step=USE_DEFAULT,
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=USE_DEFAULT,
init_fn=None,
local_init_run_options=None
)
```
This class is deprecated. Please use [`tf.compat.v1.train.MonitoredTrainingSession`](monitoredtrainingsession) instead.
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
```
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(<my_train_op>)
```
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`](../../../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*.
```
# Choose a task as the chief. This could be based on server_def.task_index,
# or job_def.name, or job_def.tasks. It's entirely up to the end user.
# But there can be only one *chief*.
is_chief = (server_def.task_index == 0)
server = tf.distribute.Server(server_def)
with tf.Graph().as_default():
...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='/shared_directory/...', is_chief=is_chief)
# Get a Session in a TensorFlow server on the cluster.
with sv.managed_session(server.target) as sess:
# Use the session to train the graph.
while not sv.should_stop():
sess.run(<my_train_op>)
```
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. See `tf.train.Server.create_local_server` for details.
* Specifying `'grpc://hostname:port'` requests a session that uses the RPC interface to a specific host, and also allows the in-process master to access remote tensorflow workers. Often, it is appropriate to pass `server.target` (for some [`tf.distribute.Server`](../../../distribute/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()`.
```
...
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 passing `None` to the `summary_op` and `saver` parameters.
Example: Create summaries manually every 100 steps in the chief.
```
# 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 range(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.
| 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.compat.v1.report_uninitialized_variables()`](../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 local\_init\_op. The model is considered ready if it returns an empty array. Defaults to `None`. If `None`, the model is not checked for readiness before running local\_init\_op. |
| `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_op` | `Operation`. Used by chief supervisors to initialize the model when it can not be recovered. Defaults to an `Operation` that initializes all global 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_op` | `Operation`. 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 'global\_step' is used in summaries and checkpoint filenames. Default to the op named 'global\_step' 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_manager` | `SessionManager`, 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_writer` | `SummaryWriter` 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. |
| `local_init_run_options` | RunOptions to be passed as the SessionManager local\_init\_run\_options parameter. |
| Raises |
| `RuntimeError` | If called with eager execution enabled. |
| Attributes |
| `coord` | Return the Coordinator used by the Supervisor. The Coordinator can be useful if you want to run multiple threads during your training. |
| `global_step` | Return the global\_step Tensor used by the supervisor. |
| `init_feed_dict` | Return the feed dictionary used when evaluating the `init_op`. |
| `init_op` | Return the Init Op used by the supervisor. |
| `is_chief` | Return True if this is a chief supervisor. |
| `ready_for_local_init_op` | |
| `ready_op` | Return the Ready Op used by the supervisor. |
| `save_model_secs` | Return the delay between checkpoints. |
| `save_path` | Return the save path used by the supervisor. |
| `save_summaries_secs` | Return the delay between summary computations. |
| `saver` | Return the Saver used by the supervisor. |
| `session_manager` | Return the SessionManager used by the Supervisor. |
| `summary_op` | Return the Summary Tensor used by the chief supervisor. |
| `summary_writer` | Return the SummaryWriter used by the chief supervisor. |
Methods
-------
### `Loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L778-L804)
```
Loop(
timer_interval_secs, target, args=None, kwargs=None
)
```
Start a LooperThread that calls a function periodically.
If `timer_interval_secs` is None the thread calls `target(*args, **kwargs)` repeatedly. Otherwise it calls it every `timer_interval_secs` seconds. The thread terminates when a stop is requested.
The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the `stop()` method.
| Args |
| `timer_interval_secs` | Number. Time boundaries at which to call `target`. |
| `target` | A callable object. |
| `args` | Optional arguments to pass to `target` when calling it. |
| `kwargs` | Optional keyword arguments to pass to `target` when calling it. |
| Returns |
| The started thread. |
### `PrepareSession`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L686-L741)
```
PrepareSession(
master='',
config=None,
wait_for_checkpoint=False,
max_wait_secs=7200,
start_standard_services=True
)
```
Make sure the model is ready to be used.
Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and `start_standard_service` is set to True, also call the session manager to start the standard services.
| Args |
| `master` | name of the TensorFlow master to use. See the [`tf.compat.v1.Session`](../session) constructor for how this is interpreted. |
| `config` | Optional ConfigProto proto used to configure the session, which is passed as-is to create the session. |
| `wait_for_checkpoint` | Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False. |
| `max_wait_secs` | Maximum time to wait for the session to become available. |
| `start_standard_services` | Whether to start the standard services and the queue runners. |
| Returns |
| A Session object that can be used to drive the model. |
### `RequestStop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L845-L855)
```
RequestStop(
ex=None
)
```
Request that the coordinator stop the threads.
See [`Coordinator.request_stop()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#request_stop).
| 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()`. |
### `ShouldStop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L857-L865)
```
ShouldStop()
```
Check if the coordinator was told to stop.
See [`Coordinator.should_stop()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#should_stop).
| Returns |
| True if the coordinator was told to stop, False otherwise. |
### `StartQueueRunners`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L743-L776)
```
StartQueueRunners(
sess, queue_runners=None
)
```
Start threads for `QueueRunners`.
Note that the queue runners collected in the graph key `QUEUE_RUNNERS` are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly.
| Args |
| `sess` | A `Session`. |
| `queue_runners` | A list of `QueueRunners`. If not specified, we'll use the list of queue runners gathered in the graph under the key `GraphKeys.QUEUE_RUNNERS`. |
| Returns |
| The list of threads started for the `QueueRunners`. |
| Raises |
| `RuntimeError` | If called with eager execution enabled. |
#### eager compatibility
Queues are not compatible with eager execution. To ingest data when eager execution is enabled, use the [`tf.data`](../../../data) API.
### `StartStandardServices`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L634-L684)
```
StartStandardServices(
sess
)
```
Start the standard services for 'sess'.
This starts services in the background. The services started depend on the parameters to the constructor and may include:
* A Summary thread computing summaries every save\_summaries\_secs.
* A Checkpoint thread saving the model every save\_model\_secs.
* A StepCounter thread measure step time.
| Args |
| `sess` | A Session. |
| Returns |
| A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join() |
| Raises |
| `RuntimeError` | If called with a non-chief Supervisor. |
| `ValueError` | If not `logdir` was passed to the constructor as the services need a log directory. |
### `Stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L806-L843)
```
Stop(
threads=None, close_summary_writer=True, ignore_live_threads=False
)
```
Stop the services and the coordinator.
This does not close the session.
| Args |
| `threads` | Optional list of threads to join with the coordinator. If `None`, defaults to the threads running the standard services, the threads started for `QueueRunners`, and the threads started by the `loop()` method. To wait on additional threads, pass the list in this parameter. |
| `close_summary_writer` | Whether to close the `summary_writer`. Defaults to `True` if the summary writer was created by the supervisor, `False` otherwise. |
| `ignore_live_threads` | If `True` ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError. |
### `StopOnException`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L867-L875)
```
StopOnException()
```
Context handler to stop the supervisor when an exception is raised.
See [`Coordinator.stop_on_exception()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#stop_on_exception).
| Returns |
| A context handler. |
### `SummaryComputed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L881-L898)
```
SummaryComputed(
sess, summary, global_step=None
)
```
Indicate that a summary was computed.
| Args |
| `sess` | A `Session` object. |
| `summary` | A Summary proto, or a string holding a serialized summary proto. |
| `global_step` | Int. global step this summary is associated with. If `None`, it will try to fetch the current step. |
| Raises |
| `TypeError` | if 'summary' is not a Summary proto or a string. |
| `RuntimeError` | if the Supervisor was created without a `logdir`. |
### `WaitForStop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L877-L879)
```
WaitForStop()
```
Block waiting for the coordinator to stop.
### `loop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L778-L804)
```
loop(
timer_interval_secs, target, args=None, kwargs=None
)
```
Start a LooperThread that calls a function periodically.
If `timer_interval_secs` is None the thread calls `target(*args, **kwargs)` repeatedly. Otherwise it calls it every `timer_interval_secs` seconds. The thread terminates when a stop is requested.
The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the `stop()` method.
| Args |
| `timer_interval_secs` | Number. Time boundaries at which to call `target`. |
| `target` | A callable object. |
| `args` | Optional arguments to pass to `target` when calling it. |
| `kwargs` | Optional keyword arguments to pass to `target` when calling it. |
| Returns |
| The started thread. |
### `managed_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L931-L1019)
```
@contextlib.contextmanager
managed_session(
master='',
config=None,
start_standard_services=True,
close_summary_writer=True
)
```
Returns a context manager for a managed session.
This context manager creates and automatically recovers a session. It optionally starts the standard services that handle checkpoints and summaries. It monitors exceptions raised from the `with` block or from the services and stops the supervisor as needed.
The context manager is typically used as follows:
```
def train():
sv = tf.compat.v1.train.Supervisor(...)
with sv.managed_session(<master>) as sess:
for step in range(..):
if sv.should_stop():
break
sess.run(<my training op>)
...do other things needed at each training step...
```
An exception raised from the `with` block or one of the service threads is raised again when the block exits. This is done after stopping all threads and closing the session. For example, an `AbortedError` exception, raised in case of preemption of one of the workers in a distributed model, is raised again when the block exits.
If you want to retry the training loop in case of preemption you can do it as follows:
```
def main(...):
while True
try:
train()
except tf.errors.Aborted:
pass
```
As a special case, exceptions used for control flow, such as `OutOfRangeError` which reports that input queues are exhausted, are not raised again from the `with` block: they indicate a clean termination of the training loop and are considered normal termination.
| Args |
| `master` | name of the TensorFlow master to use. See the [`tf.compat.v1.Session`](../session) constructor for how this is interpreted. |
| `config` | Optional `ConfigProto` proto used to configure the session. Passed as-is to create the session. |
| `start_standard_services` | Whether to start the standard services, such as checkpoint, summary and step counter. |
| `close_summary_writer` | Whether to close the summary writer when closing the session. Defaults to True. |
| Returns |
| A context manager that yields a `Session` restored from the latest checkpoint or initialized from scratch if not checkpoint exists. The session is closed when the `with` block exits. |
### `prepare_or_wait_for_session`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L686-L741)
```
prepare_or_wait_for_session(
master='',
config=None,
wait_for_checkpoint=False,
max_wait_secs=7200,
start_standard_services=True
)
```
Make sure the model is ready to be used.
Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and `start_standard_service` is set to True, also call the session manager to start the standard services.
| Args |
| `master` | name of the TensorFlow master to use. See the [`tf.compat.v1.Session`](../session) constructor for how this is interpreted. |
| `config` | Optional ConfigProto proto used to configure the session, which is passed as-is to create the session. |
| `wait_for_checkpoint` | Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False. |
| `max_wait_secs` | Maximum time to wait for the session to become available. |
| `start_standard_services` | Whether to start the standard services and the queue runners. |
| Returns |
| A Session object that can be used to drive the model. |
### `request_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L845-L855)
```
request_stop(
ex=None
)
```
Request that the coordinator stop the threads.
See [`Coordinator.request_stop()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#request_stop).
| 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()`. |
### `should_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L857-L865)
```
should_stop()
```
Check if the coordinator was told to stop.
See [`Coordinator.should_stop()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#should_stop).
| Returns |
| True if the coordinator was told to stop, False otherwise. |
### `start_queue_runners`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L743-L776)
```
start_queue_runners(
sess, queue_runners=None
)
```
Start threads for `QueueRunners`.
Note that the queue runners collected in the graph key `QUEUE_RUNNERS` are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitly.
| Args |
| `sess` | A `Session`. |
| `queue_runners` | A list of `QueueRunners`. If not specified, we'll use the list of queue runners gathered in the graph under the key `GraphKeys.QUEUE_RUNNERS`. |
| Returns |
| The list of threads started for the `QueueRunners`. |
| Raises |
| `RuntimeError` | If called with eager execution enabled. |
#### eager compatibility
Queues are not compatible with eager execution. To ingest data when eager execution is enabled, use the [`tf.data`](../../../data) API.
### `start_standard_services`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L634-L684)
```
start_standard_services(
sess
)
```
Start the standard services for 'sess'.
This starts services in the background. The services started depend on the parameters to the constructor and may include:
* A Summary thread computing summaries every save\_summaries\_secs.
* A Checkpoint thread saving the model every save\_model\_secs.
* A StepCounter thread measure step time.
| Args |
| `sess` | A Session. |
| Returns |
| A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join() |
| Raises |
| `RuntimeError` | If called with a non-chief Supervisor. |
| `ValueError` | If not `logdir` was passed to the constructor as the services need a log directory. |
### `stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L806-L843)
```
stop(
threads=None, close_summary_writer=True, ignore_live_threads=False
)
```
Stop the services and the coordinator.
This does not close the session.
| Args |
| `threads` | Optional list of threads to join with the coordinator. If `None`, defaults to the threads running the standard services, the threads started for `QueueRunners`, and the threads started by the `loop()` method. To wait on additional threads, pass the list in this parameter. |
| `close_summary_writer` | Whether to close the `summary_writer`. Defaults to `True` if the summary writer was created by the supervisor, `False` otherwise. |
| `ignore_live_threads` | If `True` ignores threads that remain running after a grace period when joining threads via the coordinator, instead of raising a RuntimeError. |
### `stop_on_exception`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L867-L875)
```
stop_on_exception()
```
Context handler to stop the supervisor when an exception is raised.
See [`Coordinator.stop_on_exception()`](https://www.tensorflow.org/api_docs/python/tf/train/Coordinator#stop_on_exception).
| Returns |
| A context handler. |
### `summary_computed`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L881-L898)
```
summary_computed(
sess, summary, global_step=None
)
```
Indicate that a summary was computed.
| Args |
| `sess` | A `Session` object. |
| `summary` | A Summary proto, or a string holding a serialized summary proto. |
| `global_step` | Int. global step this summary is associated with. If `None`, it will try to fetch the current step. |
| Raises |
| `TypeError` | if 'summary' is not a Summary proto or a string. |
| `RuntimeError` | if the Supervisor was created without a `logdir`. |
### `wait_for_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/supervisor.py#L877-L879)
```
wait_for_stop()
```
Block waiting for the coordinator to stop.
| Class Variables |
| USE\_DEFAULT | `0` |
| programming_docs |
tensorflow tf.compat.v1.train.Checkpoint tf.compat.v1.train.Checkpoint
=============================
Groups trackable objects, saving and restoring them.
```
tf.compat.v1.train.Checkpoint(
**kwargs
)
```
`Checkpoint`'s constructor accepts keyword arguments whose values are types that contain trackable state, such as [`tf.compat.v1.train.Optimizer`](optimizer) implementations, [`tf.Variable`](../../../variable), `tf.keras.Layer` implementations, or [`tf.keras.Model`](../../../keras/model) implementations. It saves these values with a checkpoint, and maintains a `save_counter` for numbering checkpoints.
Example usage when graph building:
```
import tensorflow as tf
import os
checkpoint_directory = "/tmp/training_checkpoints"
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))
train_op = optimizer.minimize( ... )
status.assert_consumed() # Optional sanity checks.
with tf.compat.v1.Session() as session:
# Use the Session to restore variables, or initialize them if
# tf.train.latest_checkpoint returned None.
status.initialize_or_restore(session)
for _ in range(num_training_steps):
session.run(train_op)
checkpoint.save(file_prefix=checkpoint_prefix)
```
Example usage with eager execution enabled:
```
import tensorflow as tf
import os
tf.compat.v1.enable_eager_execution()
checkpoint_directory = "/tmp/training_checkpoints"
checkpoint_prefix = os.path.join(checkpoint_directory, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=model)
status = checkpoint.restore(tf.train.latest_checkpoint(checkpoint_directory))
for _ in range(num_training_steps):
optimizer.minimize( ... ) # Variables will be restored on creation.
status.assert_consumed() # Optional sanity checks.
checkpoint.save(file_prefix=checkpoint_prefix)
```
[`Checkpoint.save`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#save) and [`Checkpoint.restore`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#restore) write and read object-based checkpoints, in contrast to [`tf.compat.v1.train.Saver`](saver) which writes and reads `variable.name` based checkpoints. Object-based checkpointing saves a graph of dependencies between Python objects (`Layer`s, `Optimizer`s, `Variable`s, etc.) with named edges, and this graph is used to match variables when restoring a checkpoint. It can be more robust to changes in the Python program, and helps to support restore-on-create for variables when executing eagerly. Prefer [`tf.train.Checkpoint`](../../../train/checkpoint) over [`tf.compat.v1.train.Saver`](saver) for new code.
`Checkpoint` objects have dependencies on the objects passed as keyword arguments to their constructors, and each dependency is given a name that is identical to the name of the keyword argument for which it was created. TensorFlow classes like `Layer`s and `Optimizer`s will automatically add dependencies on their variables (e.g. "kernel" and "bias" for [`tf.keras.layers.Dense`](../../../keras/layers/dense)). Inheriting from [`tf.keras.Model`](../../../keras/model) makes managing dependencies easy in user-defined classes, since `Model` hooks into attribute assignment. For example:
```
class Regress(tf.keras.Model):
def __init__(self):
super(Regress, self).__init__()
self.input_transform = tf.keras.layers.Dense(10)
# ...
def call(self, inputs):
x = self.input_transform(inputs)
# ...
```
This `Model` has a dependency named "input\_transform" on its `Dense` layer, which in turn depends on its variables. As a result, saving an instance of `Regress` using [`tf.train.Checkpoint`](../../../train/checkpoint) will also save all the variables created by the `Dense` layer.
When variables are assigned to multiple workers, each worker writes its own section of the checkpoint. These sections are then merged/re-indexed to behave as a single checkpoint. This avoids copying all variables to one worker, but does require that all workers see a common filesystem.
While [`tf.keras.Model.save_weights`](../../../keras/model#save_weights) and [`tf.train.Checkpoint.save`](../../../train/checkpoint#save) save in the same format, note that the root of the resulting checkpoint is the object the save method is attached to. This means saving a [`tf.keras.Model`](../../../keras/model) using `save_weights` and loading into a [`tf.train.Checkpoint`](../../../train/checkpoint) with a `Model` attached (or vice versa) will not match the `Model`'s variables. See the [guide to training checkpoints](https://www.tensorflow.org/guide/checkpoint) for details. Prefer [`tf.train.Checkpoint`](../../../train/checkpoint) over [`tf.keras.Model.save_weights`](../../../keras/model#save_weights) for training checkpoints.
| Args |
| `**kwargs` | Keyword arguments are set as attributes of this object, and are saved with the checkpoint. Values must be trackable objects. |
| Raises |
| `ValueError` | If objects in `kwargs` are not trackable. |
| Attributes |
| `save_counter` | Incremented when `save()` is called. Used to number checkpoints. |
Methods
-------
### `restore`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/tracking/util.py#L1850-L1972)
```
restore(
save_path
)
```
Restore a training checkpoint.
Restores this `Checkpoint` and any objects it depends on.
When executing eagerly, either assigns values immediately if variables to restore have been created already, or defers restoration until the variables are created. Dependencies added after this call will be matched if they have a corresponding object in the checkpoint (the restore request will queue in any trackable object waiting for the expected dependency to be added).
When graph building, restoration ops are added to the graph but not run immediately.
```
checkpoint = tf.train.Checkpoint( ... )
checkpoint.restore(path)
```
To ensure that loading is complete and no more deferred restorations will take place, you can use the `assert_consumed()` method of the status object returned by `restore`. The assert will raise an exception if any Python objects in the dependency graph were not found in the checkpoint, or if any checkpointed values do not have a matching Python object:
```
checkpoint = tf.train.Checkpoint( ... )
checkpoint.restore(path).assert_consumed()
```
When graph building, `assert_consumed()` indicates that all of the restore ops that will be created for this checkpoint have been created. They can be run via the `run_restore_ops()` method of the status object:
```
checkpoint.restore(path).assert_consumed().run_restore_ops()
```
If the checkpoint has not been consumed completely, then the list of restore ops will grow as more objects are added to the dependency graph.
To check that all variables in the Python object have restored values from checkpoint, use `assert_existing_objects_matched()`. This assertion is useful when called after the variables in your graph have been created.
Name-based [`tf.compat.v1.train.Saver`](saver) checkpoints can be loaded using this method. Names are used to match variables. No restore ops are created/run until `run_restore_ops()` or `initialize_or_restore()` are called on the returned status object when graph building, but there is restore-on-creation when executing eagerly. Re-encode name-based checkpoints using [`tf.train.Checkpoint.save`](../../../train/checkpoint#save) as soon as possible.
| Args |
| `save_path` | The path to the checkpoint, as returned by `save` or [`tf.train.latest_checkpoint`](../../../train/latest_checkpoint). If None (as when there is no latest checkpoint for [`tf.train.latest_checkpoint`](../../../train/latest_checkpoint) to return), returns an object which may run initializers for objects in the dependency graph. If the checkpoint was written by the name-based [`tf.compat.v1.train.Saver`](saver), names are used to match variables. |
| Returns |
| A load status object, which can be used to make assertions about the status of a checkpoint restoration and run initialization/restore ops. The returned status object has the following methods:* `assert_consumed()`: Raises an exception if any variables are unmatched: either checkpointed values which don't have a matching Python object or Python objects in the dependency graph with no values in the checkpoint. This method returns the status object, and so may be chained with `initialize_or_restore` or `run_restore_ops`.
* `assert_existing_objects_matched()`: Raises an exception if any existing Python objects in the dependency graph are unmatched. Unlike `assert_consumed`, this assertion will pass if values in the checkpoint have no corresponding Python objects. For example a `tf.keras.Layer` object which has not yet been built, and so has not created any variables, will pass this assertion but will fail `assert_consumed`. Useful when loading part of a larger checkpoint into a new Python program, e.g. a training checkpoint with a [`tf.compat.v1.train.Optimizer`](optimizer) was saved but only the state required for inference is being loaded. This method returns the status object, and so may be chained with `initialize_or_restore` or `run_restore_ops`.
* `assert_nontrivial_match()`: Asserts that something aside from the root object was matched. This is a very weak assertion, but is useful for sanity checking in library code where objects may exist in the checkpoint which haven't been created in Python and some Python objects may not have a checkpointed value.
* `expect_partial()`: Silence warnings about incomplete checkpoint restores. Warnings are otherwise printed for unused parts of the checkpoint file or object when the `Checkpoint` object is deleted (often at program shutdown).
* `initialize_or_restore(session=None)`: When graph building, runs variable initializers if `save_path` is `None`, but otherwise runs restore operations. If no `session` is explicitly specified, the default session is used. No effect when executing eagerly (variables are initialized or restored eagerly).
* `run_restore_ops(session=None)`: When graph building, runs restore operations. If no `session` is explicitly specified, the default session is used. No effect when executing eagerly (restore operations are run eagerly). May only be called when `save_path` is not `None`.
|
### `save`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/tracking/util.py#L1790-L1848)
```
save(
file_prefix, session=None
)
```
Saves a training checkpoint and provides basic checkpoint management.
The saved checkpoint includes variables created by this object and any trackable objects it depends on at the time [`Checkpoint.save()`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#save) is called.
`save` is a basic convenience wrapper around the `write` method, sequentially numbering checkpoints using `save_counter` and updating the metadata used by [`tf.train.latest_checkpoint`](../../../train/latest_checkpoint). More advanced checkpoint management, for example garbage collection and custom numbering, may be provided by other utilities which also wrap `write` ([`tf.train.CheckpointManager`](../../../train/checkpointmanager) for example).
| Args |
| `file_prefix` | A prefix to use for the checkpoint filenames (/path/to/directory/and\_a\_prefix). Names are generated based on this prefix and [`Checkpoint.save_counter`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#save_counter). |
| `session` | The session to evaluate variables in. Ignored when executing eagerly. If not provided when graph building, the default session is used. |
| Returns |
| The full path to the checkpoint. |
### `write`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/tracking/util.py#L1728-L1776)
```
write(
file_prefix, session=None
)
```
Writes a training checkpoint.
The checkpoint includes variables created by this object and any trackable objects it depends on at the time [`Checkpoint.write()`](https://www.tensorflow.org/api_docs/python/tf/train/Checkpoint#write) is called.
`write` does not number checkpoints, increment `save_counter`, or update the metadata used by [`tf.train.latest_checkpoint`](../../../train/latest_checkpoint). It is primarily intended for use by higher level checkpoint management utilities. `save` provides a very basic implementation of these features.
| Args |
| `file_prefix` | A prefix to use for the checkpoint filenames (/path/to/directory/and\_a\_prefix). |
| `session` | The session to evaluate variables in. Ignored when executing eagerly. If not provided when graph building, the default session is used. |
| Returns |
| The full path to the checkpoint (i.e. `file_prefix`). |
tensorflow tf.compat.v1.train.cosine_decay_restarts tf.compat.v1.train.cosine\_decay\_restarts
==========================================
Applies cosine decay with restarts to the learning rate.
```
tf.compat.v1.train.cosine_decay_restarts(
learning_rate,
global_step,
first_decay_steps,
t_mul=2.0,
m_mul=1.0,
alpha=0.0,
name=None
)
```
When training a model, it is often recommended to lower the learning rate as the training progresses. This function applies a cosine decay function with restarts 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 while taking into account possible warm restarts. The learning rate multiplier first decays from 1 to `alpha` for `first_decay_steps` steps. Then, a warm restart is performed. Each new warm restart runs for `t_mul` times more steps and with `m_mul` times smaller initial learning rate.
#### Example usage:
```
first_decay_steps = 1000
lr_decayed = cosine_decay_restarts(learning_rate, global_step,
first_decay_steps)
```
| 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. |
| `first_decay_steps` | A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. |
| `t_mul` | A scalar `float32` or `float64` `Tensor` or a Python number. Used to derive the number of iterations in the i-th period |
| `m_mul` | A scalar `float32` or `float64` `Tensor` or a Python number. Used to derive the initial learning rate of the i-th period: |
| `alpha` | A scalar `float32` or `float64` Tensor or a Python number. Minimum learning rate value as a fraction of the learning\_rate. |
| `name` | String. Optional name of the operation. Defaults to 'SGDRDecay'. |
| Returns |
| A scalar `Tensor` of the same type as `learning_rate`. The decayed learning rate. |
| Raises |
| `ValueError` | if `global_step` is not supplied. |
#### References:
Stochastic Gradient Descent with Warm Restarts: [Loshchilov et al., 2017](https://openreview.net/forum?id=Skq89Scxx¬eId=Skq89Scxx) ([pdf](https://openreview.net/pdf?id=Skq89Scxx))
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.FtrlOptimizer tf.compat.v1.train.FtrlOptimizer
================================
Optimizer that implements the FTRL algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.FtrlOptimizer(
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',
accum_name=None,
linear_name=None,
l2_shrinkage_regularization_strength=0.0,
beta=None
)
```
This version has support for both online L2 (McMahan et al., 2013) and shrinkage-type L2, which is the addition of an L2 penalty to the loss function.
#### References:
Ad-click prediction: [McMahan et al., 2013](https://dl.acm.org/citation.cfm?id=2488200) ([pdf](https://dl.acm.org/ft_gateway.cfm?id=2488200&ftid=1388399&dwn=1&CFID=32233078&CFTOKEN=d60fe57a294c056a-CB75C374-F915-E7A6-1573FBBC7BF7D526))
| Args |
| `learning_rate` | A float value or a constant float `Tensor`. |
| `learning_rate_power` | A float value, must be less or equal to zero. Controls how the learning rate decreases during training. Use zero for a fixed learning rate. See section 3.1 in (McMahan et al., 2013). |
| `initial_accumulator_value` | The starting value for accumulators. Only zero or 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". |
| `accum_name` | The suffix for the variable that keeps the gradient squared accumulator. If not present, defaults to name. |
| `linear_name` | The suffix for the variable that keeps the linear gradient accumulator. If not present, defaults to name + "*1".* |
| `l2_shrinkage_regularization_strength` | A float value, must be greater than or equal to zero. This differs from L2 above in that the L2 above is a stabilization penalty, whereas this L2 shrinkage is a magnitude penalty. The FTRL formulation can be written as: w{t+1} = argmin*w(\hat{g}*{1:t}w + L1*||w||\_1 + L2*||w||\_2^2), where \hat{g} = g + (2*L2\_shrinkage*w), and g is the gradient of the loss function w.r.t. the weights w. Specifically, in the absence of L1 regularization, it is equivalent to the following update rule: w\_{t+1} = w\_t - lr\_t / (beta + 2*L2*lr\_t) \* g\_t - 2*L2\_shrinkage*lr\_t / (beta + 2*L2*lr\_t) \* w\_t where lr\_t is the learning rate at t. When input is sparse shrinkage will only happen on the active weights. |
| `beta` | A float value; corresponds to the beta parameter in the paper. |
| Raises |
| `ValueError` | If one of the arguments is invalid. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
| programming_docs |
tensorflow tf.compat.v1.train.checkpoint_exists tf.compat.v1.train.checkpoint\_exists
=====================================
Checks whether a V1 or V2 checkpoint exists with the specified prefix. (deprecated)
```
tf.compat.v1.train.checkpoint_exists(
checkpoint_prefix
)
```
This is the recommended way to check if a checkpoint exists, since it takes into account the naming difference between V1 and V2 formats.
| Args |
| `checkpoint_prefix` | the prefix of a V1 or V2 checkpoint, with V2 taking priority. Typically the result of `Saver.save()` or that of [`tf.train.latest_checkpoint()`](../../../train/latest_checkpoint), regardless of sharded/non-sharded or V1/V2. |
| Returns |
| A bool, true if a checkpoint referred to by `checkpoint_prefix` exists. |
tensorflow tf.compat.v1.train.polynomial_decay tf.compat.v1.train.polynomial\_decay
====================================
Applies a polynomial decay to the learning rate.
```
tf.compat.v1.train.polynomial_decay(
learning_rate,
global_step,
decay_steps,
end_learning_rate=0.0001,
power=1.0,
cycle=False,
name=None
)
```
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:
```
global_step = min(global_step, decay_steps)
decayed_learning_rate = (learning_rate - end_learning_rate) *
(1 - global_step / decay_steps) ^ (power) +
end_learning_rate
```
If `cycle` is True then a multiple of `decay_steps` is used, the first one that is bigger than `global_steps`.
```
decay_steps = decay_steps * ceil(global_step / decay_steps)
decayed_learning_rate = (learning_rate - end_learning_rate) *
(1 - global_step / decay_steps) ^ (power) +
end_learning_rate
```
Example: decay from 0.1 to 0.01 in 10000 steps using sqrt (i.e. power=0.5):
```
...
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.1
end_learning_rate = 0.01
decay_steps = 10000
learning_rate = tf.compat.v1.train.polynomial_decay(starter_learning_rate,
global_step,
decay_steps, end_learning_rate,
power=0.5)
# Passing global_step to minimize() will increment it at each step.
learning_step = (
tf.compat.v1.train.GradientDescentOptimizer(learning_rate)
.minimize(...my loss..., global_step=global_step)
)
```
| 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 linear, 1.0. |
| `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. |
eager compatibility
-------------------
When eager execution is enabled, this function returns a function which in turn returns the decayed learning rate Tensor. This can be useful for changing the learning rate value across different invocations of optimizer functions.
tensorflow tf.compat.v1.train.RMSPropOptimizer tf.compat.v1.train.RMSPropOptimizer
===================================
Optimizer that implements the RMSProp algorithm (Tielemans et al.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.RMSPropOptimizer(
learning_rate,
decay=0.9,
momentum=0.0,
epsilon=1e-10,
use_locking=False,
centered=False,
name='RMSProp'
)
```
Migrate to TF2
--------------
tf.compat.v1.train.RMSPropOptimizer is compatible with eager mode and [`tf.function`](../../../function). When eager execution is enabled, `learning_rate`, `decay`, `momentum`, and `epsilon` can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions.
To switch to native TF2 style, use [`tf.keras.optimizers.RMSprop`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/RMSprop) instead. Please notice that due to the implementation differences, [`tf.keras.optimizers.RMSprop`](../../../keras/optimizers/rmsprop) and [`tf.compat.v1.train.RMSPropOptimizer`](rmspropoptimizer) may have slight differences in floating point numerics even though the formula used for the variable updates still matches.
#### Structural mapping to native TF2
Before:
```
optimizer = tf.compat.v1.train.RMSPropOptimizer(
learning_rate=learning_rate,
decay=decay,
momentum=momentum,
epsilon=epsilon)
```
After:
```
optimizer = tf.keras.optimizers.RMSprop(
learning_rate=learning_rate,
rho=decay,
momentum=momentum,
epsilon=epsilon)
```
#### How to map arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `learning_rate` | `learning_rate` | Be careful of setting learning\_rate tensor value computed from the global step. In TF1 this was usually meant to imply a dynamic learning rate and would recompute in each step. In TF2 (eager + function) it will treat it as a scalar value that only gets computed once instead of a symbolic placeholder to be computed each time. |
| `decay` | `rho` | - |
| `momentum` | `momentum` | - |
| `epsilon` | `epsilon` | Default value is 1e-10 in TF1, but 1e-07 in TF2. |
| `use_locking` | - | Not applicable in TF2. |
#### Before & after usage example
Before:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.compat.v1.train.RMSPropOptimizer(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
After:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.keras.optimizers.RMSprop(learning_rate=0.001)
optimizer.apply_gradients(zip([grad], [x]))
```
Description
-----------
2012).
#### References:
Coursera slide 29: Hinton, 2012 ([pdf](http://www.cs.toronto.edu/%7Etijmen/csc321/slides/lecture_slides_lec6.pdf))
| 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". |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
tensorflow tf.compat.v1.train.SaverDef tf.compat.v1.train.SaverDef
===========================
A ProtocolMessage
| Attributes |
| `filename_tensor_name` | `string filename_tensor_name` |
| `keep_checkpoint_every_n_hours` | `float keep_checkpoint_every_n_hours` |
| `max_to_keep` | `int32 max_to_keep` |
| `restore_op_name` | `string restore_op_name` |
| `save_tensor_name` | `string save_tensor_name` |
| `sharded` | `bool sharded` |
| `version` | `CheckpointFormatVersion version` |
| Class Variables |
| CheckpointFormatVersion | Instance of `google.protobuf.internal.enum_type_wrapper.EnumTypeWrapper` |
| LEGACY | `0` |
| V1 | `1` |
| V2 | `2` |
tensorflow tf.compat.v1.train.get_checkpoint_mtimes tf.compat.v1.train.get\_checkpoint\_mtimes
==========================================
Returns the mtimes (modification timestamps) of the checkpoints. (deprecated)
```
tf.compat.v1.train.get_checkpoint_mtimes(
checkpoint_prefixes
)
```
Globs for the checkpoints pointed to by `checkpoint_prefixes`. If the files exist, collect their mtime. Both V2 and V1 checkpoints are considered, in that priority.
This is the recommended way to get the mtimes, since it takes into account the naming difference between V1 and V2 formats.
>
> **Note:** If not all checkpoints exist, the length of the returned mtimes list will be smaller than the length of `checkpoint_prefixes` list, so mapping checkpoints to corresponding mtimes will not be possible.
>
| Args |
| `checkpoint_prefixes` | a list of checkpoint paths, typically the results of `Saver.save()` or those of [`tf.train.latest_checkpoint()`](../../../train/latest_checkpoint), regardless of sharded/non-sharded or V1/V2. |
| Returns |
| A list of mtimes (in microseconds) of the found checkpoints. |
tensorflow tf.compat.v1.train.NewCheckpointReader tf.compat.v1.train.NewCheckpointReader
======================================
A function that returns a CheckPointReader.
```
tf.compat.v1.train.NewCheckpointReader(
filepattern
)
```
| Args |
| `filepattern` | The filename. |
| Returns |
| A CheckpointReader object. |
tensorflow tf.compat.v1.train.MomentumOptimizer tf.compat.v1.train.MomentumOptimizer
====================================
Optimizer that implements the Momentum algorithm.
Inherits From: [`Optimizer`](optimizer)
```
tf.compat.v1.train.MomentumOptimizer(
learning_rate,
momentum,
use_locking=False,
name='Momentum',
use_nesterov=False
)
```
Migrate to TF2
--------------
tf.compat.v1.train.MomentumOptimizer is compatible with eager mode and [`tf.function`](../../../function). When eager execution is enabled, `learning_rate`,`momentum`, can each be a callable that takes no arguments and returns the actual value to use. This can be useful for changing these values across different invocations of optimizer functions.
To switch to native TF2 style, please directly use [`tf.keras.optimizers.SGD`](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/SGD) with the `momentum` argument.
#### Structural mapping to native TF2
Before:
```
optimizer = tf.compat.v1.train.MomentumOptimizer(
learning_rate=learning_rate,
momentum=momentum,
use_nesterov=use_nesterov)
```
After:
```
optimizer = tf.keras.optimizers.SGD(
learning_rate=learning_rate,
momentum=momentum,
nesterov=use_nesterov)
```
#### How to map arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `learning_rate` | `learning_rate` | Be careful of setting learning\_rate tensor value computed from the global step. In TF1 this was usually meant to imply a dynamic learning rate and would recompute in each step. In TF2 (eager + function) it will treat it as a scalar value that only gets computed once instead of a symbolic placeholder to be computed each time. |
| `momentum` | `momentum` | - |
| `use_locking` | - | Not applicable in TF2. |
| `use_nesterov` | `nesterov` | - |
#### Before & after usage example
Before:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.compat.v1.train.MomentumOptimizer(
learning_rate=0.001,
momentum=0.9,
use_nesterov=False)
optimizer.apply_gradients(zip([grad], [x]))
```
After:
```
x = tf.Variable([1,2,3], dtype=tf.float32)
grad = tf.constant([0.1, 0.2, 0.3])
optimizer = tf.keras.optimizers.SGD(
learning_rate=0.001,
momentum=0.9,
nesterov=False)
optimizer.apply_gradients(zip([grad], [x]))
```
Description
-----------
Computes (if `use_nesterov = False`):
```
accumulation = momentum * accumulation + gradient
variable -= learning_rate * accumulation
```
Note that in the dense version of this algorithm, `accumulation` is updated and applied regardless of a gradient's value, whereas the sparse version (when the gradient is an `IndexedSlices`, typically because of [`tf.gather`](../../../gather) or an embedding) only updates variable slices and corresponding `accumulation` terms when that part of the variable was used in the forward pass.
| 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". |
| `use_nesterov` | If `True` use Nesterov Momentum. See (Sutskever et al., 2013). This implementation always computes gradients at the value of the variable(s) passed to the optimizer. Using Nesterov Momentum makes the variable(s) track the values called `theta_t + mu*v_t` in the paper. This implementation is an approximation of the original formula, valid for high values of momentum. It will compute the "adjusted gradient" in NAG by assuming that the new gradient will be estimated by the current average gradient plus the product of momentum and the change in the average gradient. |
Methods
-------
### `apply_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L626-L744)
```
apply_gradients(
grads_and_vars, global_step=None, name=None
)
```
Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that applies gradients.
@compatibility(TF2)
#### How to Map Arguments
| TF1 Arg Name | TF2 Arg Name | Note |
| --- | --- | --- |
| `grads_and_vars` | `grads_and_vars` | - |
| `global_step` | Not supported. | Use `optimizer.iterations` |
| `name` | `name.` | - |
| 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. |
| `RuntimeError` | If you should use `_distributed_apply()` instead. |
### `compute_gradients`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L493-L614)
```
compute_gradients(
loss,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None
)
```
Compute gradients of `loss` for the variables in `var_list`.
#### Migrate to TF2
[`tf.keras.optimizers.Optimizer`](../../../keras/optimizers/optimizer) in TF2 does not provide a `compute_gradients` method, and you should use a [`tf.GradientTape`](../../../gradienttape) to obtain the gradients:
```
@tf.function
def train step(inputs):
batch_data, labels = inputs
with tf.GradientTape() as tape:
predictions = model(batch_data, training=True)
loss = tf.keras.losses.CategoricalCrossentropy(
reduction=tf.keras.losses.Reduction.NONE)(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
```
Args: loss: A Tensor containing the value to minimize or a callable taking no arguments which returns the value to minimize. When eager execution is enabled it must be a callable. var\_list: Optional list or tuple of [`tf.Variable`](../../../variable) to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. gate\_gradients: How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. RuntimeError: If called with eager execution enabled and `loss` is not callable.
@compatibility(eager) When eager execution is enabled, `gate_gradients`, `aggregation_method`, and `colocate_gradients_with_ops` are ignored.
#### Description
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.
### `get_name`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L430-L431)
```
get_name()
```
### `get_slot`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L841-L867)
```
get_slot(
var, name
)
```
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. |
### `get_slot_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L869-L877)
```
get_slot_names()
```
Return a list of the names of slots created by the `Optimizer`.
See `get_slot()`.
| Returns |
| A list of strings. |
### `minimize`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L433-L491)
```
minimize(
loss,
global_step=None,
var_list=None,
gate_gradients=GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
name=None,
grad_loss=None
)
```
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 call `compute_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 or tuple of `Variable` objects to update to minimize `loss`. Defaults to the list of variables collected in the graph under the key `GraphKeys.TRAINABLE_VARIABLES`. |
| `gate_gradients` | How to gate the computation of gradients. Can be `GATE_NONE`, `GATE_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. |
#### eager compatibility
When eager execution is enabled, `loss` should be a Python function that takes no arguments and computes the value to be minimized. Minimization (and gradient computation) is done with respect to the elements of `var_list` if not None, else with respect to any trainable variables created during the execution of the `loss` function. `gate_gradients`, `aggregation_method`, `colocate_gradients_with_ops` and `grad_loss` are ignored when eager execution is enabled.
### `variables`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/optimizer.py#L879-L905)
```
variables()
```
A list of variables which encode the current state of `Optimizer`.
Includes slot variables and additional global variables created by the optimizer in the current default graph.
| Returns |
| A list of variables. |
| Class Variables |
| GATE\_GRAPH | `2` |
| GATE\_NONE | `0` |
| GATE\_OP | `1` |
| programming_docs |
tensorflow tf.compat.v1.train.init_from_checkpoint tf.compat.v1.train.init\_from\_checkpoint
=========================================
Replaces [`tf.Variable`](../../../variable) initializers so they load from a checkpoint file.
```
tf.compat.v1.train.init_from_checkpoint(
ckpt_dir_or_file, assignment_map
)
```
Migrate to TF2
--------------
[`tf.compat.v1.train.init_from_checkpoint`](init_from_checkpoint) is not recommended for restoring variable values in TF2.
To restore checkpoints in TF2, please use [`tf.keras.Model.load_weights`](../../../keras/model#load_weights) or [`tf.train.Checkpoint.restore`](../../../train/checkpoint#restore). These APIs use use an [object-based method of checkpointing](https://www.tensorflow.org/guide/checkpoint#loading_mechanics), while `tf.compat.v1.init_from_checkpoint` relies on a more-fragile variable-name based method of checkpointing. There is no object-based equivalent of `init_from_checkpoint` in TF2.
Please re-write your checkpoints immediately using the object-based APIs, see [migration guide](https://www.tensorflow.org/guide/migrate#checkpoint_compatibility) for more details.
You can load a name-based checkpoint written by [`tf.compat.v1.train.Saver`](saver) using [`tf.train.Checkpoint.restore`](../../../train/checkpoint#restore) or [`tf.keras.Model.load_weights`](../../../keras/model#load_weights). However, you may have to change the names of the variables in your model to match the variable names in the name-based checkpoint, which can be viewed with [`tf.train.list_variables(path)`](../../../train/list_variables).
Another option is to create an `assignment_map` that maps the name of the variables in the name-based checkpoint to the variables in your model, eg:
```
{
'sequential/dense/bias': model.variables[0],
'sequential/dense/kernel': model.variables[1]
}
```
and use [`tf.compat.v1.train.init_from_checkpoint(path, assignment_map)`](init_from_checkpoint) to restore the name-based checkpoint.
After restoring, re-encode your checkpoint using [`tf.train.Checkpoint.save`](../../../train/checkpoint#save) or [`tf.keras.Model.save_weights`](../../../keras/model#save_weights).
Description
-----------
Values are not loaded immediately, but when the initializer is run (typically by running a [`tf.compat.v1.global_variables_initializer`](../global_variables_initializer) op).
>
> **Note:** This overrides default initialization ops of specified variables and redefines dtype.
>
Assignment map supports following syntax:
* `'checkpoint_scope_name/': 'scope_name/'` - will load all variables in current `scope_name` from `checkpoint_scope_name` with matching tensor names.
* `'checkpoint_scope_name/some_other_variable': 'scope_name/variable_name'` - will initialize `scope_name/variable_name` variable from `checkpoint_scope_name/some_other_variable`.
* `'scope_variable_name': variable` - will initialize given [`tf.Variable`](../../../variable) object with tensor 'scope\_variable\_name' from the checkpoint.
* `'scope_variable_name': list(variable)` - will initialize list of partitioned variables with tensor 'scope\_variable\_name' from the checkpoint.
* `'/': 'scope_name/'` - will load all variables in current `scope_name` from checkpoint's root (e.g. no scope).
Supports loading into partitioned variables, which are represented as `'<variable>/part_<part #>'`.
Assignment map can be a dict, or a list of pairs. The latter is necessary to initialize multiple variables in the current graph from the same variable in the checkpoint.
#### Example:
```
# Say, '/tmp/model.ckpt' has the following tensors:
# -- name='old_scope_1/var1', shape=[20, 2]
# -- name='old_scope_1/var2', shape=[50, 4]
# -- name='old_scope_2/var3', shape=[100, 100]
# Create new model's variables
with tf.compat.v1.variable_scope('new_scope_1'):
var1 = tf.compat.v1.get_variable('var1', shape=[20, 2],
initializer=tf.compat.v1.zeros_initializer())
with tf.compat.v1.variable_scope('new_scope_2'):
var2 = tf.compat.v1.get_variable('var2', shape=[50, 4],
initializer=tf.compat.v1.zeros_initializer())
# Partition into 5 variables along the first axis.
var3 = tf.compat.v1.get_variable(name='var3', shape=[100, 100],
initializer=tf.compat.v1.zeros_initializer(),
partitioner=lambda shape, dtype: [5, 1])
# Initialize all variables in `new_scope_1` from `old_scope_1`.
init_from_checkpoint('/tmp/model.ckpt', {'old_scope_1/': 'new_scope_1/'})
# Use names to specify which variables to initialize from checkpoint.
init_from_checkpoint('/tmp/model.ckpt',
{'old_scope_1/var1': 'new_scope_1/var1',
'old_scope_1/var2': 'new_scope_2/var2'})
# Or use tf.Variable objects to identify what to initialize.
init_from_checkpoint('/tmp/model.ckpt',
{'old_scope_1/var1': var1,
'old_scope_1/var2': var2})
# Initialize partitioned variables using variable's name
init_from_checkpoint('/tmp/model.ckpt',
{'old_scope_2/var3': 'new_scope_2/var3'})
# Or specify the list of tf.Variable objects.
init_from_checkpoint('/tmp/model.ckpt',
{'old_scope_2/var3': var3._get_variable_list()})
```
| Args |
| `ckpt_dir_or_file` | Directory with checkpoints file or path to checkpoint. |
| `assignment_map` | Dict, or a list of key-value pairs, where keys are names of the variables in the checkpoint and values are current variables or names of current variables (in default graph). |
| Raises |
| `ValueError` | If missing variables in current graph, or if missing checkpoints or tensors in checkpoints. |
tensorflow tf.compat.v1.train.MonitoredSession.StepContext tf.compat.v1.train.MonitoredSession.StepContext
===============================================
Control flow instrument for the `step_fn` from `run_step_fn()`.
#### View aliases
**Compat aliases for migration**
See [Migration guide](https://www.tensorflow.org/guide/migrate) for more details.
[`tf.compat.v1.train.SingularMonitoredSession.StepContext`](https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/MonitoredSession/StepContext)
```
tf.compat.v1.train.MonitoredSession.StepContext(
session, run_with_hooks_fn
)
```
Users of `step_fn` may perform `run()` calls without running hooks by accessing the `session`. A `run()` call with hooks may be performed using `run_with_hooks()`. Computation flow can be interrupted using `request_stop()`.
| Args |
| `session` | An instance of [`tf.compat.v1.Session`](../../session). |
| `run_with_hooks_fn` | A function for running fetches and hooks. |
| Attributes |
| `session` | |
Methods
-------
### `request_stop`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L871-L879)
```
request_stop()
```
Exit the training loop by causing `should_stop()` to return `True`.
Causes `step_fn` to exit by raising an exception.
| Raises |
| StopIteration |
### `run_with_hooks`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/training/monitored_session.py#L867-L869)
```
run_with_hooks(
*args, **kwargs
)
```
Same as `MonitoredSession.run`. Accepts the same arguments.
tensorflow tf.compat.v1.profiler.profile tf.compat.v1.profiler.profile
=============================
Profile model.
```
tf.compat.v1.profiler.profile(
graph=None,
run_meta=None,
op_log=None,
cmd='scope',
options=_DEFAULT_PROFILE_OPTIONS
)
```
Tutorials and examples can be found in: <https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/profiler/g3doc/python_api.md>
| Args |
| `graph` | tf.Graph. If None and eager execution is not enabled, use default graph. |
| `run_meta` | optional tensorflow.RunMetadata proto. It is necessary to to support run time information profiling, such as time and memory. |
| `op_log` | tensorflow.tfprof.OpLogProto proto. User can assign "types" to graph nodes with op\_log. "types" allow user to flexibly group and account profiles using options['accounted\_type\_regexes']. |
| `cmd` | string. Either 'op', 'scope', 'graph' or 'code'. 'op' view organizes profile using operation type. (e.g. MatMul) 'scope' view organizes profile using graph node name scope. 'graph' view organizes profile using graph node inputs/outputs. 'code' view organizes profile using Python call stack. |
| `options` | A dict of options. See core/profiler/g3doc/options.md. |
| Returns |
| If cmd is 'scope' or 'graph', returns GraphNodeProto proto. If cmd is 'op' or 'code', returns MultiGraphNodeProto proto. Side effect: stdout/file/timeline.json depending on options['output'] |
tensorflow tf.compat.v1.profiler.write_op_log tf.compat.v1.profiler.write\_op\_log
====================================
Log provided 'op\_log', and add additional model information below.
```
tf.compat.v1.profiler.write_op_log(
graph, log_dir, op_log=None, run_meta=None, add_trace=True
)
```
The API also assigns ops in tf.compat.v1.trainable\_variables() an op type called '\_trainable\_variables'. The API also logs 'flops' statistics for ops with op.RegisterStatistics() defined. flops calculation depends on Tensor shapes defined in 'graph', which might not be complete. 'run\_meta', if provided, completes the shape information with best effort.
| Args |
| `graph` | tf.Graph. If None and eager execution is not enabled, use default graph. |
| `log_dir` | directory to write the log file. |
| `op_log` | (Optional) OpLogProto proto to be written. If not provided, an new one is created. |
| `run_meta` | (Optional) RunMetadata proto that helps flops computation using run time shape information. |
| `add_trace` | Whether to add python code trace information. Used to support "code" view. |
tensorflow tf.compat.v1.profiler.ProfileOptionBuilder tf.compat.v1.profiler.ProfileOptionBuilder
==========================================
Option Builder for Profiling API.
```
tf.compat.v1.profiler.ProfileOptionBuilder(
options=None
)
```
For tutorial on the options, see <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md>
```
# Users can use pre-built options:
opts = (
tf.profiler.ProfileOptionBuilder.trainable_variables_parameter())
# Or, build your own options:
opts = (tf.compat.v1.profiler.ProfileOptionBuilder()
.with_max_depth(10)
.with_min_micros(1000)
.select(['accelerator_micros'])
.with_stdout_output()
.build()
# Or customize the pre-built options:
opts = (tf.compat.v1.profiler.ProfileOptionBuilder(
tf.profiler.ProfileOptionBuilder.time_and_memory())
.with_displaying_options(show_name_regexes=['.*rnn.*'])
.build())
# Finally, profiling with the options:
_ = tf.compat.v1.profiler.profile(tf.compat.v1.get_default_graph(),
run_meta=run_meta,
cmd='scope',
options=opts)
```
| Args |
| `options` | Optional initial option dict to start with. |
Methods
-------
### `account_displayed_op_only`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L368-L381)
```
account_displayed_op_only(
is_true
)
```
Whether only account the statistics of displayed profiler nodes.
| Args |
| `is_true` | If true, only account statistics of nodes eventually displayed by the outputs. Otherwise, a node's statistics are accounted by its parents as long as it's types match 'account\_type\_regexes', even if it is hidden from the output, say, by hide\_name\_regexes. |
| Returns |
| self |
### `build`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L189-L195)
```
build()
```
Build a profiling option.
| Returns |
| A dict of profiling options. |
### `float_operation`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L110-L137)
```
@staticmethod
float_operation()
```
Options used to profile float operations.
Please see <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/profile_model_architecture.md> on the caveats of calculating float operations.
| Returns |
| A dict of profiling options. |
### `order_by`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L417-L431)
```
order_by(
attribute
)
```
Order the displayed profiler nodes based on a attribute.
Supported attribute includes micros, bytes, occurrence, params, etc. <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md>
| Args |
| `attribute` | An attribute the profiler node has. |
| Returns |
| self |
### `select`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L433-L447)
```
select(
attributes
)
```
Select the attributes to display.
See <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/options.md> for supported attributes.
| Args |
| `attributes` | A list of attribute the profiler node has. |
| Returns |
| self |
### `time_and_memory`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L139-L187)
```
@staticmethod
time_and_memory(
min_micros=1,
min_bytes=1,
min_accelerator_micros=0,
min_cpu_micros=0,
min_peak_bytes=0,
min_residual_bytes=0,
min_output_bytes=0
)
```
Show operation time and memory consumptions.
| Args |
| `min_micros` | Only show profiler nodes with execution time no less than this. It sums accelerator and cpu times. |
| `min_bytes` | Only show profiler nodes requested to allocate no less bytes than this. |
| `min_accelerator_micros` | Only show profiler nodes spend no less than this time on accelerator (e.g. GPU). |
| `min_cpu_micros` | Only show profiler nodes spend no less than this time on cpu. |
| `min_peak_bytes` | Only show profiler nodes using no less than this bytes at peak (high watermark). For profiler nodes consist of multiple graph nodes, it sums the graph nodes' peak\_bytes. |
| `min_residual_bytes` | Only show profiler nodes have no less than this bytes not being de-allocated after Compute() ends. For profiler nodes consist of multiple graph nodes, it sums the graph nodes' residual\_bytes. |
| `min_output_bytes` | Only show profiler nodes have no less than this bytes output. The output are not necessarily allocated by this profiler nodes. |
| Returns |
| A dict of profiling options. |
### `trainable_variables_parameter`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L84-L108)
```
@staticmethod
trainable_variables_parameter()
```
Options used to profile trainable variable parameters.
Normally used together with 'scope' view.
| Returns |
| A dict of profiling options. |
### `with_accounted_types`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L312-L332)
```
with_accounted_types(
account_type_regexes
)
```
Selectively counting statistics based on node types.
Here, 'types' means the profiler nodes' properties. Profiler by default consider device name (e.g. /job:xx/.../device:GPU:0) and operation type (e.g. MatMul) as profiler nodes' properties. User can also associate customized 'types' to profiler nodes through OpLogProto proto.
For example, user can select profiler nodes placed on gpu:0 with: `account_type_regexes=['.*gpu:0.*']`
If none of a node's properties match the specified regexes, the node is not displayed nor accounted.
| Args |
| `account_type_regexes` | A list of regexes specifying the types. |
| Returns |
| self. |
### `with_empty_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L383-L386)
```
with_empty_output()
```
Do not generate side-effect outputs.
### `with_file_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L393-L396)
```
with_file_output(
outfile
)
```
Print the result to a file.
### `with_max_depth`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L197-L210)
```
with_max_depth(
max_depth
)
```
Set the maximum depth of display.
The depth depends on profiling view. For 'scope' view, it's the depth of name scope hierarchy (tree), for 'op' view, it's the number of operation types (list), etc.
| Args |
| `max_depth` | Maximum depth of the data structure to display. |
| Returns |
| self |
### `with_min_execution_time`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L241-L260)
```
with_min_execution_time(
min_micros=0, min_accelerator_micros=0, min_cpu_micros=0
)
```
Only show profiler nodes consuming no less than 'min\_micros'.
| Args |
| `min_micros` | Only show profiler nodes with execution time no less than this. It sums accelerator and cpu times. |
| `min_accelerator_micros` | Only show profiler nodes spend no less than this time on accelerator (e.g. GPU). |
| `min_cpu_micros` | Only show profiler nodes spend no less than this time on cpu. |
| Returns |
| self |
### `with_min_float_operations`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L295-L310)
```
with_min_float_operations(
min_float_ops
)
```
Only show profiler nodes consuming no less than 'min\_float\_ops'.
Please see <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/g3doc/profile_model_architecture.md> on the caveats of calculating float operations.
| Args |
| `min_float_ops` | Only show profiler nodes with float operations no less than this. |
| Returns |
| self |
### `with_min_memory`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L212-L239)
```
with_min_memory(
min_bytes=0, min_peak_bytes=0, min_residual_bytes=0, min_output_bytes=0
)
```
Only show profiler nodes consuming no less than 'min\_bytes'.
| Args |
| `min_bytes` | Only show profiler nodes requested to allocate no less bytes than this. |
| `min_peak_bytes` | Only show profiler nodes using no less than this bytes at peak (high watermark). For profiler nodes consist of multiple graph nodes, it sums the graph nodes' peak\_bytes. |
| `min_residual_bytes` | Only show profiler nodes have no less than this bytes not being de-allocated after Compute() ends. For profiler nodes consist of multiple graph nodes, it sums the graph nodes' residual\_bytes. |
| `min_output_bytes` | Only show profiler nodes have no less than this bytes output. The output are not necessarily allocated by this profiler nodes. |
| Returns |
| self |
### `with_min_occurrence`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L277-L293)
```
with_min_occurrence(
min_occurrence
)
```
Only show profiler nodes including no less than 'min\_occurrence' graph nodes.
A "node" means a profiler output node, which can be a python line (code view), an operation type (op view), or a graph node (graph/scope view). A python line includes all graph nodes created by that line, while an operation type includes all graph nodes of that type.
| Args |
| `min_occurrence` | Only show nodes including no less than this. |
| Returns |
| self |
### `with_min_parameters`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L262-L275)
```
with_min_parameters(
min_params
)
```
Only show profiler nodes holding no less than 'min\_params' parameters.
'Parameters' normally refers the weights of in TensorFlow variables. It reflects the 'capacity' of models.
| Args |
| `min_params` | Only show profiler nodes holding number parameters no less than this. |
| Returns |
| self |
### `with_node_names`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L334-L366)
```
with_node_names(
start_name_regexes=None,
show_name_regexes=None,
hide_name_regexes=None,
trim_name_regexes=None
)
```
Regular expressions used to select profiler nodes to display.
After 'with\_accounted\_types' is evaluated, 'with\_node\_names' are evaluated as follows:
For a profile data structure, profiler first finds the profiler nodes matching 'start\_name\_regexes', and starts displaying profiler nodes from there. Then, if a node matches 'show\_name\_regexes' and doesn't match 'hide\_name\_regexes', it's displayed. If a node matches 'trim\_name\_regexes', profiler stops further searching that branch.
| Args |
| `start_name_regexes` | list of node name regexes to start displaying. |
| `show_name_regexes` | list of node names regexes to display. |
| `hide_name_regexes` | list of node\_names regexes that should be hidden. |
| `trim_name_regexes` | list of node name regexes from where to stop. |
| Returns |
| self |
### `with_pprof_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L403-L415)
```
with_pprof_output(
pprof_file
)
```
Generate a pprof profile gzip file.
#### To use the pprof file:
pprof -png --nodecount=100 --sample\_index=1
| Args |
| `pprof_file` | filename for output, usually suffixed with .pb.gz. |
| Returns |
| self. |
### `with_stdout_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L388-L391)
```
with_stdout_output()
```
Print the result to stdout.
### `with_step`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L449-L461)
```
with_step(
step
)
```
Which profile step to use for profiling.
The 'step' here refers to the step defined by `Profiler.add_step()` API.
| Args |
| `step` | When multiple steps of profiles are available, select which step's profile to use. If -1, use average of all available steps. |
| Returns |
| self |
### `with_timeline_output`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/option_builder.py#L398-L401)
```
with_timeline_output(
timeline_file
)
```
Generate a timeline json file.
| programming_docs |
tensorflow tf.compat.v1.profiler.OpLogProto tf.compat.v1.profiler.OpLogProto
================================
A ProtocolMessage
| Attributes |
| `id_to_string` | `repeated IdToStringEntry id_to_string` |
| `log_entries` | `repeated OpLogEntry log_entries` |
Child Classes
-------------
[`class IdToStringEntry`](oplogproto/idtostringentry)
tensorflow tf.compat.v1.profiler.GraphNodeProto tf.compat.v1.profiler.GraphNodeProto
====================================
A ProtocolMessage
| Attributes |
| `accelerator_exec_micros` | `int64 accelerator_exec_micros` |
| `children` | `repeated GraphNodeProto children` |
| `cpu_exec_micros` | `int64 cpu_exec_micros` |
| `devices` | `repeated string devices` |
| `exec_micros` | `int64 exec_micros` |
| `float_ops` | `int64 float_ops` |
| `input_shapes` | `repeated InputShapesEntry input_shapes` |
| `name` | `string name` |
| `output_bytes` | `int64 output_bytes` |
| `parameters` | `int64 parameters` |
| `peak_bytes` | `int64 peak_bytes` |
| `requested_bytes` | `int64 requested_bytes` |
| `residual_bytes` | `int64 residual_bytes` |
| `run_count` | `int64 run_count` |
| `shapes` | `repeated TensorShapeProto shapes` |
| `tensor_value` | `TFProfTensorProto tensor_value` |
| `total_accelerator_exec_micros` | `int64 total_accelerator_exec_micros` |
| `total_cpu_exec_micros` | `int64 total_cpu_exec_micros` |
| `total_definition_count` | `int64 total_definition_count` |
| `total_exec_micros` | `int64 total_exec_micros` |
| `total_float_ops` | `int64 total_float_ops` |
| `total_output_bytes` | `int64 total_output_bytes` |
| `total_parameters` | `int64 total_parameters` |
| `total_peak_bytes` | `int64 total_peak_bytes` |
| `total_requested_bytes` | `int64 total_requested_bytes` |
| `total_residual_bytes` | `int64 total_residual_bytes` |
| `total_run_count` | `int64 total_run_count` |
Child Classes
-------------
[`class InputShapesEntry`](graphnodeproto/inputshapesentry)
tensorflow tf.compat.v1.profiler.MultiGraphNodeProto tf.compat.v1.profiler.MultiGraphNodeProto
=========================================
A ProtocolMessage
| Attributes |
| `accelerator_exec_micros` | `int64 accelerator_exec_micros` |
| `children` | `repeated MultiGraphNodeProto children` |
| `cpu_exec_micros` | `int64 cpu_exec_micros` |
| `exec_micros` | `int64 exec_micros` |
| `float_ops` | `int64 float_ops` |
| `graph_nodes` | `repeated GraphNodeProto graph_nodes` |
| `name` | `string name` |
| `output_bytes` | `int64 output_bytes` |
| `parameters` | `int64 parameters` |
| `peak_bytes` | `int64 peak_bytes` |
| `requested_bytes` | `int64 requested_bytes` |
| `residual_bytes` | `int64 residual_bytes` |
| `total_accelerator_exec_micros` | `int64 total_accelerator_exec_micros` |
| `total_cpu_exec_micros` | `int64 total_cpu_exec_micros` |
| `total_exec_micros` | `int64 total_exec_micros` |
| `total_float_ops` | `int64 total_float_ops` |
| `total_output_bytes` | `int64 total_output_bytes` |
| `total_parameters` | `int64 total_parameters` |
| `total_peak_bytes` | `int64 total_peak_bytes` |
| `total_requested_bytes` | `int64 total_requested_bytes` |
| `total_residual_bytes` | `int64 total_residual_bytes` |
tensorflow tf.compat.v1.profiler.Profiler tf.compat.v1.profiler.Profiler
==============================
TensorFlow multi-step profiler.
```
tf.compat.v1.profiler.Profiler(
graph=None, op_log=None
)
```
```
Typical use case:
# Currently we are only allowed to create 1 profiler per process.
profiler = Profiler(sess.graph)
for i in range(total_steps):
if i % 10000 == 0:
run_meta = tf.compat.v1.RunMetadata()
_ = sess.run(...,
options=tf.compat.v1.RunOptions(
trace_level=tf.RunOptions.FULL_TRACE),
run_metadata=run_meta)
profiler.add_step(i, run_meta)
# Profile the parameters of your model.
profiler.profile_name_scope(options=(option_builder.ProfileOptionBuilder
.trainable_variables_parameter()))
# Or profile the timing of your model operations.
opts = option_builder.ProfileOptionBuilder.time_and_memory()
profiler.profile_operations(options=opts)
# Or you can generate a timeline:
opts = (option_builder.ProfileOptionBuilder(
option_builder.ProfileOptionBuilder.time_and_memory())
.with_step(i)
.with_timeline_output(filename).build())
profiler.profile_graph(options=opts)
else:
_ = sess.run(...)
# Auto detect problems and generate advice.
profiler.advise()
```
| Args |
| `graph` | tf.Graph. If None and eager execution is not enabled, use default graph. |
| `op_log` | optional. tensorflow::tfprof::OpLogProto proto. Used to define extra op types. |
Methods
-------
### `add_step`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L185-L201)
```
add_step(
step, run_meta
)
```
Add statistics of a step.
| Args |
| `step` | int, An id used to group one or more different `run_meta` together. When profiling with the profile\_xxx APIs, user can use the `step` id in the `options` to profile these `run_meta` together. |
| `run_meta` | RunMetadata proto that contains statistics of a session run. |
### `advise`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L281-L294)
```
advise(
options
)
```
Automatically detect problems and generate reports.
| Args |
| `options` | A dict of options. See ALL\_ADVICE example above. |
| Returns |
| An Advise proto that contains the reports from all checkers. |
### `profile_graph`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L263-L279)
```
profile_graph(
options
)
```
Profile the statistics of graph nodes, organized by dataflow graph.
| Args |
| `options` | A dict of options. See core/profiler/g3doc/options.md. |
| Returns |
| a GraphNodeProto that records the results. |
### `profile_name_scope`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L245-L261)
```
profile_name_scope(
options
)
```
Profile the statistics of graph nodes, organized by name scope.
| Args |
| `options` | A dict of options. See core/profiler/g3doc/options.md. |
| Returns |
| a GraphNodeProto that records the results. |
### `profile_operations`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L225-L243)
```
profile_operations(
options
)
```
Profile the statistics of the Operation types (e.g.
MatMul, Conv2D).
| Args |
| `options` | A dict of options. See core/profiler/g3doc/options.md. |
| Returns |
| a MultiGraphNodeProto that records the results. |
### `profile_python`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L203-L223)
```
profile_python(
options
)
```
Profile the statistics of the Python codes.
By default, it shows the call stack from root. To avoid redundant output, you may use options to filter as below options['show\_name\_regexes'] = ['.*my\_code.py.*']
| Args |
| `options` | A dict of options. See core/profiler/g3doc/options.md. |
| Returns |
| a MultiGraphNodeProto that records the results. |
### `serialize_to_string`
[View source](https://github.com/tensorflow/tensorflow/blob/v2.9.0/tensorflow/python/profiler/model_analyzer.py#L296-L305)
```
serialize_to_string()
```
Serialize the ProfileProto to a binary string.
Users can write it to file for offline analysis by tfprof commandline or graphical interface.
| Returns |
| ProfileProto binary string. |
tensorflow tf.compat.v1.profiler.AdviceProto tf.compat.v1.profiler.AdviceProto
=================================
A ProtocolMessage
| Attributes |
| `checkers` | `repeated CheckersEntry checkers` |
Child Classes
-------------
[`class Checker`](adviceproto/checker)
[`class CheckersEntry`](adviceproto/checkersentry)
tensorflow tf.compat.v1.profiler.advise tf.compat.v1.profiler.advise
============================
Auto profile and advise.
```
tf.compat.v1.profiler.advise(
graph=None, run_meta=None, options=_DEFAULT_ADVISE_OPTIONS
)
```
Builds profiles and automatically check anomalies of various aspects. For more details: <https://github.com/tensorflow/tensorflow/tree/master/tensorflow/core/profiler/README.md>
| Args |
| `graph` | tf.Graph. If None and eager execution is not enabled, use default graph. |
| `run_meta` | optional tensorflow.RunMetadata proto. It is necessary to to support run time information profiling, such as time and memory. |
| `options` | see ALL\_ADVICE example above. Default checks everything. |
| Returns |
| Returns AdviceProto proto |
tensorflow tf.compat.v1.profiler.AdviceProto.Checker tf.compat.v1.profiler.AdviceProto.Checker
=========================================
A ProtocolMessage
| Attributes |
| `reports` | `repeated string reports` |
tensorflow tf.compat.v1.profiler.AdviceProto.CheckersEntry tf.compat.v1.profiler.AdviceProto.CheckersEntry
===============================================
A ProtocolMessage
| Attributes |
| `key` | `string key` |
| `value` | `Checker value` |
tensorflow tf.compat.v1.profiler.GraphNodeProto.InputShapesEntry tf.compat.v1.profiler.GraphNodeProto.InputShapesEntry
=====================================================
A ProtocolMessage
| Attributes |
| `key` | `int32 key` |
| `value` | `TensorShapeProto value` |
tensorflow tf.compat.v1.profiler.OpLogProto.IdToStringEntry tf.compat.v1.profiler.OpLogProto.IdToStringEntry
================================================
A ProtocolMessage
| Attributes |
| `key` | `int64 key` |
| `value` | `string value` |
tensorflow tf.compat.v1.RunMetadata.FunctionGraphs tf.compat.v1.RunMetadata.FunctionGraphs
=======================================
A ProtocolMessage
| Attributes |
| `partition_graphs` | `repeated GraphDef partition_graphs` |
| `post_optimization_graph` | `GraphDef post_optimization_graph` |
| `pre_optimization_graph` | `GraphDef pre_optimization_graph` |
tensorflow tf.compat.v1.tpu.bfloat16_scope tf.compat.v1.tpu.bfloat16\_scope
================================
Scope class for bfloat16 variables so that the model uses custom getter.
```
@tf_contextlib.contextmanager
tf.compat.v1.tpu.bfloat16_scope(
name: Optional[Text] = None
) -> Generator[tf.compat.v1.variable_scope, None, None]
```
This enables variables to be read as bfloat16 type when using get\_variable.
| Arguments |
| `name` | Name to use for scope. |
| Yields |
| a variable scope. |
tensorflow tf.compat.v1.tpu.initialize_system tf.compat.v1.tpu.initialize\_system
===================================
Initializes a distributed TPU system for use with TensorFlow.
```
tf.compat.v1.tpu.initialize_system(
embedding_config: Optional[embedding_pb2.TPUEmbeddingConfiguration] = None,
job: Optional[Text] = None,
compilation_failure_closes_chips: bool = True,
tpu_cancellation_closes_chips: Optional[bool] = None
) -> core_types.Tensor
```
| Args |
| `embedding_config` | If not None, a `TPUEmbeddingConfiguration` proto describing the desired configuration of the hardware embedding lookup tables. If embedding\_config is None, no hardware embeddings can be used. |
| `job` | The job (the XXX in TensorFlow device specification /job:XXX) that contains the TPU devices that will be initialized. If job=None it is assumed there is only one job in the TensorFlow flock, and an error will be returned if this assumption does not hold. |
| `compilation_failure_closes_chips` | Set the configuration whether we want to close TPU chips when there is a compilation failure. |
| `tpu_cancellation_closes_chips` | Set the configuration whether we want to close TPU chips when a TPU execution is cancelled. If the value is None, the behavior will be determined by the command line flag `tpu_cancellation_closes_chips` for the TPU worker. WARNING: this argument only applies to TFRT TPU runtime. |
| Returns |
| A serialized `TopologyProto` that describes the TPU system. Note: the topology must be evaluated using `Session.run` before it can be used. |
tensorflow tf.compat.v1.tpu.cross_replica_sum tf.compat.v1.tpu.cross\_replica\_sum
====================================
Sum the input tensor across replicas according to group\_assignment.
```
tf.compat.v1.tpu.cross_replica_sum(
x, group_assignment=None, name=None
)
```
| Args |
| `x` | The local tensor to the sum. |
| `group_assignment` | Optional 2d int32 lists with shape [num\_groups, num\_replicas\_per\_group]. `group_assignment[i]` represents the replica ids in the ith subgroup. |
| `name` | Optional op name. |
| Returns |
| A `Tensor` which is summed across replicas. |
tensorflow tf.compat.v1.tpu.core tf.compat.v1.tpu.core
=====================
Returns the device name for a core in a replicated TPU computation.
```
tf.compat.v1.tpu.core(
num: int
) -> Text
```
| Args |
| `num` | the virtual core number within each replica to which operators should be assigned. |
| Returns |
| A device name, suitable for passing to [`tf.device()`](../../../device). |
tensorflow Module: tf.compat.v1.tpu.experimental Module: tf.compat.v1.tpu.experimental
=====================================
Public API for tf.tpu.experimental namespace.
Modules
-------
[`embedding`](experimental/embedding) module: Public API for tf.tpu.experimental.embedding namespace.
Classes
-------
[`class AdagradParameters`](experimental/adagradparameters): Optimization parameters for Adagrad with TPU embeddings.
[`class AdamParameters`](experimental/adamparameters): Optimization parameters for Adam with TPU embeddings.
[`class DeviceAssignment`](../../../tpu/experimental/deviceassignment): Mapping from logical cores in a computation to the physical TPU topology.
[`class FtrlParameters`](experimental/ftrlparameters): Optimization parameters for Ftrl with TPU embeddings.
[`class HardwareFeature`](../../../tpu/experimental/hardwarefeature): class holds all the feature info about the TPU.
[`class StochasticGradientDescentParameters`](experimental/stochasticgradientdescentparameters): Optimization parameters for stochastic gradient descent for TPU embeddings.
[`class TPUSystemMetadata`](../../../tpu/experimental/tpusystemmetadata): Describes some metadata about the TPU system.
[`class Topology`](../../../tpu/experimental/topology): Describes a set of TPU devices.
Functions
---------
[`embedding_column(...)`](experimental/embedding_column): TPU version of [`tf.compat.v1.feature_column.embedding_column`](../../../feature_column/embedding_column).
[`initialize_tpu_system(...)`](../../../tpu/experimental/initialize_tpu_system): Initialize the TPU devices.
[`shared_embedding_columns(...)`](experimental/shared_embedding_columns): TPU version of [`tf.compat.v1.feature_column.shared_embedding_columns`](../feature_column/shared_embedding_columns).
[`shutdown_tpu_system(...)`](../../../tpu/experimental/shutdown_tpu_system): Shuts down the TPU devices.
tensorflow tf.compat.v1.tpu.PaddingSpec tf.compat.v1.tpu.PaddingSpec
============================
Represents the type of padding policies for tpu.replicate.
| Class Variables |
| AUTO | `<PaddingSpec.AUTO: 0>` |
| POWER\_OF\_TWO | `<PaddingSpec.POWER_OF_TWO: 1>` |
tensorflow tf.compat.v1.tpu.outside_compilation tf.compat.v1.tpu.outside\_compilation
=====================================
Builds part of a computation outside any current TPU replicate scope.
```
tf.compat.v1.tpu.outside_compilation(
computation: Callable[..., Any], *args, **kwargs
) -> Any
```
`tf.tpu.outside_compilation()` is used to run ops in `computation` on CPU instead of running on TPU. For example, users can run ops that are not supported on TPU's (e.g. tf.summary.write()) by explicitly placing those ops on CPU's. Below usage of outside compilation will place ops in `computation_with_string_ops` on CPU.
#### Example usage:
```
def computation_with_string_ops(x):
# strings types are not supported on TPU's and below ops must
# run on CPU instead.
output = tf.strings.format('1{}', x)
return tf.strings.to_number(output)
def tpu_computation():
# Expected output is 11.
output = tf.tpu.outside_compilation(computation_with_string_ops, 1)
```
Outside compilation should be called inside TPUReplicateContext. That is, `tf.tpu.outside_compilation()` should be called inside a function that is passed to `tpu.split_compile_and_replicate()` -- this is implied when outside compilation is invoked inside a function passed to TPUStrategy `run()`. If invoked outside of TPUReplicateContext, then this simply returns the result of `computation`, and therefore, would be a no-op. Note that outside compilation is different from `tf.distribute.experimental.TPUStrategy.merge_call()` as logic in outside compilation is replicated and executed separately for each replica. On the other hand, `merge_call()` requires a `merge_fn` to aggregate the inputs from different replicas and is executed only once.
For variables placed in TPU device, which includes variables created inside TPUStrategy scope, outside compilation logic must not include variable read/write. For variables placed on host, which is the case when variables created via TPUEstimator, variable read/write is only allowed if the variable is not accessed by any other ops in the TPU computation. Variable read/write from outside compilation cluster is not visible from TPU computation and vice versa. Therefore, if outside compilation logic contains such host variables read/write ops and if the variables are accessed by TPU computation as well, then this may lead to deadlock.
Internally, `tf.tpu.outside_compilation()` adds outside compilation attributes to all ops in `computation`. During later graph pass, these ops with outside compilation attribute is extracted out and replicated into a host-side graph. Inputs to this extract host-side graph is sent from TPU computation graph to host graph via a pair of XlaSendToHost and XlaRecvFromHost ops. Note that using `tf.tpu.outside_compilation()` may result in tensor transfer between TPU and CPU, leading to non-trivial performance impact.
| Args |
| `computation` | A Python function that builds the computation to place on the host. |
| `*args` | the positional arguments for the computation. |
| `**kwargs` | the keyword arguments for the computation. |
| Returns |
| The Tensors returned by computation. |
tensorflow tf.compat.v1.tpu.shard tf.compat.v1.tpu.shard
======================
Shards `computation` for parallel execution.
```
tf.compat.v1.tpu.shard(
computation: Callable[..., Any],
inputs: Optional[List[core_types.Tensor]] = None,
num_shards: int = 1,
input_shard_axes: Optional[List[int]] = None,
outputs_from_all_shards: Union[bool, List[bool]] = True,
output_shard_axes: Optional[List[int]] = None,
infeed_queue: Optional[tpu_feed.InfeedQueue] = None,
device_assignment: Optional[tf.tpu.experimental.DeviceAssignment] = None,
name: Optional[Text] = None,
xla_options: Optional[tf.tpu.XLAOptions] = None
) -> List[core_types.Tensor]
```
`inputs` must be a list of Tensors or None (equivalent to an empty list), each of which has a corresponding split axis (from `input_shard_axes`). Each input is split into `num_shards` pieces along the corresponding axis, and computation is applied to each shard in parallel.
Tensors are broadcast to all shards if they are lexically captured by `computation`. e.g.,
x = tf.constant(7) def computation(): return x + 3 ... = shard(computation, ...)
as inputs.
If `outputs_from_all_shards` is true, the outputs from all shards of `computation` are concatenated back together along their `output_shard_axes`. Otherwise, each output is taken from an arbitrary shard.
Inputs and outputs of the computation must be at least rank-1 Tensors.
| Args |
| `computation` | A Python function that builds a computation to apply to each shard of the input. |
| `inputs` | A list of input tensors or None (equivalent to an empty list). Each input tensor has a corresponding shard axes, given by `input_shard_axes`, which must have size divisible by `num_shards`. |
| `num_shards` | The number of shards. |
| `input_shard_axes` | A list of dimensions along which to shard `inputs`, or `None`. `None` means "shard all inputs along dimension 0". If not `None`, there must be one dimension per input. |
| `outputs_from_all_shards` | Boolean or list of boolean. For each output, if `True`, outputs from all shards are concatenated along the corresponding `output_shard_axes` entry. Otherwise, each output is taken from an arbitrary shard. If the argument is a boolean, the argument's value is used for each output. |
| `output_shard_axes` | A list of dimensions along which to concatenate the outputs of `computation`, or `None`. `None` means "concatenate all outputs along dimension 0". If not `None`, there must be one dimension per output. Ignored if `outputs_from_all_shards` is False. |
| `infeed_queue` | If not `None`, the `InfeedQueue` to use to augment the inputs of `computation`. |
| `device_assignment` | If not `None`, a `DeviceAssignment` describing the mapping between logical cores in the computation with physical cores in the TPU topology. Uses a default device assignment if `None`. The `DeviceAssignment` may be omitted if each shard of the computation uses only one core, and there is either only one shard, or the number of shards is equal to the number of cores in the TPU system. |
| `name` | (Deprecated) Does nothing. |
| `xla_options` | An instance of [`tpu.XLAOptions`](https://www.tensorflow.org/api_docs/python/tf/tpu/XLAOptions) which indicates the options passed to XLA compiler. Use `None` for default options. |
| Returns |
| A list of output tensors. |
| Raises |
| `ValueError` | If num\_shards <= 0 |
| `ValueError` | If len(input\_shard\_axes) != len(inputs) |
| `ValueError` | If len(output\_shard\_axes) != len(outputs from `computation`) |
| programming_docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.