https://tensorflow.google.cn/guide/tensor
Introduction to Tensors
Tensors
aremulti-dimensional arrays with a uniform type
(called adtype
).tf.dtypes
included all supported dtypes.
If you're familiar withNumPy
, tensors are (kind of) likenp.arrays
.All tensors are immutable
andonly create a new one
, just like Python numbers and strings: you can never update the contents of a tensor.
About shapes
Tensors have shapes. Some vocabulary:
Shape
: The length (number of elements) of each of the axes of a tensor.Rank
: Number of tensor axes:- A scalar has rank 0,
- a vector has rank 1,
- a matrix is rank 2.
Axis or Dimension
: A particular dimension of a tensor.Size
: The total number of items in the tensor, the product of the shape vector's elements.- The base tf.Tensor class
requires tensors to be "rectangular"
--- that is,along each axis, every element is the same size
.
However, there are specialized types of tensors that can handle different shapes:Ragged tensors
(see RaggedTensor below)Sparse tensors
(see SparseTensor below)
You can do math on tensors, including addition, element-wise multiplication, and matrix multiplication.
Note: Although you may see reference to a "tensor of two dimensions", a rank-2 tensor does not usually describe a 2D space.
Tensors and tf.TensorShape
objects have convenient properties for accessing these:
a = tf.constant([ [1, 2], [3, 4] ])
b = tf.constant([ [1, 1], [1, 1] ]) # Could have also said `tf.ones([2,2], dtype=tf.int32)`
print(tf.add(a, b), "\n")
# print(a + b, "\n")
# element-wise addition
print(tf.multiply(a, b), "\n")
# print(a
*
b, "\n")
# element-wise multiplication
print(tf.matmul(a, b), "\n")
# print(a
@
b, "\n")
# matrix multiplication