Tensor Basics

Loading concept...

๐Ÿงฑ TensorFlow Tensor Basics: Building Blocks of AI Magic

Imagine you have a magical LEGO set. Each brick can hold a number, and you can stack them in different ways to build amazing things. Thatโ€™s exactly what tensors are in TensorFlow!


๐ŸŒŸ The Big Picture: What Are Tensors?

Think of a tensor like a special container for numbers. Just like how you might organize your toys in different ways:

  • A single toy = one number (scalar)
  • A line of toys = a list of numbers (1D tensor)
  • Toys arranged in a grid = a table of numbers (2D tensor)
  • Toys stacked in a cube = a 3D block of numbers (3D tensor)

TensorFlow is a tool that helps computers do math with these containers super fast! Itโ€™s like having a robot helper that can play with millions of LEGO bricks at once.

graph TD A[๐ŸŽฒ Scalar<br>Just ONE number] --> B[๐Ÿ“ Vector<br>A LINE of numbers] B --> C[๐Ÿ“Š Matrix<br>A TABLE of numbers] C --> D[๐Ÿ“ฆ 3D Tensor<br>A CUBE of numbers] D --> E[๐ŸŒŒ Higher Dimensions<br>Even MORE complex!]

๐ŸŽฏ Tensor Fundamentals

What Makes a Tensor Special?

A tensor has three super important features:

  1. Shape โ€“ How the numbers are arranged (like the size of your LEGO structure)
  2. Data Type โ€“ What kind of numbers it holds (whole numbers? decimals?)
  3. Values โ€“ The actual numbers inside

Simple Example:

import tensorflow as tf

# A simple tensor with 3 numbers
my_tensor = tf.constant([1, 2, 3])
print(my_tensor)
# Output: tf.Tensor([1 2 3],
#         shape=(3,), dtype=int32)

This tells us:

  • Values: [1, 2, 3]
  • Shape: (3,) โ€“ itโ€™s a line with 3 spots
  • Data Type: int32 โ€“ whole numbers

๐Ÿ”ข Tensor Data Types

Just like crayons come in different colors, numbers come in different types!

Common Data Types

Type What It Is Example Use
int32 Whole numbers Counting items: 1, 2, 3
float32 Decimal numbers Prices: 3.99, 10.50
float64 Super precise decimals Science calculations
bool True or False Yes/No questions
string Text Names, words

Example: Different Types in Action

import tensorflow as tf

# Whole numbers (integers)
ages = tf.constant([5, 8, 10],
                   dtype=tf.int32)

# Decimal numbers (floats)
prices = tf.constant([1.50, 2.75],
                     dtype=tf.float32)

# True/False values
answers = tf.constant([True, False])

# Text
names = tf.constant(["Cat", "Dog"])

๐Ÿ’ก Pro Tip: Choosing the Right Type

  • Use float32 for most AI work (good balance of speed and accuracy)
  • Use int32 when counting things
  • Use float64 only when you need extra precision

๐Ÿ“ Tensor Shapes and Ranks

Understanding Shape

Shape tells you how many numbers are in each direction. Think of it like describing a box:

  • Width: how many across
  • Height: how many down
  • Depth: how many layers

Examples:

import tensorflow as tf

# Shape (3,) = 3 items in a line
line = tf.constant([1, 2, 3])

# Shape (2, 3) = 2 rows, 3 columns
table = tf.constant([
    [1, 2, 3],
    [4, 5, 6]
])

# Shape (2, 2, 2) = 2 layers of 2x2
cube = tf.constant([
    [[1, 2], [3, 4]],
    [[5, 6], [7, 8]]
])

Understanding Rank

Rank is simply how many dimensions your tensor has. Itโ€™s like counting how many directions you can move!

Rank Name Shape Example Real World
0 Scalar () Your age: 10
1 Vector (3,) [Red, Green, Blue]
2 Matrix (2, 3) A photo (height ร— width)
3 3D Tensor (2, 3, 4) A video (frames ร— H ร— W)
graph TD A["Rank 0<br>๐ŸŽฒ Single Number<br>Shape: #40;#41;"] B["Rank 1<br>๐Ÿ“ List/Array<br>Shape: #40;n,#41;"] C["Rank 2<br>๐Ÿ“Š Table/Grid<br>Shape: #40;rows, cols#41;"] D["Rank 3<br>๐Ÿ“ฆ Cube/Stack<br>Shape: #40;d, h, w#41;"] A --> B --> C --> D

Getting Shape and Rank:

import tensorflow as tf

my_table = tf.constant([
    [1, 2, 3],
    [4, 5, 6]
])

print(my_table.shape)  # (2, 3)
print(tf.rank(my_table))  # 2

๐Ÿ› ๏ธ Creating Tensors

TensorFlow gives you many ways to create tensors. Here are the most common:

1. From Regular Lists: tf.constant()

Turn Python lists into tensors:

import tensorflow as tf

# From a simple list
numbers = tf.constant([1, 2, 3, 4, 5])

# From a nested list (makes a 2D tensor)
grid = tf.constant([
    [1, 2, 3],
    [4, 5, 6]
])

2. All Zeros: tf.zeros()

Create a tensor filled with zeros:

# 3 zeros in a line
zeros_line = tf.zeros(3)
# Result: [0. 0. 0.]

# 2ร—3 table of zeros
zeros_table = tf.zeros([2, 3])
# Result: [[0. 0. 0.]
#          [0. 0. 0.]]

3. All Ones: tf.ones()

Create a tensor filled with ones:

# 4 ones in a line
ones_line = tf.ones(4)
# Result: [1. 1. 1. 1.]

# 3ร—2 table of ones
ones_table = tf.ones([3, 2])

4. Random Numbers: tf.random

Create tensors with random values:

# Random numbers between 0 and 1
random_tensor = tf.random.uniform([2, 3])

# Random numbers from bell curve
normal_tensor = tf.random.normal([2, 3])

5. A Range of Numbers: tf.range()

Create a sequence of numbers:

# Numbers 0 to 4
sequence = tf.range(5)
# Result: [0 1 2 3 4]

# Numbers 2 to 10, step by 2
evens = tf.range(2, 11, 2)
# Result: [2 4 6 8 10]

6. Fill with Any Value: tf.fill()

Create a tensor filled with any number you choose:

# 3ร—3 table filled with 7s
sevens = tf.fill([3, 3], 7)
# Result: [[7 7 7]
#          [7 7 7]
#          [7 7 7]]
graph TD A[Creating Tensors] --> B[tf.constant<br>From your data] A --> C[tf.zeros<br>All zeros] A --> D[tf.ones<br>All ones] A --> E[tf.random<br>Random values] A --> F[tf.range<br>Sequences] A --> G[tf.fill<br>Any value]

๐Ÿ”„ tf.Variable: Tensors That Can Change

Hereโ€™s a big secret: Regular tensors created with tf.constant() can NEVER change. Theyโ€™re like numbers written in permanent marker!

But sometimes, we need numbers that CAN change โ€“ especially when teaching AI to learn. Thatโ€™s where tf.Variable comes in!

The Difference:

tf.constant() tf.Variable()
Values are FIXED forever Values can CHANGE
Like a printed book Like a whiteboard
Great for input data Great for learning weights

Creating Variables

import tensorflow as tf

# Create a variable
my_variable = tf.Variable([1, 2, 3])
print(my_variable)
# <tf.Variable 'Variable:0'
#  shape=(3,) dtype=int32>

Changing Variable Values

# Create a variable
score = tf.Variable(10)

# Change the whole value
score.assign(25)
print(score)  # 25

# Add to the value
score.assign_add(5)
print(score)  # 30

# Subtract from the value
score.assign_sub(3)
print(score)  # 27

Why Variables Matter for AI

When AI learns, it needs to adjust numbers (called weights) to get better. Variables let TensorFlow:

  1. Start with initial guesses
  2. Calculate how wrong they are
  3. Update the values to be more correct
  4. Repeat until the AI is smart!
graph TD A[๐ŸŽฏ AI Learning Loop] --> B[Start with Variable] B --> C[Make Prediction] C --> D[Check if Wrong] D --> E[Update Variable] E --> C style B fill:#e8f5e9 style E fill:#fff3e0

Real Example: A Simple Learning Loop

import tensorflow as tf

# The AI's guess (starts wrong)
guess = tf.Variable(0.0)

# The right answer
target = 10.0

# Learning step by step
for i in range(5):
    # How far off are we?
    error = target - guess

    # Move closer (update!)
    guess.assign_add(error * 0.2)

    print(f"Step {i+1}: {guess.numpy():.1f}")

# Output:
# Step 1: 2.0
# Step 2: 3.6
# Step 3: 4.9
# Step 4: 5.9
# Step 5: 6.7

๐ŸŽฎ Quick Reference: Tensor Operations

Checking What You Have

tensor = tf.constant([[1, 2], [3, 4]])

tensor.shape      # (2, 2) - dimensions
tensor.dtype      # int32 - data type
tf.rank(tensor)   # 2 - number of dims
tf.size(tensor)   # 4 - total elements

Converting to Python

# Get the NumPy array
array = tensor.numpy()

# Get a single value (for scalars)
scalar = tf.constant(42)
value = scalar.numpy()  # 42

๐ŸŒˆ Summary: Your Tensor Toolkit

Youโ€™ve learned the building blocks of TensorFlow:

โœ… Tensor Fundamentals โ€“ Tensors are containers for numbers with shape, type, and values

โœ… Data Types โ€“ int32, float32, bool, string and more

โœ… Shapes & Ranks โ€“ Shape is the dimensions, Rank is how many dimensions

โœ… Creating Tensors โ€“ constant, zeros, ones, random, range, fill

โœ… Variables โ€“ Tensors that can change, essential for AI learning


๐Ÿš€ Youโ€™re Ready!

Now you understand tensors โ€“ the LEGO bricks of AI! Every neural network, every image recognition system, every chatbot uses tensors at their core.

Remember:

  • Tensors hold your data
  • Variables let AI learn
  • Shape and type matter for everything!

Go build something amazing! ๐ŸŽ‰

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.