NumPy: Arrays for AI
Applied AI Internship · Module 1 · Class 2

NumPy:arrays for AI

Every photo, song and sentence becomes numbers before AI can use it. Today we learn the Python tool that holds and crunches those numbers.

Python refresherLive coding10 guided exercises
In [1]:import numpy as np
np.array([1, 2, 3]) * 2
Out[1]:

→ / Space: next  ·  ←: back  ·  R: restart slide  ·  Home: restart presentation  ·  P: draw  ·  B: whiteboard  ·  F: full screen

Recap · Class 1

Last class in 6 questions

Ask the class first. Then click a card to show the answer.

Agenda

Today's plan

By the end of today: you can create, slice, reshape and do maths on NumPy arrays without writing a single loop.

Why NumPy · Big idea

To an AI, everything is a grid of numbers

Photo

Pixels

Each tiny square is a number: 0 is black, 255 is white.

Voice note

Sound samples

The wave is measured 44,100 times every second.

Message
Ilovechai
40184230577

Word IDs

ChatGPT turns every word into a number before it reads it.

Marks sheet
MathsCS
Aarav7891
Diya4572
Kabir9295

Tables

Rows and columns of numbers. Most company data looks like this.

NumPy is the Python library that stores these grids and does maths on them, fast. Pandas, scikit-learn, TensorFlow and PyTorch all work with NumPy arrays.

Why NumPy · Speed

Race: add 1 to one million marks

Python list + loop

new = [] for m in marks: new.append(m + 1)
0 msabout

NumPy array

new = marks + 1
0 msabout
Times from a normal laptop, slowed down so you can watch. Your Colab may be a little different.

Same answer, about 50× faster. And the NumPy code is one short line. When a model trains on millions of numbers, this speed decides whether it takes minutes or days.

Why NumPy · Inside the computer

Why is NumPy so much faster?

Python list

Items live all over the memory

A list stores addresses. Python must follow each arrow and check each item's type, one at a time. Items can even be mixed: [85, "hi", 3.5]

NumPy array

One tight block, one type

All numbers sit side by side and have the same type. The CPU can work on the whole block at once, with fast code written in C.

Vectorization = one instruction for the whole array, instead of a Python loop. In this class we write marks + 5, never a for loop.

Why NumPy · Watch out

Same symbol, different meaning

Guess each answer before you click ▶.

Create arrays · np.array

Make an array from a list, then read its ID card

marks = np.array([[78, 65, 82, 91], # Aarav [45, 38, 56, 72], # Diya [92, 88, 79, 95], # Kabir [35, 42, 30, 60], # Meera [68, 71, 74, 80]]) # Rohan

A list of lists becomes a 2D array: rows = students, columns = subjects (Maths, Physics, Chem, CS). We will use this table all class.

marks.shape(5, 4)

5 rows, 4 columns. The most useful line in NumPy. Check it often.

marks.ndim2

Number of dimensions. A list is 1D, a table is 2D, a colour photo is 3D.

marks.dtypeint64

Type of every item. Whole numbers here. With decimals it becomes float64.

marks.size20

Total number of items: 5 × 4 = 20.

Create arrays · Live demo

Ready-made arrays: no typing needed

1. Pick a function
2. Change the numbers

Create arrays · Two ways to count

arange or linspace?

np.arange(start, stop, step)
You choose the gap. The stop value is not included. Use it for counting: 0, 5, 10, …
np.linspace(start, stop, num)
You choose how many. Both ends are included. Use it for smooth graph x-axes.
Indexing · 1D

Pick items by position: Mumbai temperatures, 10 days

Slice rule: t[start:stop:step]. Start is included, stop is not. Counting starts at 0. Negative numbers count from the end.

Indexing · 2D

In a table, give two positions: m[row, column]

: on its own means "all". So m[:, 0] = all rows, column 0 = everyone's Maths.

Indexing · True / False filter

Who passed Maths? Filter with a condition

maths
maths >= 40
names[maths >= 40]
(maths >= 40).sum()
4
True counts as 1, False as 0. So .sum() counts the passes.

In AI: this is how we pick rows of data, like "only fraud payments" or "only emails marked spam", in one line.

Reshape · Live demo

reshape(): same numbers, new shape

.shape

The one rule: the new shape must hold the same number of items. 12 = 3 × 4 = 2 × 6 = 2 × 2 × 3. Write -1 and NumPy works out that number for you.

Reshape · Images

A camera sends one long row. Reshape makes it a photo.

pixels.shape → (64,)

What arrives: 64 numbers in a row

pixels.reshape(8, 8)

Now it is an 8 × 8 picture

colour photo → (8, 8, 3)

Colour adds a 3rd dimension

RGB

3 numbers per pixel: red, green, blue.

Your phone photo is an array of shape (3000, 4000, 3): 36 million numbers. This is exactly Exercise Q4 and Q5 today.

Reshape · Going back to one row

flatten() and -1: very common in AI code

1

Grid → row

Some models want each example as one row of numbers.

img.flatten() # (8,8) → (64,)
2

Handwritten digits

A famous dataset has photos of digits 0–9, each 28 × 28 pixels.

28 × 28 = 784 numbers
3

A whole batch

100 photos together have shape (100, 28, 28).

imgs.reshape(100, -1)
4

Ready for the model

100 rows, 784 columns: one row per photo. -1 worked out the 784.

→ (100, 784)
Vectorized operations · Live coding

Maths on the whole array at once

Broadcasting · The idea

Broadcasting: the small array stretches to fit

Number + array
(3,) + ()
+
=
Table + row
(3, 3) + (3,)
+
=

Grace marks per subject: +5 Maths, 0 Physics, +3 Chem. The row is copied down to every student.

Dashed boxes are not really copied. NumPy pretends, so it uses no extra memory.

Broadcasting · The rule

Will these two shapes work together?

Quick examples

Rule: line the shapes up from the right. Each pair must be equal, or one of them must be 1. A missing number counts as 1.

Broadcasting · Common error

Attendance bonus per student: why does it fail?

Try 1
bonus = np.array([2, 0, 1, 3, 0]) # (5,) marks + bonus # (5, 4) + (5,)
ValueError: operands could not be broadcast together with shapes (5,4) (5,)
Fix: make it a column
bonus.reshape(5, 1) # (5, 1) marks + bonus.reshape(5, 1) # works!

The column is copied across to all 4 subjects.

Statistics · Live coding

Six one-word statistics

Statistics · Rows or columns?

axis: which direction do we squash?

Function
axis

Remember: axis=0 goes down → one answer per column (subject). axis=1 goes across → one answer per row (student).

Statistics · argmax in AI

argmax: how an AI model picks its answer

A photo goes into an image model. It gives one score per label:
probs = np.array([0.05, 0.80, 0.15]) labels = np.array(["cat", "dog", "bird"])
probs.max()0.8

The biggest value. Good, but it does not tell us which label.

probs.argmax()1

The position of the biggest value.

labels[probs.argmax()]'dog'

Same trick for our class: names[marks[:, 3].argmax()] → 'Kabir', the CS topper.

Statistics · Spread

Same average, very different classes

std (standard deviation) = how far marks usually are from the average. Small std: everyone is close. Big std: marks are spread out. In Module 2 we use mean and std to scale data before training.

Matrix operations · Transpose

Transpose: rows become columns

.shape

Row 0 (blue) becomes column 0. Use .T when two shapes do not line up for matrix multiplication.

Matrix operations · Dot product

Dot product = your bill at the canteen

item
vada pav
sandwich
chai
qty
price (₹)
qty * price
add them up
₹245
80 + 120 + 45

One line: np.dot(qty, price) or qty @ price → 245. Multiply the pairs, then add. A neuron in a neural network does exactly this.

Matrix operations · @

Matrix multiplication: many dot products at once

Shape rule(2, 3) @ (3, 2) → (2, 2)Inner numbers must match. Outer numbers give the answer's shape.

Click any orange answer box to see how it was made.

Matrix operations · Watch out

* and @ are not the same

a * b · element by element

Each box times the box in the same place. Shapes must match (or broadcast).

a @ b · matrix multiplication

Row times column, then add. Top-left: 1×10 + 2×30 = 70.

Same inputs, different answers. If your model gives strange numbers, check whether you meant * or @.

Putting it together

One line of a neural network uses everything from today

scores = X @ W + b pred = scores.argmax(axis=1)
1

X: the data

4 emails, 3 numbers each: links, CAPITAL words, says "FREE".

reshape · shape (4, 3)
2

X @ W

Weights turn each email into 2 scores: not spam, spam.

matrix multiplication
3

+ b

A bias of shape (2,) is added to every row of (4, 2).

broadcasting
4

argmax

For each email, pick the bigger score.

statistics · axis=1

Q10 today is this exact spam filter. In Module 2, a model will learn W and b by itself.

Summary

NumPy cheat sheet: keep this open in the lab

Break

5-minute break

5:00

When you come back: open Colab and the class notebook link from the group.

Hands-on

Open the exercise notebook

1

Open the link, save a copy

Class group link → File → Save a copy in Drive

2

Run the Setup cell

It loads NumPy and the marks table. Wait for the green tick ✓

3

Replace every None

Write your answer in the 💻 cell, then run the ✅ check cell below it

4

Red error? Read the last line

The check message tells you what to fix

5

Stuck for 3 minutes?

Read the hint in the question. Still stuck: raise your hand

How we will work

We solve the questions together, a few at a time. You try first, then I show the answer on the screen.

Finished early?

Help your neighbour. Point, but do not type for them. Then try the Bonus at the end.

Hands-on · Exercise set

Your 10 questions

Submit: a screenshot showing all 10 green ✅ ticks, plus the link to your notebook.

Hands-on · Debugging

Four errors you will see today, and the fix

Shapes do not match

ValueError: operands could not be broadcast together with shapes (5,4) (5,)

Fix: print both .shapes. Line them up from the right. Often you need .reshape(5, 1).

Wrong reshape size

ValueError: cannot reshape array of size 64 into shape (8,7)

Fix: rows × columns must equal the size. 8 × 8 = 64. Or use -1.

Counting from 1

IndexError: index 5 is out of bounds for axis 0 with size 5

Fix: 5 rows have positions 0 to 4. The last one is [-1].

Skipped the Setup cell

NameError: name 'np' is not defined

Fix: run cells top to bottom. Or Runtime → Run all.

Wrap-up

Before you go

Exit question

A class has 30 students and 5 subjects. What is the shape of marks.mean(axis=0)? Why?

Write the answer on paper or post it in the class group.

Homework: submit these Submit before the next class
Thank you

Questions?

Today you created arrays, sliced them, reshaped a flat row into a photo, used broadcasting, found statistics along an axis and multiplied matrices, all without a single loop.

In [∞]:class_2.status()
Out[∞]:'complete ✓'