Google I/O is a wrap! Catch up on TensorFlow sessions View sessions

tf.Tensor

TensorFlow 1 version View source on GitHub

A tensor represents a rectangular array of data.

When writing a TensorFlow program, the main object you manipulate and pass around is the tf.Tensor. A tf.Tensor object represents a rectangular array of arbitrary dimension, filled with data of a specific data type.

A tf.Tensor has the following properties:

  • a data type (float32, int32, or string, for example)
  • a shape

Each element in the Tensor has the same data type, and the data type is always known.

In eager execution, which is the default mode in TensorFlow, results are calculated immediately.

# Compute some values using a Tensor
c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
print(e)
tf.Tensor(
[[1. 3.]
 [3. 7.]], shape=(2, 2), dtype=float32)

Note that during eager execution, you may discover your Tensors are actually of type EagerTensor. This is an internal detail, but it does give you access to a useful function, numpy:

type(e)
<class '...ops.EagerTensor'>
print(e.numpy())
  [[1. 3.]
   [3. 7.]]

TensorFlow can define computations without immediately executing them, most commonly inside tf.functions, as well as in (legacy) Graph mode. In those cases, the shape (that is, the rank of the Tensor and the size of each dimension) might be only partially known.

Most operations produce tensors of fully-known shapes if the shapes of their inputs are also fully known, but in some cases it's only possible to find the shape of a tensor at execution time.

There are specialized tensors; for these, see tf.Variable, tf.constant, tf.placeholder, tf.SparseTensor, and tf.RaggedTensor.

For more on Tensors, see the guide.

op An Operation. Operation that computes this tensor.
value_index An int. Index of the operation's endpoint that produces this tensor.
dtype A DType. Type of elements stored in this tensor.

TypeError If the op is not an Operation.

device The name of the device on which this tensor will be produced, or None.
dtype The DType of elements in this tensor.
graph The Graph that contains this tensor.
name The string name of this tensor.
op The Operation that produces this tensor as an output.
shape Returns the TensorShape that represents the shape of this tensor.

The shape is computed using shape inference functions that are registered in the Op for each Operation. See tf.TensorShape for more details of what a shape represents.

The inferred shape of a tensor is used to provide shape information without having to execute the underlying kernel. This can be used for debugging and providing early error messages. For example:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.shape) # will be TensorShape([2, 3])
(2, 3)

d = tf.constant([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]]) print(d.shape) (4, 2)


# Raises a ValueError, because `c` and `d` do not have compatible
# inner dimensions.
>>> e = tf.matmul(c, d)
Traceback (most recent call last):
...
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix
size-incompatible: In[0]: [2,3], In[1]: [4,2] [Op:MatMul] name: MatMul/

# This works because we have compatible shapes.
>>> f = tf.matmul(c, d, transpose_a=True, transpose_b=True)
>>> print(f.shape)
(3, 4)

In some cases, the inferred shape may have unknown dimensions. If the caller has additional information about the values of these dimensions, Tensor.set_shape() can be used to augment the inferred shape.

value_index The index of this tensor in the outputs of its Operation.

Methods

consumers

View source

Returns a list of Operations that consume this tensor.

Returns
A list of Operations.

eval

View source

Evaluates this tensor in a Session.

Calling this method will execute all preceding operations that produce the inputs needed for the operation that produces this tensor.

Args
feed_dict A dictionary that maps Tensor objects to feed values. See tf.Session.run for a description of the valid feed values.
session (Optional.) The Session to be used to evaluate this tensor. If none, the default session will be used.

Returns
A numpy array corresponding to the value of this tensor.

experimental_ref

View source

DEPRECATED FUNCTION

get_shape

View source

Alias of tf.Tensor.shape.

ref

View source

Returns a hashable reference object to this Tensor.

The primary use case for this API is to put tensors in a set/dictionary. We can't put tensors in a set/dictionary as tensor.__hash__() is no longer available starting Tensorflow 2.0.

The following will raise an exception starting 2.0

x = tf.constant(5)
y = tf.constant(10)
z = tf.constant(10)
tensor_set = {x, y, z}
Traceback (most recent call last):

TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.
tensor_dict = {x: 'five', y: 'ten'}
Traceback (most recent call last):

TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.

Instead, we can use tensor.ref().

tensor_set = {x.ref(), y.ref(), z.ref()}
x.ref() in tensor_set
True
tensor_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'}
tensor_dict[y.ref()]
'ten'

Also, the reference object provides .deref() function that returns the original Tensor.

x = tf.constant(5)
x.ref().deref()
<tf.Tensor: shape=(), dtype=int32, numpy=5>

set_shape

View source

Updates the shape of this tensor.

This method can be called multiple times, and will merge the given shape with the current shape of this tensor. It can be used to provide additional information about the shape of this tensor that cannot be inferred from the graph alone. For example, this can be used to provide additional information about the shapes of images:

_, image_data = tf.compat.v1.TFRecordReader(...).read(...)
image = tf.image.decode_png(image_data, channels=3)

# The height and width dimensions of `image` are data dependent, and
# cannot be computed without executing the op.
print(image.shape)
==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])

# We know that each image in this dataset is 28 x 28 pixels.
image.set_shape([28, 28, 3])
print(image.shape)
==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])

Args
shape A TensorShape representing the shape of this tensor, a TensorShapeProto, a list, a tuple, or None.

Raises
ValueError If shape is not compatible with the current shape of this tensor.

__abs__

View source

Computes the absolute value of a tensor.

Given a tensor of integer or floating-point values, this operation returns a tensor of the same type, where each element contains the absolute value of the corresponding element in the input.

Given a tensor x of complex numbers, this operation returns a tensor of type float32 or float64 that is the absolute value of each element in x. For a complex number \(a + bj\), its absolute value is computed as \(\sqrt{a^2

  • b^2}\). For example:
x = tf.constant([[-2.25 + 4.75j], [-3.25 + 5.75j]])
tf.abs(x)
<tf.Tensor: shape=(2, 1), dtype=float64, numpy=
array([[5.25594901],
       [6.60492241]])>

Args
x A Tensor or SparseTensor of type float16, float32, float64, int32, int64, complex64 or complex128.
name A name for the operation (optional).

Returns
A Tensor or SparseTensor of the same size, type and sparsity as x, with absolute values. Note, for complex64 or complex128 input, the returned Tensor will be of type float32 or float64, respectively.

If