Salva la data! Google I / O ritorna dal 18 al 20 maggio Registrati ora


A tensor is a multidimensional array of elements represented by a

tf.Tensor object. All elements are of a single known data type.

When writing a TensorFlow program, the main object that is manipulated and passed around is the tf.Tensor.

A tf.Tensor has the following properties:

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

TensorFlow supports eager execution and graph execution. In eager execution, operations are evaluated immediately. In graph execution, a computational graph is constructed for later evaluation.

TensorFlow defaults to eager execution. In the example below, the matrix multiplication 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)
[[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:

<class '...ops.EagerTensor'>
  [[1. 3.]
   [3. 7.]]

In TensorFlow, tf.functions are a common way to define graph execution.

A Tensor's shape (that is, the rank of the Tensor and the size of each dimension) may not always be fully known. In tf.function definitions, the shape may only be 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.

A number of specialized tensors are available: see tf.Variable, tf.constant, tf.placeholder, tf.sparse.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 a tf.TensorShape that represents the shape of this tensor.

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

tf.Tensor.shape is equivalent to tf.Tensor.get_shape().

In a tf.function or when building a model using tf.keras.Input, they return the build-time shape of the tensor, which may be partially unknown.

A tf.TensorShape is not a tensor. Use tf.shape(t) to get a tensor containing the shape, calculated at runtime.

See tf.Tensor.get_shape(), and tf.TensorShape for details and examples.

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



View source

Returns a list of Operations that consume this tensor.

A list of Operations.


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.

feed_dict A dictionary that maps Tensor objects to feed values. See 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.

A numpy array corresponding to the value of this tensor.


View source



View source

Returns a tf.TensorShape that represents the shape of this tensor.

In eager execution the shape is always fully-known.

a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
(2, 3)

tf.Tensor.get_shape() is equivalent to tf.Tensor.shape.

When executing in a tf.function or building a model using tf.keras.Input, Tensor.shape may return a partial shape (including None for unknown dimensions). See tf.TensorShape for more details.

inputs = tf.keras.Input(shape = [10])
# Unknown batch size
(None, 10)

The shape is computed using shape inference functions that are registered for each tf.Operation.

The returned tf.TensorShape is determined at build time, without executing the underlying kernel. It is not a tf.Tensor. If you need a shape tensor, either convert the tf.TensorShape to a tf.constant, or use the tf.shape(tensor) function, which returns the tensor's shape at execution time.

This is useful for debugging and providing early errors. For example, when tracing a tf.function, no ops are being executed, shapes may be unknown (See the Concrete Functions Guide for details).

def my_matmul(a, b):
  result = a@b
  # the `print` executes during tracing.
  print("Result shape: ", result.shape)
  return result

The shape inference functions propagate shapes to the extent possible:

f = my_matmul.get_concrete_function(
Result shape: (None, 5)

Tracing may fail if a shape missmatch can be detected:

cf = my_matmul.get_concrete_function(
Traceback (most recent call last):

ValueError: Dimensions must be equal, but are 3 and 4 for 'matmul' (op:
'MatMul') with input shapes: [?,3], [4,5].

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

def my_fun(a):
  a = tf.ensure_shape(a, [5, 5])
  # the `print` executes during tracing.
  print("Result shape: ", a.shape)
  return a
cf = my_fun.get_concrete_function(
  tf.TensorSpec([None, None]))
Result shape: (5, 5)

A tf.TensorShape representing the shape of this tensor.


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
tensor_dict = {x.ref(): 'five', y.ref(): 'ten', z.ref(): 'ten'}

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

x = tf.constant(5)