tf.TensorShape  |  TensorFlow v2.16.1 (original) (raw)

Represents the shape of a Tensor.

Inherits From: TraceType

View aliases

Compat aliases for migration

SeeMigration guide for more details.

tf.compat.v1.TensorShape

tf.TensorShape(
    dims
)

Used in the notebooks

Used in the guide Used in the tutorials
TensorFlow 1.x vs TensorFlow 2 - Behaviors and APIs DTensor concepts Working with RNNs Distributed Input Tensorflow datasets from MongoDB collections

t = tf.constant([[1,2,3],[4,5,6]]) t.shape TensorShape([2, 3])

TensorShape is the static shape representation of a Tensor. During eager execution a Tensor always has a fully specified shape but when tracing a tf.function it may be one of the following:

During function tracing t.shape will return a TensorShape object representing the shape of Tensor as it is known during tracing. This static representation will be partially defined in cases where the exact shape depends on the values within the tensors. To get the_dynamic_ representation, please use tf.shape(t)which will return Tensor representing the fully defined shape of t. This way, you can express logic that manipulates the shapes of tensors by building other tensors that depend on the dynamic shape of t.

For example, this function prints the TensorShape' (t.shape), when you trace the function, and returns a tensor <a href="../tf/shape"><code>tf.shape(t)</code></a> for given inputt`:

@tf.function def get_dynamic_shape(t): print("tracing...") print(f"static shape is {t.shape}") return tf.shape(t)

Just calling the function traces it with a fully-specified static shape:

result = get_dynamic_shape(tf.constant([[1, 1, 1], [0, 0, 0]])) tracing... static shape is (2, 3) result.numpy() array([2, 3], dtype=int32)

But tf.function can also trace the function with a partially specified (or even unspecified) shape:

cf1 = get_dynamic_shape.get_concrete_function(tf.TensorSpec( shape=[None, 2])) tracing... static shape is (None, 2) cf1(tf.constant([[1., 0],[1, 0],[1, 0]])).numpy() array([3, 2], dtype=int32)

cf2 = get_dynamic_shape.get_concrete_function(tf.TensorSpec(shape=None)) tracing... static shape is <unknown> cf2(tf.constant([[[[[1., 0]]]]])).numpy() array([1, 1, 1, 1, 2], dtype=int32)

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 functionsfor details of shape functions and how to register them. Alternatively, you may set the shape explicitly using tf.Tensor.ensure_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 bothself 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.

Args
other Another TensorShape.
Returns
A TensorShape whose dimensions are the concatenation of the dimensions in self and other.

experimental_as_proto

View source

experimental_as_proto() -> tensor_shape_pb2.TensorShapeProto

Returns a proto representation of the TensorShape instance.

experimental_from_proto

View source

@classmethod experimental_from_proto( proto: tensor_shape_pb2.TensorShapeProto ) -> 'TensorShape'

Returns a TensorShape instance based on the serialized proto.

experimental_type_proto

View source

@classmethod experimental_type_proto() -> Type[tensor_shape_pb2.TensorShapeProto]

Returns the type of proto associated with TensorShape serialization.

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:

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.

is_subtype_of

View source

is_subtype_of(
    other: tf.types.experimental.TraceType
) -> bool

Returns True iff self is subtype of other.

Shape A is a subtype of shape B if shape B can successfully represent it:

The subtyping relation is reflexive and transitive, but not symmetric.

Some examples:

Args
other Another TensorShape.
Returns
True iff self is subtype of other.

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 element-wise, according to the rules below:

Dimension(n).merge_with(Dimension(None)) == Dimension(n)
Dimension(None).merge_with(Dimension(n)) == Dimension(n)
Dimension(None).merge_with(Dimension(None)) == Dimension(None)
# raises ValueError for n != m
Dimension(n).merge_with(Dimension(m))

ts = tf.TensorShape([1,2]) ot1 = tf.TensorShape([1,2]) ts.merge_with(ot).as_list() [1,2]

ot2 = tf.TensorShape([1,None]) ts.merge_with(ot2).as_list() [1,2]

ot3 = tf.TensorShape([None, None]) ot3.merge_with(ot2).as_list() [1, None]

Args
other Another TensorShape.
Returns
A TensorShape containing the combined information of self andother.
Raises
ValueError If self and other are not compatible.

most_specific_common_supertype

View source

most_specific_common_supertype(
    others: Sequence[tf.types.experimental.TraceType]
) -> Optional['TensorShape']

Returns the most specific supertype TensorShape of self and others.

Args
others Sequence of TensorShape.
Returns
A TensorShape which is the most specific supertype shape of selfand others. None if it does not exist.

most_specific_compatible_shape

View source

most_specific_compatible_shape(
    other
) -> 'TensorShape'

Returns the most specific TensorShape compatible with self and other.

Args
other Another TensorShape.
Returns
A TensorShape which is the most specific compatible shape of selfand 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 givenrank.

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 givenrank.

__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.

It first tries to convert other to TensorShape. TypeError is thrown when the conversion fails. Otherwise, it compares each element in the TensorShape dimensions.

>>> t_a = tf.TensorShape([1,2])
>>> a = [1, 2]
>>> t_b = tf.TensorShape([1,2])
>>> t_c = tf.TensorShape([1,2,3])
>>> t_a.__eq__(a)
True
>>> t_a.__eq__(t_b)
True
>>> t_a.__eq__(t_c)
False
>>> p_a = tf.TensorShape([1,None])
>>> p_b = tf.TensorShape([1,None])
>>> p_c = tf.TensorShape([2,None])
>>> p_a.__eq__(p_b)
True
>>> t_a.__eq__(p_a)
False
>>> p_a.__eq__(p_c)
False
>>> unk_a = tf.TensorShape(None)
>>> unk_b = tf.TensorShape(None)
>>> unk_a.__eq__(unk_b)
True
>>> unk_a.__eq__(t_a)
False
Args
other A TensorShape or type that can be converted to TensorShape.
Returns
True if the dimensions are all equal.
Raises
TypeError if other can not be converted to TensorShape.

__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.

__nonzero__

View source

__nonzero__()

Returns True if this shape contains non-zero information.

__radd__

View source

__radd__(
    other
)