Core Concepts: Working with Tensors
7 min read
Course: TensorFlow
Module: Core Concepts
Estimated Time: 20 Minutes
π Welcome back, Developer!
So, you've decided to tackle Deep Learning. You might have heard the word "Tensor" thrown around like it's some sort of intergalactic currency or a muscle in your forearm.
In reality, a Tensor is just a container for data. If you know NumPy, youβre already 80% of the way there. If you don't, no worries! We are going to build this up from the ground, pixel by pixel.
Why does this matter?
Imagine trying to build a skyscraper (a Neural Network) using mud and sticks (standard Python lists). It might work, but itβll be slow, wobbly, and collapse if you look at it wrong. Tensors are the steel beams. They allow TensorFlow to perform math on billions of numbers simultaneously using GPUs (Graphics Processing Units) or TPUs (Tensor Processing Units).
Letβs get your hands dirty. π οΈ
1. Understanding Tensors: The Fundamental Building Blocks
π The Problem
Computers are binary. The real world is not. We have images (pixels), audio (frequencies), and text. We need a standardized mathematical structure to feed this chaotic real-world data into our algorithms so they can perform calculations efficiently. Standard lists ([1, 2, 3]) are too slow and lack the structural strictness required for linear algebra.
β The Solution: The Tensor
A Tensor is a typed, multi-dimensional array. It is the fundamental data type used in TensorFlow.
Do not think of a Tensor as a magic box. Think of it strictly as a grid of numbers that has:
- Data Type (
dtype): (e.g., float, int). - Shape: The dimensions of the grid.
The Hierarchy of Dimensions (Rank)
Let's learn the "alphabet" of Tensors before writing words.
- Scalar (Rank 0): A single number.
- Example:
7(Maybe the predicted price of a stock).
- Example:
- Vector (Rank 1): A list of numbers.
- Example:
[7, 5, 2](Coordinates in a 3D space).
- Example:
- Matrix (Rank 2): A table of numbers.
- Example: A grayscale image (height x width).
- Tensor (Rank 3+): A 3D (or higher) array.
- Example: A color image (height x width x 3 color channels).
π‘ Fun Fact: The name "TensorFlow" literally comes from how the data (Tensors) flows through the mathematical operations (the Graph). Creative, right?
2. Creating and Initializing Tensors
π The Problem
We need to get data into TensorFlow's format. You cannot simply pass a raw JPEG file or a Python integer to a GPU for training. It needs to be wrapped in a TensorFlow object.
β
The Solution: tf.constant and tf.Variable
First, let's import the library.
import tensorflow as tf
import numpy as np
# Check your version - Industry standard is currently 2.x
print(f"TensorFlow Version: {tf.__version__}")A. The Immutable Tensor: tf.constant
This is the most common way to create a tensor. "Immutable" means once you create it, you cannot change the values inside it. This safety is preferred for input data.
# 1. Creating a Scalar (Rank 0)
scalar = tf.constant(7)
print(scalar)
# Output: tf.Tensor(7, shape=(), dtype=int32)
# 2. Creating a Vector (Rank 1)
vector = tf.constant([10, 10])
print(vector)
# Output: shape=(2,)
# 3. Creating a Matrix (Rank 2)
matrix = tf.constant([[10, 7],
[7, 10]])
print(matrix)
# Output: shape=(2, 2)B. The Mutable Tensor: tf.Variable
In Deep Learning, a network needs to learn. This means it needs to update its internal numbers (weights and biases) to get better at predicting. Since tf.constant can't be changed, we use tf.Variable.
# A variable that we can update later
trainable_variable = tf.Variable([10, 7])
# Trying to change a value
# trainable_variable[0] = 50 # β This throws an error!
trainable_variable[0].assign(50) # β
This is the correct way
print(trainable_variable)π¨βπ» Industry Insight: In 99% of your daily work, you won't type out tensors manually like
[1, 2, 3]. You will usually convert NumPy arrays to Tensors or load data from files usingtf.data.
# Converting NumPy to Tensor
numpy_arr = np.array([1, 2, 3])
tensor_from_numpy = tf.constant(numpy_arr)3. Basic Tensor Operations and Mathematics
π The Problem
Having data sitting in a Tensor is useless. We need to crunch the numbers to find patterns. We need to add, multiply, and manipulate these grids.
β The Solution: Vectorized Operations
TensorFlow performs operations on the whole tensor at once (element-wise), rather than looping through numbers like standard Python (which is agonizingly slow).
A. Basic Math
You can use standard Python operators (+, -, *, /) or TensorFlow specific methods.
tensor = tf.constant([[10, 7], [3, 4]])
# Addition (Adds 10 to EVERY element)
print(tensor + 10)
# Multiplication (Multiplies EVERY element by 10)
print(tensor * 10)
# Built-in functions (Often faster on GPU)
print(tf.multiply(tensor, 10))B. The Big One: Matrix Multiplication
Pay attention! This is where most beginners crash their code.
There is a massive difference between Element-wise Multiplication and Matrix Multiplication (Dot Product). Deep Learning relies heavily on the Dot Product.
- Element-wise (
*): Multiplies matching slots.[2] * [3] = [6] - Matrix Mult (
@ortf.matmul): The "Row by Column" rule from high school algebra.
t1 = tf.constant([[1, 2],
[3, 4]])
t2 = tf.constant([[5, 6],
[7, 8]])
# 1. Element-wise (The easy one)
print(t1 * t2)
# Result: [[5, 12], [21, 32]]
# 2. Matrix Multiplication (The linear algebra one)
# Rule: Inner dimensions must match! (2x2) @ (2x2) is okay.
print(tf.matmul(t1, t2))
# Result: [[19, 22], [43, 50]]
# Calculation for first cell: (1*5) + (2*7) = 19π Watch out: If you try to multiply a shape
(3, 2)by(3, 2)using matrix multiplication, it will fail. You must transpose one to match the inner dimensions (e.g.,(3, 2) @ (2, 3)).
4. Manipulating Shape, Rank, and Reshaping
π The Problem
Real-world data is messy. You might have a list of 100 images, where each image is 28x28 pixels. Your data shape is (100, 28, 28). But your Neural Network expects a flat vector of size 784 for each image. If the shapes don't match, TensorFlow will throw an error and refuse to run.
β
The Solution: tf.reshape
Reshaping allows you to rearrange the elements of a tensor into a new configuration without changing the data itself.
Getting Information
Before fixing a shape, you need to know what it is.
x = tf.zeros([10, 28, 28, 3]) # Imagine a batch of 10 color images
print("Type:", x.dtype)
print("Shape:", x.shape)
print("Rank (Dimensions):", x.ndim)
print("Total Elements:", tf.size(x))Reshaping
Let's flatten a matrix into a vector.
# Create a rank 2 tensor (3 rows, 2 cols)
tensor_2d = tf.constant([[1, 2],
[3, 4],
[5, 6]])
print(tensor_2d.shape) # (3, 2)
# Reshape to rank 1 (1 row, 6 cols)
reshaped = tf.reshape(tensor_2d, shape=(6))
print(reshaped)
# Output: [1, 2, 3, 4, 5, 6]
# Reshape using -1
# -1 tells TensorFlow: "You figure out this dimension based on the others"
auto_reshaped = tf.reshape(tensor_2d, shape=(2, -1))
print(auto_reshaped.shape)
# Output: (2, 3) -> It figured out 3 because 6 total elements / 2 rows = 3 cols.π§ Simulation: Imagine you have a deck of cards (52 cards).
- Current state: 4 rows (suits) x 13 columns (values).
- Reshape: 2 rows x 26 columns.
- Reshape: 52 rows x 1 column.
It's the same 52 cards, just organized differently on the table. That is
tf.reshape.
Expanding Dimensions
Sometimes a model expects a batch of items, but you only have one item. You need to add a "fake" dimension.
tensor_hw = tf.zeros([200, 200]) # Height, Width
# Add a dimension at the 0-index (axis=0)
tensor_bhw = tf.expand_dims(tensor_hw, axis=0)
print(tensor_bhw.shape)
# Output: (1, 200, 200) -> Now it looks like a "Batch of 1"π§ͺ Summary & Best Practices
- Tensors are just n-dimensional arrays optimized for GPU math.
- Use
tf.constantby default. Usetf.variableonly when you need to update the value (like model weights). - Shapes are everything. 90% of your errors in Deep Learning will be shape mismatches. Always check
.shape. - Matrix Multiplication (
tf.matmul) is not the same as Element-wise multiplication (*). float32is the standard data type for Deep Learning. It's precise enough for learning but faster thanfloat64.
π References & Further Reading
- Official TensorFlow Tensor Guide - The bible of tensors.
- tf.reshape Documentation - For when your shapes don't fit.
- NumPy to TensorFlow - If you are coming from Data Science.
Next Up: Now that we can store and shape our data, how do we actually "learn" from it? Proceed to the next topic to build your first computational graph! π
Challenge
Challenge: Simulate a Neural Network Forward Pass
Your task is to prepare data and execute the primary calculation for a single dense (fully-connected) layer of a neural network. You will be converting raw Python lists into appropriate TensorFlow tensors, manipulating their shapes, and performing the core mathematical operations.
Instructions:
- Import the
tensorflowlibrary and alias it astf. - You are provided with
input_data, a Python list representing a batch of two 3x3 images. Convert this list into an immutable TensorFlow tensor namedinputswith adtypeoftf.float32. - The shape of the
inputstensor is not suitable for multiplication with a standard dense layer's weight matrix. Reshape theinputstensor into a 2D tensor where each row represents a flattened image. Name this new tensorinputs_reshaped. - You are given
weights_dataandbias_data. Convert these lists into mutable TensorFlow tensors namedweightsandbiases, respectively. Both must have adtypeoftf.float32. - Perform the forward pass calculation: a matrix multiplication between
inputs_reshapedandweights, followed by the element-wise addition of thebiases. Store the result in a tensor namedoutput. - Finally, to prepare the data for a subsequent hypothetical layer (like a 1D convolutional layer), add a new dimension of size 1 at the end of the
outputtensor. Store this final result in a tensor namedfinal_output.
Expected result
Your final code should define the following five TensorFlow objects with the specified properties:
inputs: Atf.Tensorcreated withtf.constant, having a shape of(2, 3, 3)and adtypeoftf.float32.inputs_reshaped: Atf.Tensorcreated by reshapinginputs. It must have a shape of(2, 9).weights: Atf.Variablewith a shape of(9, 4)and adtypeoftf.float32.biases: Atf.Variablewith a shape of(4,)and adtypeoftf.float32.output: Atf.Tensorresulting from the operation(inputs_reshaped @ weights) + biases. It must have a shape of(2, 4).final_output: Atf.Tensorcreated by expanding the dimensions ofoutput. It must have a final shape of(2, 4, 1).