0
0
TensorFlowml~5 mins

Why tensors are the fundamental data unit in TensorFlow

Choose your learning style9 modes available
Introduction

Tensors are like containers that hold numbers in machine learning. They help computers understand and work with data easily.

When you want to represent images as grids of numbers.
When you need to store and process text data as sequences.
When working with batches of data for training models.
When performing math operations on multi-dimensional data.
When building neural networks that require structured inputs.
Syntax
TensorFlow
tf.constant(value, dtype=None, shape=None)
tf.Variable(initial_value, dtype=None, shape=None)

tf.constant creates a tensor with fixed values.

tf.Variable creates a tensor that can change during training.

Examples
This creates a simple list of numbers as a tensor.
TensorFlow
import tensorflow as tf

# Create a 1D tensor (vector)
tensor_1d = tf.constant([1, 2, 3])
This creates a table of numbers with rows and columns.
TensorFlow
import tensorflow as tf

# Create a 2D tensor (matrix)
tensor_2d = tf.constant([[1, 2], [3, 4]])
This tensor can be updated during model training.
TensorFlow
import tensorflow as tf

# Create a variable tensor that can change
var_tensor = tf.Variable([5, 6, 7])
Sample Model

This example shows a 4D tensor holding two small images. Each image is 2 pixels by 2 pixels with 1 color channel. The shape tells us the dimensions of the data.

TensorFlow
import tensorflow as tf

# Create a 4D tensor representing a batch of 2 images, each 2x2 pixels with 1 color channel
images = tf.constant(
    [
        [[[1], [2]], [[3], [4]]],  # Image 1
        [[[5], [6]], [[7], [8]]]   # Image 2
    ], dtype=tf.float32
)

print("Tensor shape:", images.shape)
print("Tensor values:")
print(images.numpy())
OutputSuccess
Important Notes

Tensors can have any number of dimensions, like scalars (0D), vectors (1D), matrices (2D), or higher.

TensorFlow uses tensors to efficiently perform math on data for machine learning.

Understanding tensors helps you work with data shapes and model inputs correctly.

Summary

Tensors are the main way to store and organize data in machine learning.

They can hold numbers in many dimensions, making them flexible for different data types.

TensorFlow uses tensors to do fast math and build models.