Module 3 · Python for data: NumPy, pandas and Matplotlib
Time: about 5 hours with readings · Lab: python course/labs/lab03_python_data.py
You need: basic Python (variables, lists, loops, functions) and Module 2 §3 (vectors, matrices and shapes). If Python itself is new, the CS50P course in Go deeper covers the basics first.
By the end you can:
- think in arrays: shapes, axes, broadcasting and boolean masks;
- explain why vectorised NumPy code is ~100× faster than Python loops;
- slice, group, count and join tables with pandas, and read SQL results into a DataFrame;
- make a clear chart with Matplotlib, and avoid one classic aggregation mistake.
Why this matters in TrayCheck
| Library | Where it's used | What for |
|---|---|---|
| NumPy | food_model.py, vision_score.py, every lab |
Images and model outputs are arrays |
| pandas | review_rules.py, records.py, app.py, vision_score.py |
Scores, records and dashboard tables |
| Matplotlib | analyze.py, labs |
Charts saved as images |
| sqlite3 | records.py |
The records database (Module 12) |
review_rules.review_tradeoff is a good example of the style this module teaches: no loop over
photos, only whole-column operations such as mistakes & flagged and .sum().
1. NumPy: arrays and vectorisation
A NumPy array (ndarray) holds numbers of one type in a grid with a shape. An RGB photo
is an array of shape (height, width, 3); a batch of TrayCheck inputs is (batch, 96, 96, 3).
Vectorisation. NumPy runs operations over whole arrays in fast compiled code. The lab sums a million numbers:
Sum of 1,000,000 numbers: Python loop 113 ms, NumPy 0.85 ms (132x faster)
Why so much faster? In a Python list, every number is a separate Python object stored somewhere in
memory, and each pass of a Python loop makes the interpreter look up what the object is, how to add
it, and where to put the result: a lot of bookkeeping per number. A NumPy array stores raw numbers of
one type packed side by side in one block of memory, and a.sum() runs a single loop written in C
over that block, with none of the per-number bookkeeping; modern processors can even add several
neighbouring numbers in one instruction. Same arithmetic, a fraction of the overhead.
Deep learning frameworks (TensorFlow, PyTorch) apply the same idea to tensors on CPUs and GPUs.
Axes. a.mean(axis=0) averages down the rows (one result per column); axis=1 averages
across each row. For an image batch (B, H, W, C), averaging over axes 1 and 2 gives one value
per image per channel. That is global average pooling, the step that turns MobileNetV2's
feature maps into one vector per photo (Module 8).
Broadcasting. When shapes differ, NumPy stretches the smaller array where that makes sense.
The rule: line the shapes up from the right; each pair of sizes must be equal, or one of them must be
1 (or missing), and a size of 1 is stretched to match. Example: a table a of 4 rows × 3 columns
has shape (4, 3); its column means a.mean(axis=0) have shape (3,). Lined up from the right, 3
matches 3, and the missing rows dimension is treated as 1 and stretched to 4. So a - a.mean(axis=0)
subtracts the row of means from every row. Standardising features this way is the first step of
Module 4's lab. Shapes (4, 3) and (4,) would fail: lined up from the right, 3 and 4 don't match.
Boolean masks. a > 6 gives an array of True/False values, and a[mask] selects matching
elements. mask.sum() counts them, because True counts as 1. mask.mean() gives the fraction
that are True. That is how review_tradeoff computes the share of photos flagged.
2. pandas: tables
A DataFrame is a table: named columns, each a Series of one type. The project's tables:
| Table | Built by | One row is |
|---|---|---|
vision/scores_test.csv |
vision_score.py |
a held-out test photo with all four scores |
meal_records (SQLite) |
records.py |
one saved check of one photo |
Core moves, all used in the project:
scores = pd.read_csv("vision/scores_test.csv")
scores[scores["confidence"] < 0.85] # filter rows with a mask
scores.groupby("actual")["correct"].mean() # accuracy per real dish = recall
pd.crosstab(scores["actual"], scores["prediction"]) # the confusion matrix
test.set_index("image_path").join(saved, rsuffix="_saved") # match two tables (vision_score.py)
pd.read_sql_query("SELECT * FROM meal_records", conn) # SQL result into a DataFrame (records.py)
The lab's cross-tabulation is exactly the confusion matrix on the dashboard:
prediction baby_back_ribs beet_salad bibimbap bread_pudding
actual
baby_back_ribs 36 0 1 3
beet_salad 1 36 2 1
bibimbap 0 1 37 2
bread_pudding 3 1 3 33
A classic aggregation trap: ratio of sums vs mean of ratios
"Leftover share at dinner" can mean two different things:
- total food returned ÷ total food served (ratio of sums), which answers how much food is wasted; or
- the average of each plate's own leftover percentage (mean of ratios), which answers what a typical plate looks like.
The lab computes both:
Leftover share by meal period (sum of returned / sum of served): dinner 25.0 lunch 15.6
Average of each plate's own leftover %: dinner 25.0 lunch 15.5
They are close here because plates are similar sizes, but they can differ a lot: a few huge, untouched plates move the ratio of sums much more than the average. TrayCheck's dashboard uses the ratio of sums because the operational question is about food wasted. Always say which one you mean.
2b. SQL: the same questions in the language organisations use
The position description asks for experience with "Python, R, SQL or equivalent" and the "ability to work with and analyse structured datasets". In a PoC, the vendor's and the hospital's data will most likely sit in databases, and SQL is how you ask them questions. The good news: every pandas move above has a direct SQL equivalent.
| Question | pandas | SQL |
|---|---|---|
| Pick columns | df[["dish", "served_g"]] |
SELECT dish, served_g FROM t |
| Filter rows | df[df["served_g"] > 0] |
WHERE served_g > 0 |
| Group and summarise | df.groupby("dish")["corrected"].sum() |
SELECT dish, SUM(corrected) FROM t GROUP BY dish |
| Sort | .sort_values("n", ascending=False) |
ORDER BY n DESC |
| Combine two tables | a.merge(b, on="id") |
FROM a JOIN b ON a.id = b.id |
Three queries you could run on TrayCheck's own database (records/traycheck.db, table
meal_records), each answering a question from Modules 9–11:
-- How often do people correct each dish the model predicts?
SELECT predicted_dish,
COUNT(*) AS trays,
SUM(checked) AS checked,
SUM(corrected) AS corrected,
ROUND(100.0 * SUM(corrected) / NULLIF(SUM(checked), 0), 1) AS pct_of_checked_corrected
FROM meal_records
GROUP BY predicted_dish
ORDER BY corrected DESC;
-- Leftover share by meal period: ratio of sums, usable weights only (Module 9 §1)
SELECT meal_period,
COUNT(*) AS trays_used,
ROUND(100.0 * SUM(returned_g) / SUM(served_g), 1) AS leftover_pct
FROM meal_records
WHERE served_g > 0 AND returned_g IS NOT NULL AND returned_g <= served_g
GROUP BY meal_period;
-- Data-quality counts (Module 9 §1)
SELECT SUM(served_g IS NOT NULL AND returned_g IS NULL) AS missing_returned_weight,
SUM(returned_g > served_g) AS returned_more_than_served
FROM meal_records;
Joins: combining two tables
A join matches rows of two tables on a shared column. Suppose the records name each tray's dish, and a separate menu table holds each dish's energy content:
meal_records menu
tray_id final_dish dish kcal
1 bibimbap bibimbap 560
2 beet_salad beet_salad 210
3 apple_pie bread_pudding 410
SELECT r.tray_id, r.final_dish, m.kcal
FROM meal_records AS r
JOIN menu AS m ON m.dish = r.final_dish;
returns trays 1 (560) and 2 (210). Tray 3 vanishes, because no menu row matches apple_pie. An
inner join (plain JOIN) keeps only rows with a match in both tables. A LEFT JOIN keeps
every row of the first table and fills missing matches with NULL: tray 3 would appear with an
unknown kcal. Silent row loss from an inner join is one of the most common analysis mistakes, so
always compare row counts before and after a join. (pandas' a.merge(b, on=..., how="left") is
the same operation.)
Points worth knowing:
NULLmeans unknown, and it doesn't equal anything, not even anotherNULL. Test for it withIS NULL/IS NOT NULL, never= NULL.NULLIF(x, 0)avoids dividing by zero: it turns 0 intoNULL, and the result becomesNULLinstead of an error.- Filter before you aggregate. The
WHEREclause in the second query is the same exclusionrecords.usable_weights()applies in Python. Report how many rows it removed. - You can open the database in the free DB Browser for SQLite or run the queries from Python
with
pd.read_sql_query(sql, conn). R users do the same with thedplyrpackage (filter,group_by,summarise); the concepts are identical.
3. Matplotlib: charts that tell the truth
Matplotlib draws onto a Figure containing one or more Axes. The lab saves a histogram of
top scores for right and wrong answers to course/labs/output/lab03_confidence.png, with the
review threshold drawn as a dashed line. You'll see most right answers piled up near 1.0 and the
wrong answers spread out. A few wrong answers still sit beyond the line.
Principles worth adopting from day one:
- one message per chart, stated in the title;
- label axes with units ("Top score", "Test photos");
- one y-axis per chart (never two different scales on one chart);
- if a number matters, show it directly or in a table next to the chart.
Python features the project uses
| Feature | Example in the project | Why it's there |
|---|---|---|
pathlib.Path |
ROOT / "vision" / "metrics.json" |
Paths that work on Windows and Linux |
| f-strings | f"{score:.1%}" |
Readable formatting (0.991 → 99.1%) |
| List comprehensions | [round(0.50 + 0.05 * i, 2) for i in range(10)] |
Build lists concisely |
@dataclass |
Decision in review_rules.py |
Small classes that hold data |
| Type hints | def decide(scores: dict[str, float], ...) -> Decision |
Documentation that tools can check |
functools.lru_cache |
model_version() in food_model.py |
Compute once, reuse (hashing a 19 MB file) |
with blocks |
with connect(db) as conn: |
Resources are cleaned up even if errors happen |
Check your understanding
1. A batch of feature maps has shape (32, 3, 3, 1280). What shape do you get after averaging over axes 1 and 2?
(32, 1280): one 1280-number vector per photo. That's global average pooling.
2. How would you compute "the share of test photos flagged at threshold 0.85" in one line of pandas?
(scores["confidence"] < 0.85).mean(). The comparison gives a True/False column, and its mean
is the share of Trues. It gives 0.2375 on the test set.
3. Per-dish accuracy from groupby("actual") is recall, not precision. Why?
Grouping by the real dish asks "of the photos that really are bibimbap, what share did the model get right?", which is recall. Precision groups by the predicted dish: "of the photos the model called bibimbap, what share really were?"
4. A kitchen serves 9 small plates (200 g, 10% returned) and 1 big untouched plate (1000 g, 100% returned). Compute both leftover measures.
Ratio of sums: (9×20 + 1000) / (9×200 + 1000) = 1180 / 2800 ≈ 42%. Mean of ratios: (9×10% + 100%) / 10 = 19%. Same data, very different answers, so always say which one you mean.
Go deeper
Short on time or new to this? The study guide says exactly which of these to read first.
Core
- Python for Data Analysis, 3rd ed. (Wes McKinney, creator of pandas; O'Reilly 2022), free online at wesmckinney.com/book: Chapter 4, NumPy Basics, Chapter 5, Getting Started with pandas and Chapter 10, Data Aggregation and Group Operations.
- Python Data Science Handbook (Jake VanderPlas), free at jakevdp.github.io/PythonDataScienceHandbook: the NumPy chapter (especially Computation on Arrays: Broadcasting and Comparisons, Masks, and Boolean Logic) and the pandas chapter (Aggregation and Grouping).
SQL (free)
- SQLBolt: short interactive lessons 1–12 cover everything in §2b, in about two hours. sqlbolt.com
- pandas documentation, Comparison with SQL: every common query written both ways. pandas.pydata.org
- Kaggle Learn, Intro to SQL: practice on real public datasets in the browser. kaggle.com/learn/intro-to-sql
Optional
- NumPy's official guide NumPy: the absolute basics for beginners, and pandas' 10 minutes to pandas (both on their official documentation sites).
- Harvard CS50's Introduction to Programming with Python (CS50P), if any Python basics feel shaky: cs50.harvard.edu/python.
- Harris et al., Array programming with NumPy, Nature 585 (2020): the peer-reviewed paper describing NumPy's design.
Interview angle
"The analysis is vectorised pandas and NumPy, so there are no loops over records. For example, the review trade-off table is a handful of boolean-mask operations per threshold. For waste I report total grams returned over total grams served, because the operational question is how much food is wasted, not what the average plate looks like."