Numerical Analysis With Numpy
Numerical Analysis With Numpy
✅✅
NumPy Arrays vs Python Lists............................................................................................................. 7
Python List..................................................................................................................................8
⚡ NumPy Array.............................................................................................................................. 8
📝
Speed Comparison...................................................................................................................... 8
⚡
(Python List in Action).....................................................................................................................9
Step 3: Doing it with NumPy ..........................................................................................................9
⏱️
(NumPy in Action)..........................................................................................................................10
Step 4: Comparing the Speeds .......................................................................................................10
Creating Arrays........................................................................................................................................ 10
a) From a Python list...................................................................................................................... 10
b) Zeros and Ones........................................................................................................................... 11
c) arange (like Python’s range)....................................................................................................... 11
d) linspace....................................................................................................................................... 11
e) Random Arrays........................................................................................................................... 11
1. [Link](3, 3)..............................................................................................................11
2. [Link](3, 3)............................................................................................................11
3. [Link](0, 10, (3, 3)).............................................................................................12
f) Random Seed (Reproducibility).................................................................................................12
Array Attributes.................................................................................................................................. 12
a) .shape.......................................................................................................................................... 13
b) .dtype.......................................................................................................................................... 13
c) .ndim........................................................................................................................................... 13
d) .size.............................................................................................................................................13
e) .itemsize (extra but useful).........................................................................................................13
The Big Picture (Why This Matters for AI/ML)................................................................................ 13
NumPy Indexing, Slicing, and Broadcasting : The Magic of Arrays.......................................................14
Indexing Arrays................................................................................................................................... 14
a) 1D Arrays....................................................................................................................................14
b) 2D Arrays...................................................................................................................................15
c) 3D Arrays....................................................................................................................................15
Boolean Indexing & Masking............................................................................................................. 15
Fancy Indexing.................................................................................................................................... 16
Slicing Arrays...................................................................................................................................... 16
Breakdown of what is happening:....................................................................................................... 16
Step 1: Concept...............................................................................................................................16
Step 2: Concept for 2D slicing....................................................................................................... 17
Broadcasting : The Heart of NumPy...................................................................................................18
a) Adding a scalar...........................................................................................................................18
b) Adding arrays with compatible shapes.......................................................................................18
Breakdown of why it is compatible:....................................................................................................18
Step 1: Understand the shapes........................................................................................................ 18
Step 2: How NumPy broadcasts.....................................................................................................18
reshape, transpose, newaxis.................................................................................................................19
Adding [Link]......................................................................................................................... 19
Shape After Transformation............................................................................................................20
🎨
Visualization................................................................................................................................... 20
Mini-Project: Grayscale Image Inversion .....................................................................................20
Image:..................................................................................................................................................21
Explanation:.........................................................................................................................................21
1. The “image” is just numbers (matrix form)................................................................................21
2. Displaying it with matplotlib...................................................................................................... 22
3. Inverting the image using broadcasting......................................................................................22
4. Visualizing inverted.................................................................................................................... 22
Numerical Operations in NumPy............................................................................................................. 23
1. Element-wise Operations................................................................................................................ 23
2. Matrix Multiplication...................................................................................................................... 23
First: Why do we even need "matrix multiplication"?................................................................... 23
1. The Three Faces of Matrix Multiplication in NumPy................................................................24
1. @ (modern operator)..............................................................................................................24
2. [Link]()...................................................................................................................................24
3. [Link]()...........................................................................................................................24
Difference....................................................................................................................................... 25
Example 1: Weighted Grades.....................................................................................................25
3. 📊
Why Three Options?.......................................................................................................................25
Aggregations (Summaries)........................................................................................................ 26
What Are Aggregations?.................................................................................................................26
The Functions................................................................................................................................. 26
Example in Code............................................................................................................................ 27
Why Does This Matter in AI / Data Science?................................................................................27
Relatable Analogy (Friends’ Heights)............................................................................................27
4. Cumulative Operations....................................................................................................................28
5. Axis Operations (Row vs Column)................................................................................................. 29
6. Clipping Values............................................................................................................................... 29
Mini Project: Manual Linear Regression Step................................................................................... 29
Step by Step Break Down:................................................................................................................. 30
Arrays x and y.................................................................................................................................30
Initial weights w and b....................................................................................................................30
Prediction: y_pred = w * x + b.......................................................................................................30
Compute error: error = ((y - y_pred)**2).mean()..........................................................................31
Gradients........................................................................................................................................31
Update weights............................................................................................................................... 31
Stacking Arrays...................................................................................................................................32
Example:......................................................................................................................................... 32
Splitting Arrays...................................................................................................................................32
Example:......................................................................................................................................... 33
Repeating & Tiling.............................................................................................................................. 33
Example:......................................................................................................................................... 33
Flattening Arrays................................................................................................................................. 33
Example:......................................................................................................................................... 33
Copy vs View...................................................................................................................................... 33
Example:......................................................................................................................................... 33
Sorting................................................................................................................................................. 34
Example:......................................................................................................................................... 34
Unique Values......................................................................................................................................34
Example:......................................................................................................................................... 34
Index Tricks.........................................................................................................................................34
np.ix_ → cross product of indices.................................................................................................. 35
That prints:......................................................................................................................................35
Explanation.................................................................................................................................... 35
The concrete array we’ll use...............................................................................................................35
Step 1 - What np.ix_([0,2], [1,2]) actually produces...........................................................................36
Step 2 - Why those shapes? (so they can combine)............................................................................36
Step 3 - Using it to select the submatrix..............................................................................................37
Step 4 - Contrast with arr[[0,2], [1,2]] (important!)............................................................................ 37
Short visual summary.........................................................................................................................37
Final checklist (so you remember which to use)................................................................................ 38
Related helpers (brief)....................................................................................................................38
[Link] → make coordinate grids...........................................................................................38
Randomness & Probability..................................................................................................................38
🟩🟦
1. Random Sampling...................................................................................................................... 39
Uniform Distribution............................................................................................................ 39
🎯🪄🟥
Normal Distribution (a.k.a. Bell Curve).............................................................................39
Binomial Distribution......................................................................................................... 39
2. [Link] - Picking Random Items.........................................................................40
🖼️⚖️
Practical Applications for AI/ML........................................................................................................ 41
1. Image Representation as NumPy Arrays..............................................................................41
2. Normalization & Standardization........................................................................................ 42
🌀🔀
3. One-Hot Encoding...................................................................................................................... 42
4. Dataset Shuffling & Batching..............................................................................................43
5. Convolution Basics (Before Deep Learning Frameworks)..................................................43
🧩
6. Implementing Loss Functions (MSE, Cross-Entropy)..............................................................44
Summary...................................................................................................................................44
⚙️
Connecting to AI Frameworks ( Beginner Breakdown)..........................................................................45
1. How NumPy Underlies TensorFlow & PyTorch..................................................................45
2. Converting Between NumPy Arrays and Tensors.....................................................................46
Using PyTorch........................................................................................................................... 46
Using TensorFlow..................................................................................................................... 46
3. When to Use NumPy vs Pandas vs SciPy..................................................................................46
Example:................................................................................................................................... 46
4. Why NumPy Operations Look Like Tensor Operations............................................................47
Example:................................................................................................................................... 47
🧩
5. Bonus (Optional but Cool): What Are Tensors Really?............................................................47
Summary Table........................................................................................................................ 48
The Source Code for this is available in my Github
repository:
[Link]
What NumPy is and Why It’s Used in AI/ML
Imagine you want to build an AI system. At its heart, AI is just math applied to data:
• Adding, multiplying, dividing, taking averages.
• Working with large datasets (millions of numbers).
• Representing vectors (like word embeddings, pixel values in an image).
• Working with matrices (like weights in a neural network).
If you tried to do this with pure Python lists, you’d run into problems:
• Slow performance (Python loops run one step at a time).
• High memory usage (Python objects carry overhead).
• No vectorization (you can’t just multiply a list by another list directly in a mathematical
sense).
👉 That’s why NumPy exists: it gives you a way to store and manipulate numerical data
efficiently, almost like C or Fortran speed, but with Python’s ease of use.
In AI/ML, every neural network weight, every image, every dataset feature is basically stored in a
NumPy array (or something built on top of it, like PyTorch tensors).
So, if you understand NumPy deeply, you understand the language that AI frameworks speak.
Why as np?
Because you’ll be calling NumPy functions a lot, and typing numpy everywhere would be too long.
np has become the standard alias in the Python community.
So now whenever you see [Link]() or [Link](), just remember it’s NumPy.
✅ NumPy Array
1. np_array = [Link]([1, 2, 3, 4, 5])
• Homogeneous: all elements must be the same type (e.g., all floats, all ints).
• Stored in contiguous memory blocks, like in C, so it’s extremely efficient.
• Supports vectorization: you can apply operations to the whole array at once without explicit
loops.
Vectorization is the magic: instead of writing a loop to add 2 to every number, you just write:
1. np_array + 2
and NumPy applies it to the whole array internally, in compiled C speed.
⚡ Speed Comparison
1. import time
2. import numpy as np
3.
4. # Python list
5. lst = list(range(1000000))
6. start = [Link]()
7. lst = [x + 2 for x in lst]
8. print("Python list:", [Link]()-start)
9.
10. # NumPy array
11. arr = [Link](1000000)
12. start = [Link]()
13. arr = arr + 2
14. print("NumPy array:", [Link]()-start)
You’ll see NumPy is many times faster. Let go in depth on the code analysis
When people first hear about NumPy, they often wonder:
“Why can’t I just use normal Python lists?”
Let’s break it down slowly using the above code as example.
⚡
6. After: [2, 3, 4, 5, 6, 7, ...]
(NumPy in Action)
1. Before: [0, 1, 2, 3, 4, 5, ...]
2. Apply "+2" to all at once (machine-like efficiency
3.
⚡)
⏱️
4. After: [2, 3, 4, 5, 6, 7, ...]
Even though both do the same job, NumPy is usually 30x+ faster (sometimes even 100x depending
on the task).
Creating Arrays
Creating arrays is the first step to fluency. NumPy gives you many tools:
d) linspace
1. [Link](0, 1, 5) # [0. , 0.25, 0.5 , 0.75, 1. ]
Creates evenly spaced numbers between start and stop. Very useful in plotting or when you need
normalized values.
e) Random Arrays
ML thrives on randomness (weight initialization, shuffling data, sampling).
1. [Link](3, 3) # Uniform distribution between 0 and 1
2. [Link](3, 3) # Normal distribution (mean=0, std=1)
3. [Link](0, 10, (3, 3)) # Integers between 0 and 10
When we use [Link], we’re basically asking the computer to “roll dice” for us. But the type of
dice we roll depends on the function we choose. Let’s break it down:
1. [Link](3, 3)
Think of it as rolling a special die that always gives you a number between 0 and 1.
• Each roll is equally likely just like spinning a fair wheel from 0.0 → 1.0.
• You ask for a 3x3 grid, so you get 9 rolls arranged in a little table.
🔎 Example Output:
1. [[0.12, 0.75, 0.55],
2. [0.89, 0.34, 0.01],
3. [0.67, 0.43, 0.92]]
2. [Link](3, 3)
Now imagine rolling a different die: this one produces numbers centered around 0.
• Most results will be close to 0, but sometimes you’ll get negative or positive numbers
farther away.
• This follows the bell curve (normal distribution, mean = 0, std = 1).
🔎 Example Output:
1. [[-0.45, 0.11, 1.23],
2. [ 0.88, -1.02, -0.33],
3. [ 0.09, -0.72, 0.55]]
Run this multiple times → you’ll always get the same numbers.
This is critical in AI research. Imagine you train two models and they give different results, just
because random numbers changed. Setting the seed makes experiments consistent.
Array Attributes
Once you have arrays, you need to understand their properties. Think of it like metadata about your
data.
Let’s create an example:
1. arr = [Link](3, 4)
b) .dtype
1. [Link]
c) .ndim
1. [Link]
• Number of dimensions.
• 1D = vector, 2D = matrix, 3D = tensor (e.g., images with color channels).
• Deep learning often uses high-dimensional tensors.
d) .size
1. [Link]
Indexing Arrays
Indexing is how we pick out elements from an array. Think of it as pointing at a specific box in a
huge warehouse.
a) 1D Arrays
1. import numpy as np
2.
3. arr = [Link]([10, 20, 30, 40, 50])
4. print(arr[0]) # 10 → first element
5. print(arr[-1]) # 50 → last element
c) 3D Arrays
3D arrays = “cubes” of numbers (think video frames or RGB images).
1. arr3d = [Link](27).reshape(3,3,3)
2. print(arr3d[0, 1, 2]) # pick element at depth 0, row 1, col 2
This is super useful in AI: e.g., selecting all pixels brighter than a threshold.
Fancy Indexing
Fancy indexing allows you to pick specific arbitrary elements using a list of indices:
1. arr = [Link]([10, 20, 30, 40, 50])
2. indices = [0, 2, 4]
3. print(arr[indices]) # [10 30 50]
Slicing Arrays
Slicing lets you select ranges of elements using [start:stop:step].
1. arr = [Link]([10, 20, 30, 40, 50, 60])
2. print(arr[::2]) # every other element → [10 30 50]
2D Slicing Example:
1. arr2d = [Link](1,10).reshape(3,3)
2. print(arr2d[:, 1]) # all rows, column 1 → [2 5 8]
3. print(arr2d[1, :]) # row 1, all columns → [4 5 6]
arr2d[:,1]
• : → all rows
• 1 → column 1
Pick column 1 from every row: 2,5,8
arr2d[1,:] →
• 1 → row 1
• : → all columns
Pick row 1 completely: 4,5,6
Visualization:
1. arr2d[:,1] -> pick vertical slice (column):
2. [[1 2 3] 2
3. [4 5 6] → 5
4. [7 8 9] 8]
5.
6. arr2d[1,:] -> pick horizontal slice (row):
7. [4 5 6]
a) Adding a scalar
1. arr = [Link]([1,2,3])
2. print(arr + 5) # [6 7 8]
6. [[11 22 33]
7. [14 25 36]]
Adding [Link]
1. arr[:, [Link]]
Here’s what happens:
• : → means take all elements from the original array.
• [Link] → means add a new dimension (axis) at that position.
So we’re turning a (3,) array into a column vector (3,1).
Why (3,1)?
• First dimension: 3 rows (from the original 3 elements).
• Second dimension: 1 column (the new axis we added).
Visualization
1. Before ((3,)):
2. [1 2 3] → just a flat row
3. After ((3,1)):
4. [[1]
5. [2]
6. [3]]
Image:
Explanation:
1. The “image” is just numbers (matrix form)
1. img = [Link]([[0,50,100,150,200],
2. [10,60,110,160,210],
3. [20,70,120,170,220],
4. [30,80,130,180,230],
5. [40,90,140,190,240]])
Here, img is a 5×5 NumPy array. Each value represents pixel intensity in a grayscale image.
• Small numbers (close to 0) → black/dark pixels
• Large numbers (close to 255) → white/bright pixels
• Numbers in between → shades of gray
👉 Think of it like a chessboard, but instead of black and white squares, each square has a
"brightness number."
2. Displaying it with matplotlib
1. [Link](img, cmap='gray', vmin=0, vmax=255)
2. [Link]("Original Image")
3. [Link]()
• [Link](img, ...): Displays the 2D array as an image.
• cmap='gray': Uses grayscale colormap (dark → bright).
• vmin=0, vmax=255: Fixes the brightness range so 0 = pure black, 255 = pure white (helps
keep consistency).
• [Link]("Original Image"): Adds a title.
👉 This lets us see numbers as shades of light, turning the matrix into something visually
meaningful.
4. Visualizing inverted
1. [Link](inverted, cmap='gray', vmin=0, vmax=255)
2. [Link]("Inverted Image")
3. [Link]()
This shows the inverted picture. Now the image looks like a photographic negative filter.
• Each pixel value is just a number from 0–255.
• 255 - img broadcasts 255 to every pixel → subtraction happens everywhere at once.
• This is much faster than looping pixel by pixel.
Visualization:
• You can see the original image → inverted image, making indexing + broadcasting real
and tangible.
✅ We’ll come to Matplotlib later to visualize how the line fits the data over time. For now, just know
NumPy gives us the tools to do the math that powers machine learning, data science, and
scientific computing.
Numerical Operations in NumPy
Think of NumPy arrays as supercharged Excel spreadsheets where each cell is a number. The
difference is that instead of painfully writing formulas cell by cell, NumPy can apply operations to
entire rows, columns, or even the whole sheet at once fast and memory efficient.
We’ll break this into categories:
1. Element-wise Operations
• Definition: Operations happen element by element across arrays of the same shape.
• Symbols: +, -, *, /, **
Example:
1. import numpy as np
2.
3. a = [Link]([1,2,3])
4. b = [Link]([10,20,30])
5.
6. print(a + b) # [11, 22, 33]
7. print(a * b) # [10, 40, 90]
8. print(a ** 2) # [1, 4, 9]
Imagine you and your friend have shopping lists. If you both list the number of apples, bananas, and
oranges, then a+b is like adding your lists item by item, the total fruit for each type.
⚡ Key point: Python list can’t do this directly ([1,2,3] * [10,20,30] would error). NumPy makes it
natural.
2. Matrix Multiplication
• Symbols:
• @ → Modern operator for matrix multiplication
• [Link]() → Works for both dot product and matrix multiplication
• [Link]() → Specifically for matrix multiplication
3. [Link]()
This is the clean, strict one.
It only does matrix multiplication, even for higher dimensions.
Useful in ML when multiplying batches of data (e.g. multiplying many input vectors by weights at
once).
1. print([Link](A, B)) # same as A @ B
Difference
Operation Shape Result Analogy
dot (1D) (n,) · (n,) scalar How similar are two directions? (cosine similarity idea)
matmul / @ (m,n) × (n,p) (m,p) Combining features with weights (AI, physics, graphics)
8. [[19 22]
9. [43 50]]
3. 📊 Aggregations (Summaries)
Functions: sum, mean, std, var, min, max, argmin, argmax
The Functions
1. sum() → Total
• [Link]() → adds up everything.
• Analogy: Imagine passing around a basket to collect everyone’s money in class. At
the end, sum is the total inside the basket.
2. mean() → Average
• [Link]() → total ÷ number of elements.
• Analogy: You and 4 friends go to dinner, spend $15k in total. Mean = $3k each (if split
fairly).
3. std() → Standard Deviation
• Measures how “spread out” the numbers are.
• Small std → values are tightly packed.
• Large std → values are scattered.
• Analogy: If your friends are all about the same height (±2cm), std is small. If one guy
is 7ft tall, std explodes.
4. var() → Variance
• Square of std. (Less intuitive, but easier for formulas).
• Analogy: Like measuring "spread" but in squared units.
5. min() / max()
• Smallest and largest values.
• Analogy: Shortest vs tallest friend.
6. argmin() / argmax()
• Index of the min/max element.
• Analogy: “Who is the tallest?” Instead of giving you height, it points at the person’s
position in the lineup.
Example in Code
1. import numpy as np
2.
3. arr = [Link]([1,2,3,4,5])
4.
5. print([Link]()) # 15
6. print([Link]()) # 3.0
7. print([Link]()) # 1.414...
8. print([Link]()) # 2.0
9. print([Link]()) # 1
10. print([Link]()) # 5
11. print([Link]()) # 4 (index of value 5)
12. print([Link]()) # 0 (index of value 1)
4. Cumulative Operations
• Functions: cumsum, cumprod
• They give you a “running total” instead of just the final answer.
Example:
1. arr = [Link]([1,2,3,4])
2. print([Link]()) # [1, 3, 6, 10]
3. print([Link]()) # [1, 2, 6, 24]
Relatable analogy:
Analogy:
• Axis 0 → “sum by subject” (all students’ scores in Math, English, Science)
• Axis 1 → “sum by student” (total marks per student)
6. Clipping Values
• Function: [Link](arr, min, max)
• It forces numbers into a safe range.
👉 Example:
1. arr = [Link]([100, -5, 50, 300])
2. print([Link](arr, 0, 255))
3. # [100, 0, 50, 255]
Why useful?
• In images, clipping ensures pixel values stay between 0 and 255.
• In ML training, it prevents exploding gradients (numbers becoming too large and
destabilizing learning).
Arrays x and y
x = [Link]([1,2,3,4,5])
y = [Link]([3,5,7,9,11])
b = 0.0
Prediction: y_pred = w * x + b
y_pred = w * x + b
• NumPy lets you multiply a number by an array → this multiplies each element:
• w * x → [0*1, 0*2, 0*3, 0*4, 0*5] = [0,0,0,0,0]
• Add b → [0+0, 0+0,...] = [0,0,0,0,0]
• Key idea: operations on arrays are element-wise in NumPy.
Gradients
grad_w = -2 * (x * (y - y_pred)).mean()
grad_b = -2 * (y - y_pred).mean()
Update weights
w = w - 0.01 * grad_w
b = b - 0.01 * grad_b
This shows how all those NumPy operations combine into AI. Under the hood, deep learning is
just millions of these updates, optimized with GPUs.
Advanced Manipulation
Stacking Arrays
Stacking means putting arrays together like LEGO blocks.
• Horizontal stack (side by side) → [Link]()
• Vertical stack (top to bottom) → [Link]()
• General stacking → [Link]()
Example:
1. import numpy as np
2.
3. a = [Link]([1,2,3])
4. b = [Link]([4,5,6])
5.
6. print([Link]([a,b])) # [1 2 3 4 5 6]
7. print([Link]([a,b]))
8. # [[1 2 3]
9. # [4 5 6]]
Analogy:
• hstack = placing books next to each other on a shelf.
• vstack = stacking books on top of each other.
Splitting Arrays
Splitting means cutting arrays into pieces.
• [Link]() → equal splits
• np.array_split() → allows unequal splits
Example:
1. arr = [Link]([1,2,3,4,5,6])
2. print([Link](arr, 3)) # [[1 2], [3 4], [5 6]]
3. print(np.array_split(arr, 4)) # [[1 2], [3 4], [5 6], [ ]]
Example:
1. arr = [Link]([1,2,3])
2. print([Link](arr, 2)) # [1 1 2 2 3 3]
3. print([Link](arr, 2)) # [1 2 3 1 2 3]
Analogy:
• repeat = saying each word twice ("Hi Hi Bye Bye").
• tile = replaying the whole sentence ("Hi Bye Hi Bye").
Flattening Arrays
Flattening means turning multi-dimensional arrays into 1D.
• ravel() → returns a view (shares memory, efficient).
• flatten() → returns a copy (separate memory).
Example:
1. arr = [Link]([[1,2],[3,4]])
2. print([Link]()) # [1 2 3 4]
3. print([Link]()) # [1 2 3 4]
Copy vs View
This is super important for memory efficiency.
• View: changes affect the original (they share data).
• Copy: changes don’t affect the original.
Example:
1. arr = [Link]([1,2,3])
2. view = arr[:2] # view
3. copy = arr[:2].copy() # copy
4.
5. view[0] = 99
6. print(arr) # [99 2 3] (changed!)
7.
8. copy[0] = 77
9. print(arr) # [99 2 3] (unchanged!)
Analogy:
• View = looking at the same paper (if you write, it changes the paper).
• Copy = photocopying the paper (original stays untouched).
Sorting
• [Link]() → sorts values in ascending order
• [Link]() → returns indices of sorted order
Example:
1. arr = [Link]([30,10,20])
2. print([Link](arr)) # [10 20 30]
3. print([Link](arr)) # [1 2 0]
Analogy:
• Sort = arranging books by height.
• Argsort = writing which positions they should move to.
Unique Values
• [Link]() → gives unique elements
• [Link](arr, values) → checks membership
• np.in1d(arr1, arr2) → like “is element in other array?”
Example:
1. arr = [Link]([1,2,2,3,3,3])
2. print([Link](arr)) # [1 2 3]
3. print([Link]([1,4], arr)) # [ True False ]
Index Tricks
These are NumPy “hacks” for advanced indexing.
np.ix_ → cross product of indices
1. arr = [Link](1,10).reshape(3,3)
2. print(arr)
3.
4. # pick rows [0,2] and cols [1,2]
5. print(arr[np.ix_([0,2], [1,2])])
That prints:
1. [[1 2 3]
2. [4 5 6]
3. [7 8 9]]
Explanation
Imagine a spreadsheet (grid of rows and columns).
• Rows are horizontal lines (0, 1, 2, ...).
• Columns are vertical lines (0, 1, 2, ...).
When you say “give me rows 0 and 2 and columns 1 and 2”, you want the little rectangle
that sits where those rows and columns cross, that’s the submatrix or block.
np.ix_ is the NumPy helper that builds the pair of index arrays you need to select that
block.
[[0],
[2]]
(two rows, one column)
• I[1] is the column index array, shaped (1,2) and looks like:
[[1, 2]]
(one row, two columns)
So I[0].shape == (2,1) and I[1].shape == (1,2).
[[0, 0],
[2, 2]]
• I[1] will be repeated down rows → becomes a (2,2) array of column indices:
[[1, 2],
[1, 2]]
Pairing these elementwise gives the full set of (row, column) coordinates:
(0,1), (0,2)
(2,1), (2,2)
That is the Cartesian product of rows × columns: every row index paired with every column
index.
Step 3 - Using it to select the submatrix
When you do:
1. sub = arr[np.ix_(rows, cols)]
NumPy uses those broadcasted index arrays and returns the 2×2 block:
1. sub =
2. [[ arr[0,1], arr[0,2] ],
3. [ arr[2,1], arr[2,2] ]]
With numbers:
1. sub =
2. [[2, 3],
3. [8, 9]]
Which matches the crossing of rows 0 & 2 with columns 1 & 2 from the original array.
7. X = [[1 2 3]
8. [1 2 3]]
9.
10. Y = [[10 10 10]
11. [20 20 20]]
1. Random Sampling
Imagine you’re rolling dice or picking cards from a deck, that’s random sampling.
In programming, we simulate this when we want to:
• Create fake data (e.g., random ages, incomes, etc.)
• Shuffle data for training a model
• Add randomness to algorithms (like dropout in neural networks)
NumPy gives us many ways to generate random samples.
🟩Uniform Distribution
• “Uniform” means everything has an equal chance.
• For example, picking a random number between 0 and 1 — every number in that range is
equally likely.
1. import numpy as np
2.
3. [Link](0, 1, 5)
4. # → e.g. [0.25, 0.73, 0.12, 0.94, 0.51]
Conceptually:
If you imagine a line between 0 and 1, any point is just as likely to be chosen as any other.
🟥 Binomial Distribution
Binomial is about counting successes in repeated experiments.
Example: flipping a coin 10 times and counting how many times it lands heads.
1. [Link](n=10, p=0.5, size=5)
2. # → e.g. [6, 4, 5, 7, 3]
Meaning:
• n = number of trials per experiment (10 flips)
• p = probability of success (0.5 = 50%)
• size = how many experiments to simulate
🧠 You get results like 6 heads, 4 heads, 5 heads, etc.
🎯 2. [Link] - Picking Random Items
Sometimes you want to pick random items from a list, like selecting random students or shuffling
training data.
1. names = ["Alice", "Bob", "Charlie", "Dina"]
2. [Link](names, 2)
3. # → ['Charlie', 'Bob']
📊 5. Probability Distributions
A probability distribution describes how likely different outcomes are.
You can think of it like a “map” of randomness.
• Uniform → everything equally likely
• Normal → most around the middle
• Binomial → counts of successes/failures
• Exponential → time until something happens (like waiting times)
AI models, especially probabilistic ones depend on understanding these distributions to model
uncertainty or noise.
Why this matters: AI models see images as numbers. So understanding how they’re stored helps
you process them later for training.
Example:
1. arr = [Link]([10, 20, 30, 40])
2.
3. # Normalization (0 to 1)
4. norm = (arr - [Link]()) / ([Link]() - [Link]())
5.
6. # Standardization (mean = 0, std = 1)
7. std = (arr - [Link]()) / [Link]()
8.
9. print("Normalized:", norm)
10. print("Standardized:", std)
Why this matters: Neural networks learn better when numbers are small and balanced.
3. One-Hot Encoding
Concept:
AI models can’t understand words or categories, only numbers.
So we convert categories like:
["cat", "dog", "bird"]
Why this matters: This encoding lets the model compare outputs correctly for classification tasks.
Why this matters: Models train faster and more fairly with shuffled batches.
Why this matters: This is the foundation of CNNs (Convolutional Neural Networks), the core
of computer vision.
👉 Why this matters: The smaller the loss, the smarter the model gets.
11. print("Cross-Entropy:", cross_entropy)
🧩 Summary
Concept What it Teaches Why It Matters
Image as Array Numbers = pixels Foundation for computer vision
Normalization Scaling values Helps model learn
One-Hot Encoding Convert categories Needed for classification
Shuffling/Batching Fair learning Prevents bias
Convolution Pattern detection Base of CNNs
Loss Functions Model feedback Core of training
Connecting to AI Frameworks ( Beginner
Breakdown)
⚙️ 1. How NumPy Underlies TensorFlow & PyTorch
What’s going on:
• You already know NumPy → it handles arrays and math.
• AI frameworks like TensorFlow and PyTorch do almost the same thing, but faster (and
often on GPUs instead of CPUs).
Think of it like this:
🧩
Level Tool Job
🚀
Beginner NumPy Teaches you basic math with arrays (CPU only)
✅
Advanced PyTorch, TensorFlow Use arrays called tensors (can run on GPU for big AI models)
So the core idea is:
Tensors = Fancy NumPy arrays that can live on GPU and track gradients for training.
2. Converting Between NumPy Arrays and Tensors
Let’s look at how the two talk to each other.
Using PyTorch
1. import numpy as np
2. import torch
3.
4. # Create NumPy array
5. arr = [Link]([[1, 2], [3, 4]])
6.
7. # Convert NumPy → Tensor
8. tensor = torch.from_numpy(arr)
9. print(tensor)
10.
11. # Convert Tensor → NumPy
12. back_to_numpy = [Link]()
13. print(back_to_numpy)
Both share the same memory, changing one changes the other!
Using TensorFlow
1. import tensorflow as tf
2. import numpy as np
3.
4. arr = [Link]([1, 2, 3])
5. tensor = tf.convert_to_tensor(arr)
6.
7. print(tensor) # TensorFlow tensor
8. print([Link]()) # Back to NumPy
🧮
Library Use For Example
📊
NumPy Math, arrays, and linear algebra Image pixels, ML math
🔬
Pandas Data handling (tables like Excel) Datasets, CSV files
SciPy Advanced math, scientific tools Statistics, optimization
Example:
1. import numpy as np
2. import pandas as pd
3. from scipy import stats
4.
5. # NumPy: raw math
6. arr = [Link]([1, 2, 3, 4])
7. print([Link](arr))
8.
9. # Pandas: data table
10. df = [Link]({"Age": [10, 20, 30]})
11. print(df["Age"].mean())
12.
13. # SciPy: scientific functions
14. print([Link](arr)) # Standardize data
Rule of thumb:
• NumPy = for math
• Pandas = for data
• SciPy = for advanced math
Example:
1. import numpy as np
2. import torch
3.
4. # NumPy
5. a = [Link]([[1, 2], [3, 4]])
6. b = [Link]([[5, 6], [7, 8]])
7. print([Link](a, b)) # matrix multiply
8.
9. # PyTorch
10. a_t = [Link]([[1, 2], [3, 4]])
11. b_t = [Link]([[5, 6], [7, 8]])
12. print([Link](a_t, b_t)) # same idea!
Key idea:
If you understand NumPy’s rules, how shapes, broadcasting, and indexing work,
you already understand 80% of PyTorch and TensorFlow.
🧩 Summary Table
Concept Meaning Example
NumPy → Base library Handles arrays and math [Link], [Link]
Built on top of NumPy
TensorFlow / PyTorch [Link], [Link]
ideas
Converting between
Easy and instant torch.from_numpy()
them
Pandas Works with tabular data CSV or DataFrames
SciPy Adds scientific math tools Stats, optimization
Tensors Generalized arrays Used in AI models