tf.TensorShape     View source on GitHub    Represents the shape of a Tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.TensorShape
tf.TensorShape(
    dims
)
 A TensorShape represents a possibly-partial shape specification for a Tensor. It may be one of the following:
Fully-known shape: has a known number of dimensions and a known size for each dimension. e.g. TensorShape([16, 256])

Partially-known shape: has a known number of dimensions, and an unknown size for one or more dimension. e.g. TensorShape([None, 256])

Unknown shape: has an unknown number of dimensions, and an unknown size in all dimensions. e.g. TensorShape(None)
  If a tensor is produced by an operation of type "Foo", its shape may be inferred if there is a registered shape function for "Foo". See Shape functions for details of shape functions and how to register them. Alternatively, the shape may be set explicitly using tf.Tensor.set_shape.

 Args
  dims   A list of Dimensions, or None if the shape is unspecified.

 Raises
  TypeError   If dims cannot be converted to a list of dimensions.

 Attributes
  dims   Deprecated. Returns list of dimensions for this shape. Suggest TensorShape.as_list instead.

  ndims   Deprecated accessor for rank.
  rank   Returns the rank of this shape, or None if it is unspecified.    Methods as_list View source
as_list()
 Returns a list of integers or None for each dimension.

 Returns   A list of integers or None for each dimension.

 Raises
  ValueError   If self is an unknown shape with an unknown rank.    as_proto View source
as_proto()
 Returns this shape as a TensorShapeProto. assert_has_rank View source
assert_has_rank(
    rank
)
 Raises an exception if self is not compatible with the given rank.

 Args
  rank   An integer.

 Raises
  ValueError   If self does not represent a shape with the given rank.    assert_is_compatible_with View source
assert_is_compatible_with(
    other
)
 Raises exception if self and other do not represent the same shape. This method can be used to assert that there exists a shape that both self and other represent.

 Args
  other   Another TensorShape.

 Raises
  ValueError   If self and other do not represent the same shape.    assert_is_fully_defined View source
assert_is_fully_defined()
 Raises an exception if self is not fully defined in every dimension.

 Raises
  ValueError   If self does not have a known value for every dimension.    assert_same_rank View source
assert_same_rank(
    other
)
 Raises an exception if self and other do not have compatible ranks.

 Args
  other   Another TensorShape.

 Raises
  ValueError   If self and other do not represent shapes with the same rank.    concatenate View source
concatenate(
    other
)
 Returns the concatenation of the dimension in self and other.
Note: If either self or other is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing.

 Args
  other   Another TensorShape.

 Returns   A TensorShape whose dimensions are the concatenation of the dimensions in self and other.
 is_compatible_with View source
is_compatible_with(
    other
)
 Returns True iff self is compatible with other. Two possibly-partially-defined shapes are compatible if there exists a fully-defined shape that both shapes can represent. Thus, compatibility allows the shape inference code to reason about partially-defined shapes. For example:  TensorShape(None) is compatible with all shapes. TensorShape([None, None]) is compatible with all two-dimensional shapes, such as TensorShape([32, 784]), and also TensorShape(None). It is not compatible with, for example, TensorShape([None]) or TensorShape([None, None, None]). TensorShape([32, None]) is compatible with all two-dimensional shapes with size 32 in the 0th dimension, and also TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32]), TensorShape([32, None, 1]) or TensorShape([64, None]). TensorShape([32, 784]) is compatible with itself, and also TensorShape([32, None]), TensorShape([None, 784]), TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32, 1, 784]) or TensorShape([None]).  The compatibility relation is reflexive and symmetric, but not transitive. For example, TensorShape([32, 784]) is compatible with TensorShape(None), and TensorShape(None) is compatible with TensorShape([4, 4]), but TensorShape([32, 784]) is not compatible with TensorShape([4, 4]).

 Args
  other   Another TensorShape.

 Returns   True iff self is compatible with other.
 is_fully_defined View source
is_fully_defined()
 Returns True iff self is fully defined in every dimension. merge_with View source
merge_with(
    other
)
 Returns a TensorShape combining the information in self and other. The dimensions in self and other are merged elementwise, according to the rules defined for Dimension.merge_with().

 Args
  other   Another TensorShape.

 Returns   A TensorShape containing the combined information of self and other.

 Raises
  ValueError   If self and other are not compatible.    most_specific_compatible_shape View source
most_specific_compatible_shape(
    other
)
 Returns the most specific TensorShape compatible with self and other.  TensorShape([None, 1]) is the most specific TensorShape compatible with both TensorShape([2, 1]) and TensorShape([5, 1]). Note that TensorShape(None) is also compatible with above mentioned TensorShapes. TensorShape([1, 2, 3]) is the most specific TensorShape compatible with both TensorShape([1, 2, 3]) and TensorShape([1, 2, 3]). There are more less specific TensorShapes compatible with above mentioned TensorShapes, e.g. TensorShape([1, 2, None]), TensorShape(None).

 Args
  other   Another TensorShape.

 Returns   A TensorShape which is the most specific compatible shape of self and other.
 num_elements View source
num_elements()
 Returns the total number of elements, or none for incomplete shapes. with_rank View source
with_rank(
    rank
)
 Returns a shape based on self with the given rank. This method promotes a completely unknown shape to one with a known rank.

 Args
  rank   An integer.

 Returns   A shape that is at least as specific as self with the given rank.

 Raises
  ValueError   If self does not represent a shape with the given rank.    with_rank_at_least View source
with_rank_at_least(
    rank
)
 Returns a shape based on self with at least the given rank.

 Args
  rank   An integer.

 Returns   A shape that is at least as specific as self with at least the given rank.

 Raises
  ValueError   If self does not represent a shape with at least the given rank.    with_rank_at_most View source
with_rank_at_most(
    rank
)
 Returns a shape based on self with at most the given rank.

 Args
  rank   An integer.

 Returns   A shape that is at least as specific as self with at most the given rank.

 Raises
  ValueError   If self does not represent a shape with at most the given rank.    __add__ View source
__add__(
    other
)
 __bool__ View source
__bool__()
 Returns True if this shape contains non-zero information. __concat__ View source
__concat__(
    other
)
 __eq__ View source
__eq__(
    other
)
 Returns True if self is equivalent to other. __getitem__ View source
__getitem__(
    key
)
 Returns the value of a dimension or a shape, depending on the key.

 Args
  key   If key is an integer, returns the dimension at that index; otherwise if key is a slice, returns a TensorShape whose dimensions are those selected by the slice from self.

 Returns   An integer if key is an integer, or a TensorShape if key is a slice.

 Raises
  ValueError   If key is a slice and self is completely unknown and the step is set.    __iter__ View source
__iter__()
 Returns self.dims if the rank is known, otherwise raises ValueError. __len__ View source
__len__()
 Returns the rank of this shape, or raises ValueError if unspecified. __ne__ View source
__ne__(
    other
)
 Returns True if self is known to be different from other. __nonzero__ View source
__nonzero__()
 Returns True if this shape contains non-zero information. __radd__ View source
__radd__(
    other
)


tf.TensorSpec     View source on GitHub    Describes a tf.Tensor. Inherits From: TypeSpec  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.TensorSpec
tf.TensorSpec(
    shape, dtype=tf.dtypes.float32, name=None
)
 Metadata for describing the tf.Tensor objects accepted or returned by some TensorFlow APIs.

 Args
  shape   Value convertible to tf.TensorShape. The shape of the tensor.
  dtype   Value convertible to tf.DType. The type of the tensor values.
  name   Optional name for the Tensor.

 Raises
  TypeError   If shape is not convertible to a tf.TensorShape, or dtype is not convertible to a tf.DType.

 Attributes
  dtype   Returns the dtype of elements in the tensor.
  name   Returns the (optionally provided) name of the described tensor.
  shape   Returns the TensorShape that represents the shape of the tensor.
  value_type
   Methods from_spec View source
@classmethod
from_spec(
    spec, name=None
)
 from_tensor View source
@classmethod
from_tensor(
    tensor, name=None
)
 is_compatible_with View source
is_compatible_with(
    spec_or_tensor
)
 Returns True if spec_or_tensor is compatible with this TensorSpec. Two tensors are considered compatible if they have the same dtype and their shapes are compatible (see tf.TensorShape.is_compatible_with).

 Args
  spec_or_tensor   A tf.TensorSpec or a tf.Tensor

 Returns   True if spec_or_tensor is compatible with self.
 most_specific_compatible_type View source
most_specific_compatible_type(
    other
)
 Returns the most specific TypeSpec compatible with self and other.

 Args
  other   A TypeSpec.

 Raises
  ValueError   If there is no TypeSpec that is compatible with both self and other.    __eq__ View source
__eq__(
    other
)
 Return self==value. __ne__ View source
__ne__(
    other
)
 Return self!=value.


tf.tensor_scatter_nd_add Adds sparse updates to an existing tensor according to indices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tensor_scatter_add, tf.compat.v1.tensor_scatter_nd_add
tf.tensor_scatter_nd_add(
    tensor, indices, updates, name=None
)
 This operation creates a new tensor by adding sparse updates to the passed in tensor. This operation is very similar to tf.scatter_nd_add, except that the updates are added onto an existing tensor (as opposed to a variable). If the memory for the existing tensor cannot be re-used, a copy is made and updated. indices is an integer tensor containing indices into a new tensor of shape tensor.shape. The last dimension of indices can be at most the rank of tensor.shape: indices.shape[-1] <= tensor.shape.rank
 The last dimension of indices corresponds to indices into elements (if indices.shape[-1] = tensor.shape.rank) or slices (if indices.shape[-1] < tensor.shape.rank) along dimension indices.shape[-1] of tensor.shape. updates is a tensor with shape indices.shape[:-1] + tensor.shape[indices.shape[-1]:]
 The simplest form of tensor_scatter_add is to add individual elements to a tensor by index. For example, say we want to add 4 elements in a rank-1 tensor with 8 elements. In Python, this scatter add operation would look like this: indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
tensor = tf.ones([8], dtype=tf.int32)
updated = tf.tensor_scatter_nd_add(tensor, indices, updates)
print(updated)
 The resulting tensor would look like this: [1, 12, 1, 11, 10, 1, 1, 13]
 We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter add operation would look like this: indices = tf.constant([[0], [2]])
updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]],
                       [[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]]])
tensor = tf.ones([4, 4, 4],dtype=tf.int32)
updated = tf.tensor_scatter_nd_add(tensor, indices, updates)
print(updated)
 The resulting tensor would look like this: [[[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],
 [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
 [[6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]],
 [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
 Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored.

 Args
  tensor   A Tensor. Tensor to copy/update.
  indices   A Tensor. Must be one of the following types: int32, int64. Index tensor.
  updates   A Tensor. Must have the same type as tensor. Updates to scatter into output.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as tensor.


tf.tensor_scatter_nd_max  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tensor_scatter_nd_max
tf.tensor_scatter_nd_max(
    tensor, indices, updates, name=None
)

 Args
  tensor   A Tensor. Tensor to update.
  indices   A Tensor. Must be one of the following types: int32, int64. Index tensor.
  updates   A Tensor. Must have the same type as tensor. Updates to scatter into output.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as tensor.


tf.tensor_scatter_nd_min  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tensor_scatter_nd_min
tf.tensor_scatter_nd_min(
    tensor, indices, updates, name=None
)

 Args
  tensor   A Tensor. Tensor to update.
  indices   A Tensor. Must be one of the following types: int32, int64. Index tensor.
  updates   A Tensor. Must have the same type as tensor. Updates to scatter into output.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as tensor.


tf.tensor_scatter_nd_sub Subtracts sparse updates from an existing tensor according to indices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tensor_scatter_nd_sub, tf.compat.v1.tensor_scatter_sub
tf.tensor_scatter_nd_sub(
    tensor, indices, updates, name=None
)
 This operation creates a new tensor by subtracting sparse updates from the passed in tensor. This operation is very similar to tf.scatter_nd_sub, except that the updates are subtracted from an existing tensor (as opposed to a variable). If the memory for the existing tensor cannot be re-used, a copy is made and updated. indices is an integer tensor containing indices into a new tensor of shape shape. The last dimension of indices can be at most the rank of shape: indices.shape[-1] <= shape.rank
 The last dimension of indices corresponds to indices into elements (if indices.shape[-1] = shape.rank) or slices (if indices.shape[-1] < shape.rank) along dimension indices.shape[-1] of shape. updates is a tensor with shape indices.shape[:-1] + shape[indices.shape[-1]:]
 The simplest form of tensor_scatter_sub is to subtract individual elements from a tensor by index. For example, say we want to insert 4 scattered elements in a rank-1 tensor with 8 elements. In Python, this scatter subtract operation would look like this: indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
tensor = tf.ones([8], dtype=tf.int32)
updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)
print(updated)
 The resulting tensor would look like this: [1, -10, 1, -9, -8, 1, 1, -11]
 We can also, insert entire slices of a higher rank tensor all at once. For example, if we wanted to insert two slices in the first dimension of a rank-3 tensor with two matrices of new values. In Python, this scatter add operation would look like this: indices = tf.constant([[0], [2]])
updates = tf.constant([[[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]],
                       [[5, 5, 5, 5], [6, 6, 6, 6],
                        [7, 7, 7, 7], [8, 8, 8, 8]]])
tensor = tf.ones([4, 4, 4],dtype=tf.int32)
updated = tf.tensor_scatter_nd_sub(tensor, indices, updates)
print(updated)
 The resulting tensor would look like this: [[[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],
 [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
 [[-4, -4, -4, -4], [-5, -5, -5, -5], [-6, -6, -6, -6], [-7, -7, -7, -7]],
 [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]]
 Note that on CPU, if an out of bound index is found, an error is returned. On GPU, if an out of bound index is found, the index is ignored.

 Args
  tensor   A Tensor. Tensor to copy/update.
  indices   A Tensor. Must be one of the following types: int32, int64. Index tensor.
  updates   A Tensor. Must have the same type as tensor. Updates to scatter into output.
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as tensor.


tf.tensor_scatter_nd_update     View source on GitHub    "Scatter updates into an existing tensor according to indices.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tensor_scatter_nd_update, tf.compat.v1.tensor_scatter_update
tf.tensor_scatter_nd_update(
    tensor, indices, updates, name=None
)
 This operation creates a new tensor by applying sparse updates to the input tensor. This is similar to an index assignment. # Not implemented: tensors cannot be updated inplace.
tensor[indices] = updates
 If an out of bound index is found on CPU, an error is returned.  Warning: There are some GPU specific semantics for this operation.  If an out of bound index is found, the index is ignored. The order in which updates are applied is nondeterministic, so the output will be nondeterministic if indices contains duplicates.   This operation is very similar to tf.scatter_nd, except that the updates are scattered onto an existing tensor (as opposed to a zero-tensor). If the memory for the existing tensor cannot be re-used, a copy is made and updated. In general:
indices is an integer tensor - the indices to update in tensor.
indices has at least two axes, the last axis is the depth of the index vectors. For each index vector in indices there is a corresponding entry in updates. If the length of the index vectors matches the rank of the tensor, then the index vectors each point to scalars in tensor and each update is a scalar. If the length of the index vectors is less than the rank of tensor, then the index vectors each point to slices of tensor and shape of the updates must match that slice.  Overall this leads to the following shape constraints: assert tf.rank(indices) >= 2
index_depth = indices.shape[-1]
batch_shape = indices.shape[:-1]
assert index_depth <= tf.rank(tensor)
outer_shape = tensor.shape[:index_depth]
inner_shape = tensor.shape[index_depth:]
assert updates.shape == batch_shape + inner_shape
 Typical usage is often much simpler than this general form, and it can be better understood starting with simple examples: Scalar updates The simplest usage inserts scalar elements into a tensor by index. In this case, the index_depth must equal the rank of the input tensor, slice each column of indices is an index into an axis of the input tensor. In this simplest case the shape constraints are: num_updates, index_depth = indices.shape.as_list()
assert updates.shape == [num_updates]
assert index_depth == tf.rank(tensor)`
 For example, to insert 4 scattered elements in a rank-1 tensor with 8 elements.    This scatter operation would look like this:
tensor = [0, 0, 0, 0, 0, 0, 0, 0]    # tf.rank(tensor) == 1
indices = [[1], [3], [4], [7]]       # num_updates == 4, index_depth == 1
updates = [9, 10, 11, 12]            # num_updates == 4
print(tf.tensor_scatter_nd_update(tensor, indices, updates))
tf.Tensor([ 0 9  0 10  11  0  0 12], shape=(8,), dtype=int32)
 The length (first axis) of updates must equal the length of the indices: num_updates. This is the the number of updates being inserted. Each scalar update is inserted into tensor at the indexed location. For a higher rank input tensor scalar updates can be inserted by using an index_depth that matches tf.rank(tensor):
tensor = [[1, 1], [1, 1], [1, 1]]    # tf.rank(tensor) == 2
indices = [[0, 1], [2, 0]]           # num_updates == 2, index_depth == 2
updates = [5, 10]                    # num_updates == 2
print(tf.tensor_scatter_nd_update(tensor, indices, updates))
tf.Tensor(
    [[ 1  5]
     [ 1  1]
     [10  1]], shape=(3, 2), dtype=int32)
 Slice updates When the input tensor has more than one axis scatter can be used to update entire slices. In this case it's helpful to think of the input tensor as being a two level array-of-arrays. The shape of this two level array is split into the outer_shape and the inner_shape. indices indexes into the outer level of the input tensor (outer_shape). and replaces the sub-array at that location with the coresponding item from the updates list. The shape of each update is inner_shape. When updating a list of slices the shape constraints are: num_updates, index_depth = indices.shape.as_list()
inner_shape = tensor.shape[:index_depth]
outer_shape = tensor.shape[index_depth:]
assert updates.shape == [num_updates, inner_shape]
 For example, to update rows of a (6, 3) tensor:
tensor = tf.zeros([6, 3], dtype=tf.int32)
 Use an index depth of one.
indices = tf.constant([[2], [4]])     # num_updates == 2, index_depth == 1
num_updates, index_depth = indices.shape.as_list()
 The outer_shape is 6, the inner shape is 3:
outer_shape = tensor.shape[:index_depth]
inner_shape = tensor.shape[index_depth:]
 2 rows are being indexed so 2 updates must be supplied. Each update must be shaped to match the inner_shape.
# num_updates == 2, inner_shape==3
updates = tf.constant([[1, 2, 3],
                       [4, 5, 6]])
 Alltogether this gives:
tf.tensor_scatter_nd_update(tensor, indices, updates).numpy()
array([[0, 0, 0],
       [0, 0, 0],
       [1, 2, 3],
       [0, 0, 0],
       [4, 5, 6],
       [0, 0, 0]], dtype=int32)
 More slice update examples A tensor representing a batch of uniformly sized video clips naturally has 5 axes: [batch_size, time, width, height, channels]. For example:
batch_size, time, width, height, channels = 13,11,7,5,3
video_batch = tf.zeros([batch_size, time, width, height, channels])
 To replace a selection of video clips:  Use an index_depth of 1 (indexing the outer_shape: [batch_size]) Provide updates each with a shape matching the inner_shape: [time, width, height, channels].  To relace the first two clips with ones:
indices = [[0],[1]]
new_clips = tf.ones([2, time, width, height, channels])
tf.tensor_scatter_nd_update(video_batch, indices, new_clips)
 To replace a selection of frames in the videos:
indices must have an index_depth of 2 for the outer_shape: [batch_size, time].
updates must be shaped like a list of images. Each update must have a shape, matching the inner_shape: [width, height, channels].  To replace the first frame of the first three video clips:
indices = [[0, 0], [1, 0], [2, 0]] # num_updates=3, index_depth=2
new_images = tf.ones([
  # num_updates=3, inner_shape=(width, height, channels)
  3, width, height, channels])
tf.tensor_scatter_nd_update(video_batch, indices, new_images)
 Folded indices In simple cases it's convienient to think of indices and updates as lists, but this is not a strict requirement. Instead of a flat num_updates, the indices and updates can be folded into a batch_shape. This batch_shape is all axes of the indices, except for the innermost index_depth axis. index_depth = indices.shape[-1]
batch_shape = indices.shape[:-1]

Note: The one exception is that the batch_shape cannot be []. You can't update a single index by passing indices with shape [index_depth].
 updates must have a matching batch_shape (the axes before inner_shape). assert updates.shape == batch_shape + inner_shape

Note: The result is equivalent to flattening the batch_shape axes of indices and updates. This generalization just avoids the need for reshapes when it is more natural to construct "folded" indices and updates.
 With this generalization the full shape constraints are: assert tf.rank(indices) >= 2
index_depth = indices.shape[-1]
batch_shape = indices.shape[:-1]
assert index_depth <= tf.rank(tensor)
outer_shape = tensor.shape[:index_depth]
inner_shape = tensor.shape[index_depth:]
assert updates.shape == batch_shape + inner_shape
 For example, to draw an X on a (5,5) matrix start with these indices:
tensor = tf.zeros([5,5])
indices = tf.constant([
 [[0,0],
  [1,1],
  [2,2],
  [3,3],
  [4,4]],
 [[0,4],
  [1,3],
  [2,2],
  [3,1],
  [4,0]],
])
indices.shape.as_list()  # batch_shape == [2, 5], index_depth == 2
[2, 5, 2]
 Here the indices do not have a shape of [num_updates, index_depth], but a shape of batch_shape+[index_depth]. Since the index_depth is equal to the rank of tensor:
outer_shape is (5,5)

inner_shape is () - each update is scalar
updates.shape is batch_shape + inner_shape == (5,2) + ()

updates = [
  [1,1,1,1,1],
  [1,1,1,1,1],
]
 Putting this together gives:
tf.tensor_scatter_nd_update(tensor, indices, updates).numpy()
array([[1., 0., 0., 0., 1.],
       [0., 1., 0., 1., 0.],
       [0., 0., 1., 0., 0.],
       [0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 1.]], dtype=float32)

 Args
  tensor   Tensor to copy/update.
  indices   Indices to update.
  updates   Updates to apply at the indices.
  name   Optional name for the operation.

 Returns   A new tensor with the given shape and updates applied according to the indices.


Module: tf.test Testing. Classes class Benchmark: Abstract class that provides helpers for TensorFlow benchmarks. class TestCase: Base class for tests that need to test TensorFlow. Functions assert_equal_graph_def(...): Asserts that two GraphDefs are (mostly) the same. benchmark_config(...): Returns a tf.compat.v1.ConfigProto for disabling the dependency optimizer. compute_gradient(...): Computes the theoretical and numeric Jacobian of f. create_local_cluster(...): Create and start local servers and return the associated Server objects. gpu_device_name(...): Returns the name of a GPU device if available or the empty string. is_built_with_cuda(...): Returns whether TensorFlow was built with CUDA (GPU) support. is_built_with_gpu_support(...): Returns whether TensorFlow was built with GPU (i.e. CUDA or ROCm) support. is_built_with_rocm(...): Returns whether TensorFlow was built with ROCm (GPU) support. is_built_with_xla(...): Returns whether TensorFlow was built with XLA support. is_gpu_available(...): Returns whether TensorFlow can access a GPU. (deprecated) main(...): Runs all unit tests.


tf.test.assert_equal_graph_def     View source on GitHub    Asserts that two GraphDefs are (mostly) the same.
tf.test.assert_equal_graph_def(
    expected, actual
)
 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. This function ignores randomized attribute values that may appear in V2 checkpoints.

 Args
  expected   The GraphDef we expected.
  actual   The GraphDef we have.

 Raises
  AssertionError   If the GraphDefs do not match.
  TypeError   If either argument is not a GraphDef.


tf.test.Benchmark     View source on GitHub    Abstract class that provides helpers for TensorFlow benchmarks.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.Benchmark
tf.test.Benchmark()
 Methods evaluate View source
evaluate(
    tensors
)
 Evaluates tensors and returns numpy values.

 Args
  tensors   A Tensor or a nested list/tuple of Tensors.

 Returns   tensors numpy values.
 is_abstract View source
@classmethod
is_abstract()
 report_benchmark View source
report_benchmark(
    iters=None, cpu_time=None, wall_time=None, throughput=None, extras=None,
    name=None, metrics=None
)
 Report a benchmark.

 Args
  iters   (optional) How many iterations were run
  cpu_time   (optional) Median or mean cpu time in seconds.
  wall_time   (optional) Median or mean wall time in seconds.
  throughput   (optional) Throughput (in MB/s)
  extras   (optional) Dict mapping string keys to additional benchmark info. Values may be either floats or values that are convertible to strings.
  name   (optional) Override the BenchmarkEntry name with name. Otherwise it is inferred from the top-level method name.
  metrics   (optional) A list of dict, where each dict has the keys below name (required), string, metric name value (required), double, metric value min_value (optional), double, minimum acceptable metric value max_value (optional), double, maximum acceptable metric value    run_op_benchmark View source
run_op_benchmark(
    sess, op_or_tensor, feed_dict=None, burn_iters=2, min_iters=10,
    store_trace=False, store_memory_usage=True, name=None, extras=None, mbs=0
)
 Run an op or tensor in the given session. Report the results.

 Args
  sess   Session object to use for timing.
  op_or_tensor   Operation or Tensor to benchmark.
  feed_dict   A dict of values to feed for each op iteration (see the feed_dict parameter of Session.run).
  burn_iters   Number of burn-in iterations to run.
  min_iters   Minimum number of iterations to use for timing.
  store_trace   Boolean, whether to run an extra untimed iteration and store the trace of iteration in returned extras. The trace will be stored as a string in Google Chrome trace format in the extras field "full_trace_chrome_format". Note that trace will not be stored in test_log_pb2.TestResults proto.
  store_memory_usage   Boolean, whether to run an extra untimed iteration, calculate memory usage, and store that in extras fields.
  name   (optional) Override the BenchmarkEntry name with name. Otherwise it is inferred from the top-level method name.
  extras   (optional) Dict mapping string keys to additional benchmark info. Values may be either floats or values that are convertible to strings.
  mbs   (optional) The number of megabytes moved by this op, used to calculate the ops throughput.

 Returns   A dict containing the key-value pairs that were passed to report_benchmark. If store_trace option is used, then full_chrome_trace_format will be included in return dictionary even though it is not passed to report_benchmark with extras.


tf.test.benchmark_config     View source on GitHub    Returns a tf.compat.v1.ConfigProto for disabling the dependency optimizer.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.benchmark_config
tf.test.benchmark_config()

 Returns   A TensorFlow ConfigProto object.


tf.test.compute_gradient     View source on GitHub    Computes the theoretical and numeric Jacobian of f.
tf.test.compute_gradient(
    f, x, delta=0.001
)
 With y = f(x), computes the theoretical and numeric Jacobian dy/dx.

 Args
  f   the function.
  x   the arguments for the function as a list or tuple of values convertible to a Tensor.
  delta   (optional) perturbation used to compute numeric Jacobian.

 Returns   A pair of lists, where the first is a list of 2-d numpy arrays representing the theoretical Jacobians for each argument, and the second list is the numerical ones. Each 2-d array has "y_size" rows and "x_size" columns where "x_size" is the number of elements in the corresponding argument and "y_size" is the number of elements in f(x).

 Raises
  ValueError   If result is empty but the gradient is nonzero.
  ValueError   If x is not list, but any other type.    Example: @tf.function
def test_func(x):
  return x*x

theoretical, numerical = tf.test.compute_gradient(test_func, [1.0])
theoretical, numerical
# ((array([[2.]], dtype=float32),), (array([[2.000004]], dtype=float32),))


tf.test.create_local_cluster     View source on GitHub    Create and start local servers and return the associated Server objects.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.create_local_cluster
tf.test.create_local_cluster(
    num_workers, num_ps, protocol='grpc', worker_config=None,
    ps_config=None
)
 "PS" stands for "parameter server": a task responsible for storing and updating the model's parameters. Other tasks send updates to these parameters as they work on optimizing the parameters. This particular division of labor between tasks is not required, but is common for distributed training. Read more at https://www.tensorflow.org/guide/extend/architecture  Figure illustrates the interaction of these components. "/job:worker/task:0" and "/job:ps/task:0" are both tasks with worker services. Example: workers, _ = tf.test.create_local_cluster(num_workers=2, num_ps=2)

worker_sessions = [tf.compat.v1.Session(w.target) for w in workers]

with tf.device("/job:ps/task:0"):
  ...
with tf.device("/job:ps/task:1"):
  ...
with tf.device("/job:worker/task:0"):
  ...
with tf.device("/job:worker/task:1"):
  ...

worker_sessions[0].run(...)

 Args
  num_workers   Number of worker servers to start.
  num_ps   Number of PS servers to start.
  protocol   Communication protocol. Allowed values are documented in the documentation of tf.distribute.Server.
  worker_config   (optional) tf.ConfigProto to initialize workers. Can be used to instantiate multiple devices etc.
  ps_config   (optional) tf.ConfigProto to initialize PS servers.

 Returns   A tuple (worker_servers, ps_servers). worker_servers is a list of num_workers objects of type tf.distribute.Server (all running locally); and ps_servers is a list of num_ps objects of similar type.

 Raises
  ImportError   if portpicker module was not found at load time


tf.test.gpu_device_name     View source on GitHub    Returns the name of a GPU device if available or the empty string.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.gpu_device_name
tf.test.gpu_device_name()


tf.test.is_built_with_cuda     View source on GitHub    Returns whether TensorFlow was built with CUDA (GPU) support.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.is_built_with_cuda
tf.test.is_built_with_cuda()


tf.test.is_built_with_gpu_support     View source on GitHub    Returns whether TensorFlow was built with GPU (i.e. CUDA or ROCm) support.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.is_built_with_gpu_support
tf.test.is_built_with_gpu_support()


tf.test.is_built_with_rocm     View source on GitHub    Returns whether TensorFlow was built with ROCm (GPU) support.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.is_built_with_rocm
tf.test.is_built_with_rocm()


tf.test.is_built_with_xla Returns whether TensorFlow was built with XLA support.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.is_built_with_xla
tf.test.is_built_with_xla()


tf.test.is_gpu_available     View source on GitHub    Returns whether TensorFlow can access a GPU. (deprecated)  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.is_gpu_available
tf.test.is_gpu_available(
    cuda_only=False, min_cuda_compute_capability=None
)
 Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use tf.config.list_physical_devices('GPU') instead.Warning: if a non-GPU version of the package is installed, the function would also return False. Use tf.test.is_built_with_cuda to validate if TensorFlow was build with CUDA support.

 Args
  cuda_only   limit the search to CUDA GPUs.
  min_cuda_compute_capability   a (major,minor) pair that indicates the minimum CUDA compute capability required, or None if no requirement.    Note that the keyword arg name "cuda_only" is misleading (since routine will return true when a GPU device is available irrespective of whether TF was built with CUDA support or ROCm support. However no changes here because ++ Changing the name "cuda_only" to something more generic would break backward compatibility ++ Adding an equivalent "rocm_only" would require the implementation check the build type. This in turn would require doing the same for CUDA and thus potentially break backward compatibility ++ Adding a new "cuda_or_rocm_only" would not break backward compatibility, but would require most (if not all) callers to update the call to use "cuda_or_rocm_only" instead of "cuda_only"

 Returns   True if a GPU device of the requested kind is available.


tf.test.main     View source on GitHub    Runs all unit tests.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.main
tf.test.main(
    argv=None
)


tf.test.TestCase       View source on GitHub    Base class for tests that need to test TensorFlow.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.TestCase
tf.test.TestCase(
    methodName='runTest'
)
 Child Classes class failureException Methods addCleanup
addCleanup(
    *args, **kwargs
)
 Add a function, with arguments, to be called when the test is completed. Functions added are called on a LIFO basis and are called after tearDown on test failure or success. Cleanup items are called even if setUp fails (unlike tearDown). addTypeEqualityFunc
addTypeEqualityFunc(
    typeobj, function
)
 Add a type specific assertEqual style function to compare a type. This method is for use by TestCase subclasses that need to register their own type equality functions to provide nicer error messages.

 Args
  typeobj   The data type to call this function on when both values are of the same type in assertEqual().
  function   The callable taking two arguments and an optional msg= argument that raises self.failureException with a useful error message when the two arguments are not equal.    assertAllClose View source
assertAllClose(
    a, b, rtol=1e-06, atol=1e-06, msg=None
)
 Asserts that two structures of numpy arrays or Tensors, have near values. a and b can be arbitrarily nested structures. A layer of a nested structure can be a dict, namedtuple, tuple or list.
Note: the implementation follows numpy.allclose (and numpy.testing.assert_allclose). It checks whether two arrays are element-wise equal within a tolerance. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

 Args
  a   The expected numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor), or any arbitrarily nested of structure of these.
  b   The actual numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor), or any arbitrarily nested of structure of these.
  rtol   relative tolerance.
  atol   absolute tolerance.
  msg   Optional message to report on failure.

 Raises
  ValueError   if only one of a[p] and b[p] is a dict or a[p] and b[p] have different length, where [p] denotes a path to the nested structure, e.g. given a = [(1, 1), {'d': (6, 7)}] and [p] = [1]['d'], then a[p] = (6, 7).    assertAllCloseAccordingToType View source
assertAllCloseAccordingToType(
    a, b, rtol=1e-06, atol=1e-06, float_rtol=1e-06, float_atol=1e-06,
    half_rtol=0.001, half_atol=0.001, bfloat16_rtol=0.01, bfloat16_atol=0.01,
    msg=None
)
 Like assertAllClose, but also suitable for comparing fp16 arrays. In particular, the tolerance is reduced to 1e-3 if at least one of the arguments is of type float16.

 Args
  a   the expected numpy ndarray or anything can be converted to one.
  b   the actual numpy ndarray or anything can be converted to one.
  rtol   relative tolerance.
  atol   absolute tolerance.
  float_rtol   relative tolerance for float32.
  float_atol   absolute tolerance for float32.
  half_rtol   relative tolerance for float16.
  half_atol   absolute tolerance for float16.
  bfloat16_rtol   relative tolerance for bfloat16.
  bfloat16_atol   absolute tolerance for bfloat16.
  msg   Optional message to report on failure.    assertAllEqual View source
assertAllEqual(
    a, b, msg=None
)
 Asserts that two numpy arrays or Tensors have the same values.

 Args
  a   the expected numpy ndarray or anything can be converted to one.
  b   the actual numpy ndarray or anything can be converted to one.
  msg   Optional message to report on failure.    assertAllGreater View source
assertAllGreater(
    a, comparison_target
)
 Assert element values are all greater than a target value.

 Args
  a   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  comparison_target   The target value of comparison.    assertAllGreaterEqual View source
assertAllGreaterEqual(
    a, comparison_target
)
 Assert element values are all greater than or equal to a target value.

 Args
  a   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  comparison_target   The target value of comparison.    assertAllInRange View source
assertAllInRange(
    target, lower_bound, upper_bound, open_lower_bound=False, open_upper_bound=False
)
 Assert that elements in a Tensor are all in a given range.

 Args
  target   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  lower_bound   lower bound of the range
  upper_bound   upper bound of the range
  open_lower_bound   (bool) whether the lower bound is open (i.e., > rather than the default >=)
  open_upper_bound   (bool) whether the upper bound is open (i.e., < rather than the default <=)

 Raises
  AssertionError   if the value tensor does not have an ordered numeric type (float* or int*), or if there are nan values, or if any of the elements do not fall in the specified range.    assertAllInSet View source
assertAllInSet(
    target, expected_set
)
 Assert that elements of a Tensor are all in a given closed set.

 Args
  target   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  expected_set   (list, tuple or set) The closed set that the elements of the value of target are expected to fall into.

 Raises
  AssertionError   if any of the elements do not fall into expected_set.    assertAllLess View source
assertAllLess(
    a, comparison_target
)
 Assert element values are all less than a target value.

 Args
  a   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  comparison_target   The target value of comparison.    assertAllLessEqual View source
assertAllLessEqual(
    a, comparison_target
)
 Assert element values are all less than or equal to a target value.

 Args
  a   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  comparison_target   The target value of comparison.    assertAlmostEqual
assertAlmostEqual(
    first, second, places=None, msg=None, delta=None
)
 Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). If the two objects compare equal then they will automatically compare almost equal. assertAlmostEquals
assertAlmostEquals(
    *args, **kwargs
)
 assertArrayNear View source
assertArrayNear(
    farray1, farray2, err, msg=None
)
 Asserts that two float arrays are near each other. Checks that for all elements of farray1 and farray2 |f1 - f2| < err. Asserts a test failure if not.

 Args
  farray1   a list of float values.
  farray2   a list of float values.
  err   a float value.
  msg   Optional message to report on failure.    assertBetween
assertBetween(
    value, minv, maxv, msg=None
)
 Asserts that value is between minv and maxv (inclusive). assertCommandFails
assertCommandFails(
    command, regexes, env=None, close_fds=True, msg=None
)
 Asserts a shell command fails and the error matches a regex in a list.

 Args
  command   List or string representing the command to run.
  regexes   the list of regular expression strings.
  env   Dictionary of environment variable settings. If None, no environment variables will be set for the child process. This is to make tests more hermetic. NOTE: this behavior is different than the standard subprocess module.
  close_fds   Whether or not to close all open fd's in the child after forking.
  msg   Optional message to report on failure.    assertCommandSucceeds
assertCommandSucceeds(
    command, regexes=(b'',), env=None, close_fds=True, msg=None
)
 Asserts that a shell command succeeds (i.e. exits with code 0).

 Args
  command   List or string representing the command to run.
  regexes   List of regular expression byte strings that match success.
  env   Dictionary of environment variable settings. If None, no environment variables will be set for the child process. This is to make tests more hermetic. NOTE: this behavior is different than the standard subprocess module.
  close_fds   Whether or not to close all open fd's in the child after forking.
  msg   Optional message to report on failure.    assertContainsExactSubsequence
assertContainsExactSubsequence(
    container, subsequence, msg=None
)
 Asserts that "container" contains "subsequence" as an exact subsequence. Asserts that "container" contains all the elements of "subsequence", in order, and without other elements interspersed. For example, [1, 2, 3] is an exact subsequence of [0, 0, 1, 2, 3, 0] but not of [0, 0, 1, 2, 0, 3, 0].

 Args
  container   the list we're testing for subsequence inclusion.
  subsequence   the list we hope will be an exact subsequence of container.
  msg   Optional message to report on failure.    assertContainsInOrder
assertContainsInOrder(
    strings, target, msg=None
)
 Asserts that the strings provided are found in the target in order. This may be useful for checking HTML output.

 Args
  strings   A list of strings, such as [ 'fox', 'dog' ]
  target   A target string in which to look for the strings, such as 'The quick brown fox jumped over the lazy dog'.
  msg   Optional message to report on failure.    assertContainsSubsequence
assertContainsSubsequence(
    container, subsequence, msg=None
)
 Asserts that "container" contains "subsequence" as a subsequence. Asserts that "container" contains all the elements of "subsequence", in order, but possibly with other elements interspersed. For example, [1, 2, 3] is a subsequence of [0, 0, 1, 2, 0, 3, 0] but not of [0, 0, 1, 3, 0, 2, 0].

 Args
  container   the list we're testing for subsequence inclusion.
  subsequence   the list we hope will be a subsequence of container.
  msg   Optional message to report on failure.    assertContainsSubset
assertContainsSubset(
    expected_subset, actual_set, msg=None
)
 Checks whether actual iterable is a superset of expected iterable. assertCountEqual
assertCountEqual(
    first, second, msg=None
)
 An unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times. self.assertEqual(Counter(list(first)),
                 Counter(list(second)))
 Example: - [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
 assertDTypeEqual View source
assertDTypeEqual(
    target, expected_dtype
)
 Assert ndarray data type is equal to expected.

 Args
  target   The numpy ndarray, or anything that can be converted into a numpy ndarray (including Tensor).
  expected_dtype   Expected data type.    assertDeviceEqual View source
assertDeviceEqual(
    device1, device2, msg=None
)
 Asserts that the two given devices are the same.

 Args
  device1   A string device name or TensorFlow DeviceSpec object.
  device2   A string device name or TensorFlow DeviceSpec object.
  msg   Optional message to report on failure.    assertDictContainsSubset
assertDictContainsSubset(
    subset, dictionary, msg=None
)
 Checks whether dictionary is a superset of subset. assertDictEqual
assertDictEqual(
    a, b, msg=None
)
 Raises AssertionError if a and b are not equal dictionaries.

 Args
  a   A dict, the expected value.
  b   A dict, the actual value.
  msg   An optional str, the associated message.

 Raises
  AssertionError   if the dictionaries are not equal.    assertEmpty
assertEmpty(
    container, msg=None
)
 Asserts that an object has zero length.

 Args
  container   Anything that implements the collections.abc.Sized interface.
  msg   Optional message to report on failure.    assertEndsWith
assertEndsWith(
    actual, expected_end, msg=None
)
 Asserts that actual.endswith(expected_end) is True.

 Args
  actual   str
  expected_end   str
  msg   Optional message to report on failure.    assertEqual
assertEqual(
    first, second, msg=None
)
 Fail if the two objects are unequal as determined by the '==' operator. assertEquals
assertEquals(
    *args, **kwargs
)
 assertFalse
assertFalse(
    expr, msg=None
)
 Check that the expression is false. assertGreater
assertGreater(
    a, b, msg=None
)
 Just like self.assertTrue(a > b), but with a nicer default message. assertGreaterEqual
assertGreaterEqual(
    a, b, msg=None
)
 Just like self.assertTrue(a >= b), but with a nicer default message. assertIn
assertIn(
    member, container, msg=None
)
 Just like self.assertTrue(a in b), but with a nicer default message. assertIs
assertIs(
    expr1, expr2, msg=None
)
 Just like self.assertTrue(a is b), but with a nicer default message. assertIsInstance
assertIsInstance(
    obj, cls, msg=None
)
 Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message. assertIsNone
assertIsNone(
    obj, msg=None
)
 Same as self.assertTrue(obj is None), with a nicer default message. assertIsNot
assertIsNot(
    expr1, expr2, msg=None
)
 Just like self.assertTrue(a is not b), but with a nicer default message. assertIsNotNone
assertIsNotNone(
    obj, msg=None
)
 Included for symmetry with assertIsNone. assertItemsEqual
assertItemsEqual(
    first, second, msg=None
)
 An unordered sequence comparison asserting that the same elements, regardless of order. If the same element occurs more than once, it verifies that the elements occur the same number of times. self.assertEqual(Counter(list(first)),
                 Counter(list(second)))
 Example: - [0, 1, 1] and [1, 0, 1] compare equal.
- [0, 0, 1] and [0, 1] compare unequal.
 assertJsonEqual
assertJsonEqual(
    first, second, msg=None
)
 Asserts that the JSON objects defined in two strings are equal. A summary of the differences will be included in the failure message using assertSameStructure.

 Args
  first   A string containing JSON to decode and compare to second.
  second   A string containing JSON to decode and compare to first.
  msg   Additional text to include in the failure message.    assertLen
assertLen(
    container, expected_len, msg=None
)
 Asserts that an object has the expected length.

 Args
  container   Anything that implements the collections.abc.Sized interface.
  expected_len   The expected length of the container.
  msg   Optional message to report on failure.    assertLess
assertLess(
    a, b, msg=None
)
 Just like self.assertTrue(a < b), but with a nicer default message. assertLessEqual
assertLessEqual(
    a, b, msg=None
)
 Just like self.assertTrue(a <= b), but with a nicer default message. assertListEqual
assertListEqual(
    list1, list2, msg=None
)
 A list-specific equality assertion.

 Args
  list1   The first list to compare.
  list2   The second list to compare.
  msg   Optional message to use on failure instead of a list of differences.    assertLogs
assertLogs(
    logger=None, level=None
)
 Fail unless a log message of level level or higher is emitted on logger_name or its children. If omitted, level defaults to INFO and logger defaults to the root logger. This method must be used as a context manager, and will yield a recording object with two attributes: output and records. At the end of the context manager, the output attribute will be a list of the matching formatted log messages and the records attribute will be a list of the corresponding LogRecord objects. Example:: with self.assertLogs('foo', level='INFO') as cm:
    logging.getLogger('foo').info('first message')
    logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
                             'ERROR:foo.bar:second message'])
 assertMultiLineEqual
assertMultiLineEqual(
    first, second, msg=None, **kwargs
)
 Asserts that two multi-line strings are equal. assertNDArrayNear View source
assertNDArrayNear(
    ndarray1, ndarray2, err, msg=None
)
 Asserts that two numpy arrays have near values.

 Args
  ndarray1   a numpy ndarray.
  ndarray2   a numpy ndarray.
  err   a float. The maximum absolute difference allowed.
  msg   Optional message to report on failure.    assertNear View source
assertNear(
    f1, f2, err, msg=None
)
 Asserts that two floats are near each other. Checks that |f1 - f2| < err and asserts a test failure if not.

 Args
  f1   A float value.
  f2   A float value.
  err   A float value.
  msg   An optional string message to append to the failure message.    assertNoCommonElements
assertNoCommonElements(
    expected_seq, actual_seq, msg=None
)
 Checks whether actual iterable and expected iterable are disjoint. assertNotAllClose View source
assertNotAllClose(
    a, b, **kwargs
)
 Assert that two numpy arrays, or Tensors, do not have near values.

 Args
  a   the first value to compare.
  b   the second value to compare.
  **kwargs   additional keyword arguments to be passed to the underlying assertAllClose call.

 Raises
  AssertionError   If a and b are unexpectedly close at all elements.    assertNotAllEqual View source
assertNotAllEqual(
    a, b, msg=None
)
 Asserts that two numpy arrays or Tensors do not have the same values.

 Args
  a   the expected numpy ndarray or anything can be converted to one.
  b   the actual numpy ndarray or anything can be converted to one.
  msg   Optional message to report on failure.    assertNotAlmostEqual
assertNotAlmostEqual(
    first, second, places=None, msg=None, delta=None
)
 Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). Objects that are equal automatically fail. assertNotAlmostEquals
assertNotAlmostEquals(
    *args, **kwargs
)
 assertNotEmpty
assertNotEmpty(
    container, msg=None
)
 Asserts that an object has non-zero length.

 Args
  container   Anything that implements the collections.abc.Sized interface.
  msg   Optional message to report on failure.    assertNotEndsWith
assertNotEndsWith(
    actual, unexpected_end, msg=None
)
 Asserts that actual.endswith(unexpected_end) is False.

 Args
  actual   str
  unexpected_end   str
  msg   Optional message to report on failure.    assertNotEqual
assertNotEqual(
    first, second, msg=None
)
 Fail if the two objects are equal as determined by the '!=' operator. assertNotEquals
assertNotEquals(
    *args, **kwargs
)
 assertNotIn
assertNotIn(
    member, container, msg=None
)
 Just like self.assertTrue(a not in b), but with a nicer default message. assertNotIsInstance
assertNotIsInstance(
    obj, cls, msg=None
)
 Included for symmetry with assertIsInstance. assertNotRegex
assertNotRegex(
    text, unexpected_regex, msg=None
)
 Fail the test if the text matches the regular expression. assertNotRegexpMatches
assertNotRegexpMatches(
    *args, **kwargs
)
 assertNotStartsWith
assertNotStartsWith(
    actual, unexpected_start, msg=None
)
 Asserts that actual.startswith(unexpected_start) is False.

 Args
  actual   str
  unexpected_start   str
  msg   Optional message to report on failure.    assertProtoEquals View source
assertProtoEquals(
    expected_message_maybe_ascii, message, msg=None
)
 Asserts that message is same as parsed expected_message_ascii. Creates another prototype of message, reads the ascii message into it and then compares them using self._AssertProtoEqual().

 Args
  expected_message_maybe_ascii   proto message in original or ascii form.
  message   the message to validate.
  msg   Optional message to report on failure.    assertProtoEqualsVersion View source
assertProtoEqualsVersion(
    expected, actual, producer=versions.GRAPH_DEF_VERSION,
    min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER, msg=None
)
 assertRaises
assertRaises(
    expected_exception, *args, **kwargs
)
 Fail unless an exception of class expected_exception is raised by the callable when invoked with specified positional and keyword arguments. If a different type of exception is raised, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertRaises(SomeException):
    do_something()
 An optional keyword argument 'msg' can be provided when assertRaises is used as a context object. The context manager keeps a reference to the exception as the 'exception' attribute. This allows you to inspect the exception after the assertion:: with self.assertRaises(SomeException) as cm:
    do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
 assertRaisesOpError View source
assertRaisesOpError(
    expected_err_re_or_predicate
)
 assertRaisesRegex
assertRaisesRegex(
    expected_exception, expected_regex, *args, **kwargs
)
 Asserts that the message in a raised exception matches a regex.

 Args
  expected_exception   Exception class expected to be raised.
  expected_regex   Regex (re.Pattern object or string) expected to be found in error message.
  args   Function to be called and extra positional args.
  kwargs   Extra kwargs.
  msg   Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager.    assertRaisesRegexp
assertRaisesRegexp(
    expected_exception, expected_regex, *args, **kwargs
)
 Asserts that the message in a raised exception matches a regex.

 Args
  expected_exception   Exception class expected to be raised.
  expected_regex   Regex (re.Pattern object or string) expected to be found in error message.
  args   Function to be called and extra positional args.
  kwargs   Extra kwargs.
  msg   Optional message used in case of failure. Can only be used when assertRaisesRegex is used as a context manager.    assertRaisesWithLiteralMatch
assertRaisesWithLiteralMatch(
    expected_exception, expected_exception_message, callable_obj=None, *args,
    **kwargs
)
 Asserts that the message in a raised exception equals the given string. Unlike assertRaisesRegex, this method takes a literal string, not a regular expression. with self.assertRaisesWithLiteralMatch(ExType, 'message'): DoSomething()

 Args
  expected_exception   Exception class expected to be raised.
  expected_exception_message   String message expected in the raised exception. For a raise exception e, expected_exception_message must equal str(e).
  callable_obj   Function to be called, or None to return a context.
  *args   Extra args.
  **kwargs   Extra kwargs.

 Returns   A context manager if callable_obj is None. Otherwise, None.

 Raises   self.failureException if callable_obj does not raise a matching exception.
 assertRaisesWithPredicateMatch View source
@contextlib.contextmanager
assertRaisesWithPredicateMatch(
    exception_type, expected_err_re_or_predicate
)
 Returns a context manager to enclose code expected to raise an exception. If the exception is an OpError, the op stack is also included in the message predicate search.

 Args
  exception_type   The expected type of exception that should be raised.
  expected_err_re_or_predicate   If this is callable, it should be a function of one argument that inspects the passed-in exception and returns True (success) or False (please fail the test). Otherwise, the error message is expected to match this regular expression partially.

 Returns   A context manager to surround code that is expected to raise an exception.
 assertRegex
assertRegex(
    text, expected_regex, msg=None
)
 Fail the test unless the text matches the regular expression. assertRegexMatch
assertRegexMatch(
    actual_str, regexes, message=None
)
 Asserts that at least one regex in regexes matches str. If possible you should use assertRegex, which is a simpler version of this method. assertRegex takes a single regular expression (a string or re compiled object) instead of a list. Notes:  This function uses substring matching, i.e. the matching succeeds if any substring of the error message matches any regex in the list. This is more convenient for the user than full-string matching. If regexes is the empty list, the matching will always fail. Use regexes=[''] for a regex that will always pass. '.' matches any single character except the newline. To match any character, use '(.|\n)'. '^' matches the beginning of each line, not just the beginning of the string. Similarly, '$' matches the end of each line. An exception will be thrown if regexes contains an invalid regex.

 Args
  actual_str   The string we try to match with the items in regexes.
  regexes   The regular expressions we want to match against str. See "Notes" above for detailed notes on how this is interpreted.
  message   The message to be printed if the test fails.    assertRegexpMatches
assertRegexpMatches(
    *args, **kwargs
)
 assertSameElements
assertSameElements(
    expected_seq, actual_seq, msg=None
)
 Asserts that two sequences have the same elements (in any order). This method, unlike assertCountEqual, doesn't care about any duplicates in the expected and actual sequences.  assertSameElements([1, 1, 1, 0, 0, 0], [0, 1]) # Doesn't raise an AssertionError  If possible, you should use assertCountEqual instead of assertSameElements.

 Args
  expected_seq   A sequence containing elements we are expecting.
  actual_seq   The sequence that we are testing.
  msg   The message to be printed if the test fails.    assertSameStructure
assertSameStructure(
    a, b, aname='a', bname='b', msg=None
)
 Asserts that two values contain the same structural content. The two arguments should be data trees consisting of trees of dicts and lists. They will be deeply compared by walking into the contents of dicts and lists; other items will be compared using the == operator. If the two structures differ in content, the failure message will indicate the location within the structures where the first difference is found. This may be helpful when comparing large structures. Mixed Sequence and Set types are supported. Mixed Mapping types are supported, but the order of the keys will not be considered in the comparison.

 Args
  a   The first structure to compare.
  b   The second structure to compare.
  aname   Variable name to use for the first structure in assertion messages.
  bname   Variable name to use for the second structure.
  msg   Additional text to include in the failure message.    assertSequenceAlmostEqual
assertSequenceAlmostEqual(
    expected_seq, actual_seq, places=None, msg=None, delta=None
)
 An approximate equality assertion for ordered sequences. Fail if the two sequences are unequal as determined by their value differences rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between each value in the two sequences is more than the given delta. Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit). If the two sequences compare equal then they will automatically compare almost equal.

 Args
  expected_seq   A sequence containing elements we are expecting.
  actual_seq   The sequence that we are testing.
  places   The number of decimal places to compare.
  msg   The message to be printed if the test fails.
  delta   The OK difference between compared values.    assertSequenceEqual
assertSequenceEqual(
    seq1, seq2, msg=None, seq_type=None
)
 An equality assertion for ordered sequences (like lists and tuples). For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

 Args
  seq1   The first sequence to compare.
  seq2   The second sequence to compare.
  seq_type   The expected datatype of the sequences, or None if no datatype should be enforced.
  msg   Optional message to use on failure instead of a list of differences.    assertSequenceStartsWith
assertSequenceStartsWith(
    prefix, whole, msg=None
)
 An equality assertion for the beginning of ordered sequences. If prefix is an empty sequence, it will raise an error unless whole is also an empty sequence. If prefix is not a sequence, it will raise an error if the first element of whole does not match.

 Args
  prefix   A sequence expected at the beginning of the whole parameter.
  whole   The sequence in which to look for prefix.
  msg   Optional message to report on failure.    assertSetEqual
assertSetEqual(
    set1, set2, msg=None
)
 A set-specific equality assertion.

 Args
  set1   The first set to compare.
  set2   The second set to compare.
  msg   Optional message to use on failure instead of a list of differences.    assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method). assertShapeEqual View source
assertShapeEqual(
    np_array, tf_tensor, msg=None
)
 Asserts that a Numpy ndarray and a TensorFlow tensor have the same shape.

 Args
  np_array   A Numpy ndarray or Numpy scalar.
  tf_tensor   A Tensor.
  msg   Optional message to report on failure.

 Raises
  TypeError   If the arguments have the wrong type.    assertStartsWith View source
assertStartsWith(
    actual, expected_start, msg=None
)
 Assert that actual.startswith(expected_start) is True.

 Args
  actual   str
  expected_start   str
  msg   Optional message to report on failure.    assertTotallyOrdered
assertTotallyOrdered(
    *groups, **kwargs
)
 Asserts that total ordering has been implemented correctly. For example, say you have a class A that compares only on its attribute x. Comparators other than lt are omitted for brevity. class A(object): def init(self, x, y): self.x = x self.y = y def hash(self): return hash(self.x) def lt(self, other): try: return self.x < other.x except AttributeError: return NotImplemented assertTotallyOrdered will check that instances can be ordered correctly. For example, self.assertTotallyOrdered( [None], # None should come before everything else. [1], # Integers sort earlier. [A(1, 'a')], [A(2, 'b')], # 2 is after 1. [A(3, 'c'), A(3, 'd')], # The second argument is irrelevant. [A(4, 'z')], ['foo']) # Strings sort last.

 Args
  *groups   A list of groups of elements. Each group of elements is a list of objects that are equal. The elements in each group must be less than the elements in the group after it. For example, these groups are totally ordered: [None], [1], [2, 2], [3]. **kwargs: optional msg keyword argument can be passed.    assertTrue
assertTrue(
    expr, msg=None
)
 Check that the expression is true. assertTupleEqual
assertTupleEqual(
    tuple1, tuple2, msg=None
)
 A tuple-specific equality assertion.

 Args
  tuple1   The first tuple to compare.
  tuple2   The second tuple to compare.
  msg   Optional message to use on failure instead of a list of differences.    assertUrlEqual
assertUrlEqual(
    a, b, msg=None
)
 Asserts that urls are equal, ignoring ordering of query params. assertWarns
assertWarns(
    expected_warning, *args, **kwargs
)
 Fail unless a warning of class warnClass is triggered by the callable when invoked with specified positional and keyword arguments. If a different type of warning is triggered, it will not be handled: depending on the other warning filtering rules in effect, it might be silenced, printed out, or raised as an exception. If called with the callable and arguments omitted, will return a context object used like this:: with self.assertWarns(SomeWarning):
    do_something()
 An optional keyword argument 'msg' can be provided when assertWarns is used as a context object. The context manager keeps a reference to the first matching warning as the 'warning' attribute; similarly, the 'filename' and 'lineno' attributes give you information about the line of Python code from which the warning was triggered. This allows you to inspect the warning after the assertion:: with self.assertWarns(SomeWarning) as cm:
    do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
 assertWarnsRegex
assertWarnsRegex(
    expected_warning, expected_regex, *args, **kwargs
)
 Asserts that the message in a triggered warning matches a regexp. Basic functioning is similar to assertWarns() with the addition that only warnings whose messages also match the regular expression are considered successful matches.

 Args
  expected_warning   Warning class expected to be triggered.
  expected_regex   Regex (re.Pattern object or string) expected to be found in error message.
  args   Function to be called and extra positional args.
  kwargs   Extra kwargs.
  msg   Optional message used in case of failure. Can only be used when assertWarnsRegex is used as a context manager.    assert_
assert_(
    *args, **kwargs
)
 cached_session View source
@contextlib.contextmanager
cached_session(
    graph=None, config=None, use_gpu=False, force_gpu=False
)
 Returns a TensorFlow Session for use in executing tests. This method behaves differently than self.session(): for performance reasons cached_session will by default reuse the same session within the same test. The session returned by this function will only be closed at the end of the test (in the TearDown function). Use the use_gpu and force_gpu options to control where ops are run. If force_gpu is True, all ops are pinned to /device:GPU:0. Otherwise, if use_gpu is True, TensorFlow tries to run as many ops on the GPU as possible. If both force_gpu anduse_gpu` are False, all ops are pinned to the CPU. Example: class MyOperatorTest(test_util.TensorFlowTestCase):
  def testMyOperator(self):
    with self.cached_session(use_gpu=True) as sess:
      valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
      result = MyOperator(valid_input).eval()
      self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
      invalid_input = [-1.0, 2.0, 7.0]
      with self.assertRaisesOpError("negative input not supported"):
        MyOperator(invalid_input).eval()

 Args
  graph   Optional graph to use during the returned session.
  config   An optional config_pb2.ConfigProto to use to configure the session.
  use_gpu   If True, attempt to run as many ops as possible on GPU.
  force_gpu   If True, pin all ops to /device:GPU:0.

 Yields   A Session object that should be used as a context manager to surround the graph building and execution code in a test case.
 captureWritesToStream View source
@contextlib.contextmanager
captureWritesToStream(
    stream
)
 A context manager that captures the writes to a given stream. This context manager captures all writes to a given stream inside of a CapturedWrites object. When this context manager is created, it yields the CapturedWrites object. The captured contents can be accessed by calling .contents() on the CapturedWrites. For this function to work, the stream must have a file descriptor that can be modified using os.dup and os.dup2, and the stream must support a .flush() method. The default python sys.stdout and sys.stderr are examples of this. Note that this does not work in Colab or Jupyter notebooks, because those use alternate stdout streams. Example: class MyOperatorTest(test_util.TensorFlowTestCase):
  def testMyOperator(self):
    input = [1.0, 2.0, 3.0, 4.0, 5.0]
    with self.captureWritesToStream(sys.stdout) as captured:
      result = MyOperator(input).eval()
    self.assertStartsWith(captured.contents(), "This was printed.")

 Args
  stream   The stream whose writes should be captured. This stream must have a file descriptor, support writing via using that file descriptor, and must have a .flush() method.

 Yields   A CapturedWrites object that contains all writes to the specified stream made during this context.
 checkedThread View source
checkedThread(
    target, args=None, kwargs=None
)
 Returns a Thread wrapper that asserts 'target' completes successfully. This method should be used to create all threads in test cases, as otherwise there is a risk that a thread will silently fail, and/or assertions made in the thread will not be respected.

 Args
  target   A callable object to be executed in the thread.
  args   The argument tuple for the target invocation. Defaults to ().
  kwargs   A dictionary of keyword arguments for the target invocation. Defaults to {}.

 Returns   A wrapper for threading.Thread that supports start() and join() methods.
 countTestCases
countTestCases()
 create_tempdir
create_tempdir(
    name=None, cleanup=None
)
 Create a temporary directory specific to the test.
Note: The directory and its contents will be recursively cleared before creation. This ensures that there is no pre-existing state.
 This creates a named directory on disk that is isolated to this test, and will be properly cleaned up by the test. This avoids several pitfalls of creating temporary directories for test purposes, as well as makes it easier to setup directories and verify their contents. For example: def test_foo(self):
  out_dir = self.create_tempdir()
  out_log = out_dir.create_file('output.log')
  expected_outputs = [
      os.path.join(out_dir, 'data-0.txt'),
      os.path.join(out_dir, 'data-1.txt'),
  ]
  code_under_test(out_dir)
  self.assertTrue(os.path.exists(expected_paths[0]))
  self.assertTrue(os.path.exists(expected_paths[1]))
  self.assertEqual('foo', out_log.read_text())
 See also: create_tempfile() for creating temporary files.

 Args
  name   Optional name of the directory. If not given, a unique name will be generated and used.
  cleanup   Optional cleanup policy on when/if to remove the directory (and all its contents) at the end of the test. If None, then uses self.tempfile_cleanup.

 Returns   A _TempDir representing the created directory; see _TempDir class docs for usage.
 create_tempfile
create_tempfile(
    file_path=None, content=None, mode='w', encoding='utf8',
    errors='strict', cleanup=None
)
 Create a temporary file specific to the test. This creates a named file on disk that is isolated to this test, and will be properly cleaned up by the test. This avoids several pitfalls of creating temporary files for test purposes, as well as makes it easier to setup files, their data, read them back, and inspect them when a test fails. For example: def test_foo(self):
  output = self.create_tempfile()
  code_under_test(output)
  self.assertGreater(os.path.getsize(output), 0)
  self.assertEqual('foo', output.read_text())

Note: This will zero-out the file. This ensures there is no pre-existing state. NOTE: If the file already exists, it will be made writable and overwritten.
 See also: create_tempdir() for creating temporary directories, and _TempDir.create_file for creating files within a temporary directory.

 Args
  file_path   Optional file path for the temp file. If not given, a unique file name will be generated and used. Slashes are allowed in the name; any missing intermediate directories will be created. NOTE: This path is the path that will be cleaned up, including any directories in the path, e.g., 'foo/bar/baz.txt' will rm -r foo.
  content   Optional string or bytes to initially write to the file. If not specified, then an empty file is created.
  mode   Mode string to use when writing content. Only used if content is non-empty.
  encoding   Encoding to use when writing string content. Only used if content is text.
  errors   How to handle text to bytes encoding errors. Only used if content is text.
  cleanup   Optional cleanup policy on when/if to remove the directory (and all its contents) at the end of the test. If None, then uses self.tempfile_cleanup.

 Returns   A _TempFile representing the created file; see _TempFile class docs for usage.
 debug
debug()
 Run the test without collecting errors in a TestResult defaultTestResult
defaultTestResult()
 doCleanups
doCleanups()
 Execute all cleanup functions. Normally called for you after tearDown. enter_context
enter_context(
    manager
)
 Returns the CM's value after registering it with the exit stack. Entering a context pushes it onto a stack of contexts. The context is exited when the test completes. Contexts are are exited in the reverse order of entering. They will always be exited, regardless of test failure/success. The context stack is specific to the test being run. This is useful to eliminate per-test boilerplate when context managers are used. For example, instead of decorating every test with @mock.patch, simply do self.foo = self.enter_context(mock.patch(...))' insetUp()`.
Note: The context managers will always be exited without any error information. This is an unfortunate implementation detail due to some internals of how unittest runs tests.

 Args
  manager   The context manager to enter.    evaluate View source
evaluate(
    tensors
)
 Evaluates tensors and returns numpy values.

 Args
  tensors   A Tensor or a nested list/tuple of Tensors.

 Returns   tensors numpy values.
 fail
fail(
    msg=None, prefix=None
)
 Fail immediately with the given message, optionally prefixed. failIf
failIf(
    *args, **kwargs
)
 failIfAlmostEqual
failIfAlmostEqual(
    *args, **kwargs
)
 failIfEqual
failIfEqual(
    *args, **kwargs
)
 failUnless
failUnless(
    *args, **kwargs
)
 failUnlessAlmostEqual
failUnlessAlmostEqual(
    *args, **kwargs
)
 failUnlessEqual
failUnlessEqual(
    *args, **kwargs
)
 failUnlessRaises
failUnlessRaises(
    *args, **kwargs
)
 get_temp_dir View source
get_temp_dir()
 Returns a unique temporary directory for the test to use. If you call this method multiple times during in a test, it will return the same folder. However, across different runs the directories will be different. This will ensure that across different runs tests will not be able to pollute each others environment. If you need multiple unique directories within a single test, you should use tempfile.mkdtemp as follows: tempfile.mkdtemp(dir=self.get_temp_dir()):

 Returns   string, the path to the unique temporary directory created for this test.
 id
id()
 run
run(
    result=None
)
 session View source
@contextlib.contextmanager
session(
    graph=None, config=None, use_gpu=False, force_gpu=False
)
 A context manager for a TensorFlow Session for use in executing tests. Note that this will set this session and the graph as global defaults. Use the use_gpu and force_gpu options to control where ops are run. If force_gpu is True, all ops are pinned to /device:GPU:0. Otherwise, if use_gpu is True, TensorFlow tries to run as many ops on the GPU as possible. If both force_gpu anduse_gpu` are False, all ops are pinned to the CPU. Example: class MyOperatorTest(test_util.TensorFlowTestCase):
  def testMyOperator(self):
    with self.session(use_gpu=True):
      valid_input = [1.0, 2.0, 3.0, 4.0, 5.0]
      result = MyOperator(valid_input).eval()
      self.assertEqual(result, [1.0, 2.0, 3.0, 5.0, 8.0]
      invalid_input = [-1.0, 2.0, 7.0]
      with self.assertRaisesOpError("negative input not supported"):
        MyOperator(invalid_input).eval()

 Args
  graph   Optional graph to use during the returned session.
  config   An optional config_pb2.ConfigProto to use to configure the session.
  use_gpu   If True, attempt to run as many ops as possible on GPU.
  force_gpu   If True, pin all ops to /device:GPU:0.

 Yields   A Session object that should be used as a context manager to surround the graph building and execution code in a test case.
 setUp View source
setUp()
 Hook method for setting up the test fixture before exercising it. setUpClass
@classmethod
setUpClass()
 Hook method for setting up class fixture before running tests in the class. shortDescription
shortDescription()
 Formats both the test method name and the first line of its docstring. If no docstring is given, only returns the method name. This method overrides unittest.TestCase.shortDescription(), which only returns the first line of the docstring, obscuring the name of the test upon failure.

 Returns
  desc   A short description of a test method.    skipTest
skipTest(
    reason
)
 Skip this test. subTest
@contextlib.contextmanager
subTest(
    msg=_subtest_msg_sentinel, **params
)
 Return a context manager that will return the enclosed block of code in a subtest identified by the optional message and keyword parameters. A failure in the subtest marks the test case as failed but resumes execution at the end of the enclosed block, allowing further test code to be executed. tearDown View source
tearDown()
 Hook method for deconstructing the test fixture after testing it. tearDownClass
@classmethod
tearDownClass()
 Hook method for deconstructing the class fixture after running all tests in the class. test_session View source
@contextlib.contextmanager
test_session(
    graph=None, config=None, use_gpu=False, force_gpu=False
)
 Use cached_session instead. (deprecated) Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use self.session() or self.cached_session() instead. __call__
__call__(
    *args, **kwds
)
 Call self as a function. __eq__
__eq__(
    other
)
 Return self==value.

 Class Variables
  longMessage   True
  maxDiff   1600
  tempfile_cleanup


tf.test.TestCase.failureException Assertion failed.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.test.TestCase.failureException
tf.test.TestCase.failureException(
    *args, **kwargs
)


tf.tile Constructs a tensor by tiling a given tensor.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.manip.tile, tf.compat.v1.tile
tf.tile(
    input, multiples, name=None
)
 This operation creates a new tensor by replicating input multiples times. The output tensor's i'th dimension has input.dims(i) * multiples[i] elements, and the values of input are replicated multiples[i] times along the 'i'th dimension. For example, tiling [a b c d] by [2] produces [a b c d a b c d].
a = tf.constant([[1,2,3],[4,5,6]], tf.int32)
b = tf.constant([1,2], tf.int32)
tf.tile(a, b)
<tf.Tensor: shape=(2, 6), dtype=int32, numpy=
array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]], dtype=int32)>
c = tf.constant([2,1], tf.int32)
tf.tile(a, c)
<tf.Tensor: shape=(4, 3), dtype=int32, numpy=
array([[1, 2, 3],
       [4, 5, 6],
       [1, 2, 3],
       [4, 5, 6]], dtype=int32)>
d = tf.constant([2,2], tf.int32)
tf.tile(a, d)
<tf.Tensor: shape=(4, 6), dtype=int32, numpy=
array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6],
       [1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]], dtype=int32)>

 Args
  input   A Tensor. 1-D or higher.
  multiples   A Tensor. Must be one of the following types: int32, int64. 1-D. Length must be the same as the number of dimensions in input
  name   A name for the operation (optional).

 Returns   A Tensor. Has the same type as input.


tf.timestamp Provides the time since epoch in seconds.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.timestamp
tf.timestamp(
    name=None
)
 Returns the timestamp as a float64 for seconds since the Unix epoch.
Note: the timestamp is computed when the op is executed, not when it is added to the graph.

 Args
  name   A name for the operation (optional).

 Returns   A Tensor of type float64.


Module: tf.tpu Ops related to Tensor Processing Units. Modules experimental module: Public API for tf.tpu.experimental namespace.


Module: tf.tpu.experimental Public API for tf.tpu.experimental namespace. Modules embedding module: Public API for tf.tpu.experimental.embedding namespace. Classes class DeviceAssignment: Mapping from logical cores in a computation to the physical TPU topology. class TPUSystemMetadata: Describes some metadata about the TPU system. class Topology: Describes a set of TPU devices. Functions initialize_tpu_system(...): Initialize the TPU devices. shutdown_tpu_system(...): Shuts down the TPU devices.


tf.tpu.experimental.DeviceAssignment     View source on GitHub    Mapping from logical cores in a computation to the physical TPU topology.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tpu.experimental.DeviceAssignment
tf.tpu.experimental.DeviceAssignment(
    topology, core_assignment
)
 Prefer to use the DeviceAssignment.build() helper to construct a DeviceAssignment; it is easier if less flexible than constructing a DeviceAssignment directly.

 Args
  topology   A Topology object that describes the physical TPU topology.
  core_assignment   A logical to physical core mapping, represented as a rank 3 numpy array. See the description of the core_assignment property for more details.

 Raises
  ValueError   If topology is not Topology object.
  ValueError   If core_assignment is not a rank 3 numpy array.

 Attributes
  core_assignment   The logical to physical core mapping.
  num_cores_per_replica   The number of cores per replica.
  num_replicas   The number of replicas of the computation.
  topology   A Topology that describes the TPU topology.    Methods build View source
@staticmethod
build(
    topology, computation_shape=None, computation_stride=None, num_replicas=1
)
 coordinates View source
coordinates(
    replica, logical_core
)
 Returns the physical topology coordinates of a logical core. host_device View source
host_device(
    replica=0, logical_core=0, job=None
)
 Returns the CPU device attached to a logical core. lookup_replicas View source
lookup_replicas(
    task_id, logical_core
)
 Lookup replica ids by task number and logical core.

 Args
  task_id   TensorFlow task number.
  logical_core   An integer, identifying a logical core.

 Returns   A sorted list of the replicas that are attached to that task and logical_core.

 Raises
  ValueError   If no replica exists in the task which contains the logical core.    tpu_device View source
tpu_device(
    replica=0, logical_core=0, job=None
)
 Returns the name of the TPU device assigned to a logical core. tpu_ordinal View source
tpu_ordinal(
    replica=0, logical_core=0
)
 Returns the ordinal of the TPU device assigned to a logical core.


Module: tf.tpu.experimental.embedding Public API for tf.tpu.experimental.embedding namespace. Classes class Adagrad: Optimization parameters for Adagrad with TPU embeddings. class Adam: Optimization parameters for Adam with TPU embeddings. class FeatureConfig: Configuration data for one embedding feature. class SGD: Optimization parameters for stochastic gradient descent for TPU embeddings. class TPUEmbedding: The TPUEmbedding mid level API. class TableConfig: Configuration data for one embedding table. Functions serving_embedding_lookup(...): Apply standard lookup ops with tf.tpu.experimental.embedding configs.


tf.tpu.experimental.embedding.Adagrad Optimization parameters for Adagrad with TPU embeddings.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tpu.experimental.embedding.Adagrad
tf.tpu.experimental.embedding.Adagrad(
    learning_rate: float = 0.001,
    initial_accumulator_value: float = 0.1,
    use_gradient_accumulation: bool = True,
    clip_weight_min: Optional[float] = None,
    clip_weight_max: Optional[float] = None,
    weight_decay_factor: Optional[float] = None,
    multiply_weight_decay_factor_by_learning_rate: bool = None,
    slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None,
    clipvalue: Optional[ClipValueType] = None
)
 Pass this to tf.tpu.experimental.embedding.TPUEmbedding via the optimizer argument to set the global optimizer and its parameters: embedding = tf.tpu.experimental.embedding.TPUEmbedding(
    ...
    optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))
 This can also be used in a tf.tpu.experimental.embedding.TableConfig as the optimizer parameter to set a table specific optimizer. This will override the optimizer and parameters for global embedding optimizer defined above: table_one = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...,
    optimizer=tf.tpu.experimental.embedding.Adagrad(0.2))
table_two = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...)

feature_config = (
    tf.tpu.experimental.embedding.FeatureConfig(
        table=table_one),
    tf.tpu.experimental.embedding.FeatureConfig(
        table=table_two))

embedding = tf.tpu.experimental.embedding.TPUEmbedding(
    feature_config=feature_config,
    batch_size=...
    optimizer=tf.tpu.experimental.embedding.Adagrad(0.1))
 In the above example, the first feature will be looked up in a table that has a learning rate of 0.2 while the second feature will be looked up in a table that has a learning rate of 0.1. See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a complete description of these parameters and their impacts on the optimizer algorithm.

 Args
  learning_rate   The learning rate. It should be a floating point value or a callable taking no arguments for a dynamic learning rate.
  initial_accumulator_value   initial accumulator for Adagrad.
  use_gradient_accumulation   setting this to False makes embedding gradients calculation less accurate but faster.
  clip_weight_min   the minimum value to clip by; None means -infinity.
  clip_weight_max   the maximum value to clip by; None means +infinity.
  weight_decay_factor   amount of weight decay to apply; None means that the weights are not decayed.
  multiply_weight_decay_factor_by_learning_rate   if true, weight_decay_factor is multiplied by the current learning rate.
  slot_variable_creation_fn   If you wish do directly control the creation of the slot variables, set this to a callable taking three parameters: a table variable, a list of slot names to create for it, and a list of initializers. This function should return a dict with the slot names as keys and the created variables as values with types matching the table variable. When set to None (the default), uses the built-in variable creation.
  clipvalue   Controls clipping of the gradient. Set to either a single positive scalar value to get clipping or a tuple of scalar values (min, max) to set a separate maximum or minimum. If one of the two entries is None, then there will be no clipping that direction.


tf.tpu.experimental.embedding.Adam Optimization parameters for Adam with TPU embeddings.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tpu.experimental.embedding.Adam
tf.tpu.experimental.embedding.Adam(
    learning_rate: Union[float, Callable[[], float]] = 0.001,
    beta_1: float = 0.9,
    beta_2: float = 0.999,
    epsilon: float = 1e-07,
    lazy_adam: bool = True,
    sum_inside_sqrt: bool = True,
    use_gradient_accumulation: bool = True,
    clip_weight_min: Optional[float] = None,
    clip_weight_max: Optional[float] = None,
    weight_decay_factor: Optional[float] = None,
    multiply_weight_decay_factor_by_learning_rate: bool = None,
    slot_variable_creation_fn: Optional[SlotVarCreationFnType] = None,
    clipvalue: Optional[ClipValueType] = None
)
 Pass this to tf.tpu.experimental.embedding.TPUEmbedding via the optimizer argument to set the global optimizer and its parameters:
Note: By default this optimizer is lazy, i.e. it will not apply the gradient update of zero to rows that were not looked up. You can change this behavior by setting lazy_adam to False.

embedding = tf.tpu.experimental.embedding.TPUEmbedding(
    ...
    optimizer=tf.tpu.experimental.embedding.Adam(0.1))
 This can also be used in a tf.tpu.experimental.embedding.TableConfig as the optimizer parameter to set a table specific optimizer. This will override the optimizer and parameters for global embedding optimizer defined above: table_one = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...,
    optimizer=tf.tpu.experimental.embedding.Adam(0.2))
table_two = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...)

feature_config = (
    tf.tpu.experimental.embedding.FeatureConfig(
        table=table_one),
    tf.tpu.experimental.embedding.FeatureConfig(
        table=table_two))

embedding = tf.tpu.experimental.embedding.TPUEmbedding(
    feature_config=feature_config,
    batch_size=...
    optimizer=tf.tpu.experimental.embedding.Adam(0.1))
 In the above example, the first feature will be looked up in a table that has a learning rate of 0.2 while the second feature will be looked up in a table that has a learning rate of 0.1. See 'tensorflow/core/protobuf/tpu/optimization_parameters.proto' for a complete description of these parameters and their impacts on the optimizer algorithm.

 Args
  learning_rate   The learning rate. It should be a floating point value or a callable taking no arguments for a dynamic learning rate.
  beta_1   A float value. The exponential decay rate for the 1st moment estimates.
  beta_2   A float value. The exponential decay rate for the 2nd moment estimates.
  epsilon   A small constant for numerical stability.
  lazy_adam   Use lazy Adam instead of Adam. Lazy Adam trains faster.
  sum_inside_sqrt   When this is true, the Adam update formula is changed from m / (sqrt(v) + epsilon) to m / sqrt(v + epsilon**2). This option improves the performance of TPU training and is not expected to harm model quality.
  use_gradient_accumulation   Setting this to False makes embedding gradients calculation less accurate but faster.
  clip_weight_min   the minimum value to clip by; None means -infinity.
  clip_weight_max   the maximum value to clip by; None means +infinity.
  weight_decay_factor   amount of weight decay to apply; None means that the weights are not decayed.
  multiply_weight_decay_factor_by_learning_rate   if true, weight_decay_factor is multiplied by the current learning rate.
  slot_variable_creation_fn   If you wish do directly control the creation of the slot variables, set this to a callable taking three parameters: a table variable, a list of slot names to create for it, and a list of initializers. This function should return a dict with the slot names as keys and the created variables as values with types matching the table variable. When set to None (the default), uses the built-in variable creation.
  clipvalue   Controls clipping of the gradient. Set to either a single positive scalar value to get clipping or a tiple of scalar values (min, max) to set a separate maximum or minimum. If one of the two entries is None, then there will be no clipping that direction.


tf.tpu.experimental.embedding.FeatureConfig Configuration data for one embedding feature.  View aliases  Compat aliases for migration
See Migration guide for more details. tf.compat.v1.tpu.experimental.embedding.FeatureConfig
tf.tpu.experimental.embedding.FeatureConfig(
    table: tf.tpu.experimental.embedding.TableConfig,
    max_sequence_length: int = 0,
    name: Optional[Text] = None
)
 This class holds the configuration data for a single embedding feature. The main use is to assign features to tf.tpu.experimental.embedding.TableConfigs via the table parameter: table_config_one = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...)
table_config_two = tf.tpu.experimental.embedding.TableConfig(
    vocabulary_size=...,
    dim=...)
feature_config = {
    'feature_one': tf.tpu.experimental.embedding.FeatureConfig(
        table=table_config_one),
    'feature_two': tf.tpu.experimental.embedding.FeatureConfig(
        table=table_config_one),
    'feature_three': tf.tpu.experimental.embedding.FeatureConfig(
        table=table_config_two)}
embedding = tf.tpu.experimental.embedding.TPUEmbedding(
    feature_config=feature_config,
    batch_size=...
    optimizer=tf.tpu.experimental.embedding.Adam(0.1))
 The above configuration has 2 tables, and three features. The first two features will be looked up in the first table and the third feature will be looked up in the second table. When feeding features into embedding.enqueue they can be tf.Tensors, tf.SparseTensors or tf.RaggedTensors. When the argument max_sequence_length is 0, the default, you should expect a output of embedding.dequeue for this feature of shape (batch_size, dim). If max_sequence_length is greater than 0, the feature is embedded as a sequence and padded up to the given length. The shape of the output for this feature will be (batch_size, max_sequence_length, dim).

 Args
  table   An instance of tf.tpu.experimental.embedding.TableConfig, describing the table in which this feature should be looked up.
  max_sequence_length   If positive, the feature is a sequence feature with the corresponding maximum sequence length. If the sequence is longer than this, it will be truncated. If 0, the feature is not a sequence feature.
  name   An optional name for the feature, useful for debugging.

 Raises
  ValueError   if table is not an instance of tf.tpu.experimental.embedding.TableConfig.
  ValueError   if max_sequence_length not an integer or is negative.