Learn TensorFlow Β· 2/11

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:

  1. Data Type (dtype): (e.g., float, int).
  2. Shape: The dimensions of the grid.

The Hierarchy of Dimensions (Rank)

Let's learn the "alphabet" of Tensors before writing words.

  1. Scalar (Rank 0): A single number.
    • Example: 7 (Maybe the predicted price of a stock).
  2. Vector (Rank 1): A list of numbers.
    • Example: [7, 5, 2] (Coordinates in a 3D space).
  3. Matrix (Rank 2): A table of numbers.
    • Example: A grayscale image (height x width).
  4. 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.

python
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.

python
# 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.

python
# 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 using tf.data.

python
# 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.

python
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 (@ or tf.matmul): The "Row by Column" rule from high school algebra.
python
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.

python
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.

python
# 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.

python
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

  1. Tensors are just n-dimensional arrays optimized for GPU math.
  2. Use tf.constant by default. Use tf.variable only when you need to update the value (like model weights).
  3. Shapes are everything. 90% of your errors in Deep Learning will be shape mismatches. Always check .shape.
  4. Matrix Multiplication (tf.matmul) is not the same as Element-wise multiplication (*).
  5. float32 is the standard data type for Deep Learning. It's precise enough for learning but faster than float64.

πŸ“š References & Further Reading


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:

  1. Import the tensorflow library and alias it as tf.
  2. You are provided with input_data, a Python list representing a batch of two 3x3 images. Convert this list into an immutable TensorFlow tensor named inputs with a dtype of tf.float32.
  3. The shape of the inputs tensor is not suitable for multiplication with a standard dense layer's weight matrix. Reshape the inputs tensor into a 2D tensor where each row represents a flattened image. Name this new tensor inputs_reshaped.
  4. You are given weights_data and bias_data. Convert these lists into mutable TensorFlow tensors named weights and biases, respectively. Both must have a dtype of tf.float32.
  5. Perform the forward pass calculation: a matrix multiplication between inputs_reshaped and weights, followed by the element-wise addition of the biases. Store the result in a tensor named output.
  6. 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 output tensor. Store this final result in a tensor named final_output.

Expected result

Your final code should define the following five TensorFlow objects with the specified properties:

  • inputs: A tf.Tensor created with tf.constant, having a shape of (2, 3, 3) and a dtype of tf.float32.
  • inputs_reshaped: A tf.Tensor created by reshaping inputs. It must have a shape of (2, 9).
  • weights: A tf.Variable with a shape of (9, 4) and a dtype of tf.float32.
  • biases: A tf.Variable with a shape of (4,) and a dtype of tf.float32.
  • output: A tf.Tensor resulting from the operation (inputs_reshaped @ weights) + biases. It must have a shape of (2, 4).
  • final_output: A tf.Tensor created by expanding the dimensions of output. It must have a final shape of (2, 4, 1).
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.