What is a Tensor?
A tensor is a container for numbers, like a NumPy array. It is the basic data type of TensorFlow, and it is where the name comes from. Tensors can have any number of dimensions.
| Name | Dimensions | Example |
| Scalar | 0D | 5 |
| Vector | 1D | [1, 2, 3] |
| Matrix | 2D | [[1, 2], [3, 4]] |
| 3D tensor | 3D | A batch of grayscale images |
| 4D tensor | 4D | A batch of color images |
Creating Tensors
python
import tensorflow as tf
scalar = tf.constant(5)
vector = tf.constant([1.0, 2.0, 3.0])
matrix = tf.constant([[1, 2], [3, 4]])
print(scalar.shape) # ()
print(vector.shape) # (3,)
print(matrix.shape) # (2, 2)
print(matrix.dtype) # <dtype: 'int32'>
Special Tensors
python
zeros = tf.zeros((2, 3))
ones = tf.ones((2, 3))
rand = tf.random.normal((2, 3)) # normal distribution
rng = tf.range(0, 10, 2) # [0 2 4 6 8]
Data Types
The type of numbers matters. Deep learning mostly uses float32. You can convert with tf.cast.
python
x = tf.constant([1, 2, 3])
y = tf.cast(x, tf.float32)
print(y) # tf.Tensor([1. 2. 3.], shape=(3,), dtype=float32)
Math Operations
python
a = tf.constant([[1.0, 2.0], [3.0, 4.0]])
b = tf.constant([[5.0, 6.0], [7.0, 8.0]])
print(a + b) # element-wise addition
print(a * b) # element-wise multiplication
print(tf.matmul(a, b)) # matrix multiplication
print(tf.reduce_sum(a)) # 10.0
print(tf.reduce_mean(a)) # 2.5
Careful: a * b multiplies matching elements. tf.matmul(a, b) does real matrix multiplication. Neural network layers use matrix multiplication.
Reshape and Index
python
t = tf.range(12)
t = tf.reshape(t, (3, 4))
print(t[0]) # first row
print(t[:, 1]) # second colum
tf.Variable: Values That Change
A tf.constant cannot change. A tf.Variable can, which is exactly what we need for the weights of a neural network that are updated during training.
python
w = tf.Variable([0.5, -0.3])
w.assign([0.7, -0.1])
w.assign_add([0.1, 0.1])
print(w.numpy()) # [0.8 0. ]
Tensors and NumPy
python
import numpy as np
t = tf.constant([1, 2, 3])
n = t.numpy() # tensor -> NumPy
t2 = tf.convert_to_tensor(np.array([4, 5, 6])) # NumPy -> tensor
Result
Both libraries share data easily, so you can mix them in the same program.
Conclusion
Tensors are the language of TensorFlow. You do not need to build everything by hand because Keras layers handle tensors for you, but understanding shapes and types will save you from many errors.
Quick Summary: Tensors are multi-dimensional arrays. Use tf.constant for fixed values, tf.Variable for weights, and always check shape and dtype.