Orientation — The Map & the Mindset
"You already know how to build systems that follow rules. Now learn how to build systems that discover rules."
This course assumes three things of you:
- You can read and write Python.
- You know basic SQL.
- You are comfortable with a terminal and git.
Fluent in Java, JavaScript, TypeScript or Go but not Python — or just rusty? Take Appendix A1 · The Python Primer first, about six hours, and come back. Module 01 will then feel natural.
Completely new to programming? Start with the official Python tutorial or Automate the Boring Stuff, then A1, then here. This course teaches AI to engineers, not programming from zero.
01 · The hookThe AI-Shaped Hole in a Nine-Year Résumé
AI/ML is a different way of writing programs: instead of writing the rules, you show the machine examples and it derives the rules. This page is the map of what you will learn, and the honest version of what the job market pays for.
"I've been shipping React frontends, Python and Node backends, and Postgres schemas for nine years. I can design a system under load, debug production at 3 a.m., and mentor a team. But when I open an ML repo I see tensors, loss functions, and weights — and when I open my job feed I see LLM, RAG, and agents in every posting that pays what I'm worth. What is machine learning, fundamentally? And how does it fit into the architecture I already know cold?"
Let's put numbers on that feeling, because the numbers are the point. Lightcast's study of 1.3 billion job postings found that AI skills carry a 28% salary premium — roughly $18K/year — and listing two or more AI skills pushes that to 43%.
Roles mentioning LLM or RAG have grown roughly 340% since 2024, while generic ML postings declined about 18%. Agentic-AI postings in the US carry a median total comp of $213K (as of mid-2026).
The market didn't just get hotter; it repriced what it wants — and what it wants is engineers who can put models into production systems.
The same four numbers, drawn, so you can see how big each one is rather than read it.
- The premium ruler. Zero to fifty percent, left to right. The first dot is what one AI skill adds to a salary in Lightcast's data: 28%, roughly $18K a year on a typical engineering salary. The second dot, further right, is what two or more AI skills add: 43%. The gap between the dots is the point: the second skill is worth almost as much again as the first, which is why this course teaches several rather than one.
- The posting bars. The tall bar is how much the number of postings mentioning LLM or RAG grew from 2024 to now: 340%, more than four times as many. The short bar going below the baseline is generic ML postings, down 18%. The market did not grow evenly; it moved from one kind of role to another. The $213K under the bars is the median total pay for the agentic-AI roles at the top of that tall bar.
Here's the part most people miss: the market is not asking you to become a researcher. Walmart's Distinguished engineer posting for agentic systems asks for 12+ years of engineering with only 2+ years in GenAI. Goldman Sachs' VP postings ask for production engineering, cloud-native design, and cross-team leadership — over research pedigree. Nine years of shipping software plus one to two years of provable GenAI work is precisely the profile large companies are hiring. Your experience isn't the thing to overcome. It's the asset.
- What the posting asks for. Twelve cells, one per year. Ten of them are ordinary engineering: designing systems, running them under load, mentoring. Only the last two, shaded, are GenAI. The posting is for an engineer who added AI late, not for a researcher who was never anything else.
- What you will have. Nine solid cells you already own. The shaded cell is the year of provable GenAI work this course builds, lab by lab, and the dashed cell is the second year that follows on the job. Line the two rows up and the gap is one to two cells wide, not nine.
So this module does one job: it installs the mental model that makes everything else in the course land. The core of it is a single idea we'll call the inversion — machine learning flips which side of the software equation you write and which side the computer produces. Once you see it, tensors and loss functions stop being an alien religion and start being a build pipeline with unfamiliar file extensions.
Nearly every ML concept has a name you already use. A model file is a compiled artifact — the deployable output of a build. Training is the build pipeline that produces it. Inference is a function call against the deployed artifact. Hyperparameters are build-time config.
Evaluation metrics are your test suite. And model drift is a stale cache: the world changed, your artifact didn't. You'll get the full dictionary later in this module — the point for now is that you are not starting from zero. You're learning a second dialect of a language you speak fluently.
02 · The intuitionThe Inversion: Software That Discovers Its Own Rules
You have just put numbers on the feeling from the field report: 28% more pay for one AI skill, 43% for two, and LLM/RAG postings up 340% while generic ML postings fell 18%. Those postings want an engineer who can put a model into a product, and the first thing that engineer needs is to know what a model is. Nine years of writing rules gets you most of the way there. What follows is the one idea that turns those nine years into the asset the Walmart posting describes: the inversion.
Your mental model of computing after nine years is deterministic: you write rules, the machine executes them. Data plus rules, in; output, out. When the business logic changes, you edit the code.
Machine learning takes the same three ingredients and rotates the equation a quarter turn: you supply the data and the historical outputs, and the machine computes the rules.
Those computed rules — a bundle of learned numbers called weights — are the model. That's the entire trick. Everything from linear regression to Claude is this diagram at different scales:
- The handwritten rules. Top row, the software you write now. Data goes in one door and the rules go in the other, and the rules were typed by a person: if-statements, regular expressions, SQL. The program applies the rules to the data and an output comes out. When the business changes its mind, someone edits this box.
- The past outputs. Bottom row, machine learning. The rules door is empty. In its place you feed in the historical answers: what each house actually sold for, whether each customer actually left. Data and answers go in together. This is the inversion: the thing you used to write is now something you supply examples of.
- fit(), the training step. The learning algorithm reads the data and the past answers side by side and computes the rules that best turn one into the other. In this module that is one line,
model.fit(X_train, y_train), and it takes a millisecond. Nobody types a constant. - The model. What comes out is a bundle of learned numbers, the weights, saved to a file such as
model.pkl. It is a build artifact: versioned, deployed, rolled back. When the world moves, you do not edit it; you run marker 3 again on fresh examples and ship a new one.
Put the data and the past answers in.
Let the machine compute the rules.
Ship those rules as an artifact.
Retrain when the world moves.
Data and past answers in: the two boxes at markers 1 and 2 of the bottom row of Fig. 0.1, the data and the historical outputs, both fed to the same door. Compute the rules: marker 3, the learning algorithm, which replaces the handwritten rules of the top row. Ship as an artifact: marker 4, the model file, deployed like any build. Retrain when the world moves: run marker 3 again on fresh rows and ship a new marker 4.
Why would anyone want computed rules instead of handwritten ones? Consider spam
detection, the canonical example. The handwritten version is 5,000 regex rules —
if "VIAGRA" in text: spam — and it loses the arms race the day spammers
switch to "V!AGRA". You patch, they mutate, forever. The learned version feeds 50,000
labeled emails to an algorithm that computes a probability weight for every token
automatically. When spammers mutate, you don't rewrite logic — you retrain on fresh
examples, and the new spelling gets a weight in seconds. Handwritten rules scale
with your team's patience. Learned rules scale with your data. That's the economic
argument underneath the entire field.
- The rule. One regex, one spelling. "VIAGRA cheap" matches and is sent to spam, correctly. "V!AGRA cheap" does not match, so it lands in the inbox, wrongly. The only fix is a person writing rule 5,001, and the spammer's only cost is changing one character. That is why the handwritten side loses: each move costs them nothing and costs you an edit.
- The weights. Fifty thousand emails, each already marked spam or not, go through fit(). Out comes a number per token: "viagra" pushes toward spam (+4.1), "meeting" pushes away (−2.3). Add up the weights of the tokens in a new email and you get a spam score. When "v!agra" starts appearing in the next batch of labelled mail, a retrain gives it a weight too (+3.8, made up), and the email scores 5.0, a 0.99 probability of spam. No line of logic was written; the data grew.
Now the same picture a second time, with real names in the boxes. The middle column
is learned_version.py, the 21-line script you will read and run in section 03.
The right column is the same stage as it exists in a production system: the ML
microservice of Fig. 0.2 below, built out properly in Modules 02 and 12.
You have not met X_train, fit() or model.pkl yet, and you are not expected to. Read the table for its shape: every box in Fig. 0.1 is a real file, a real call, or a real database column. Each name in the middle column is explained line by line in section 03. The production column is what Modules 02 and 12 build.
| Stage | In the five-row version (section 03) | In the production version (Fig. 0.2, Modules 02 and 12) | What flows out |
|---|---|---|---|
| Data | X_train: five houses typed by hand, three numbers each | Rows pulled from PostgreSQL by a scheduled query, one row per customer or sale | A table of features, one row per example |
| Past outputs | y_train: the five prices those houses actually sold for | A label column such as is_churned, filled in by what really happened | One correct answer per row, in the same order |
| Learning algorithm | LinearRegression(), then model.fit(X_train, y_train) | A training job on a schedule, scored on rows it never saw (Module 02) | The learned constants: model.coef_ and model.intercept_ |
| Model (weights) | Lives in memory until the script ends | Saved as model.pkl, versioned like a build, loaded at boot by the ML microservice | A deployable artifact you can roll back |
| Inference | model.predict(new_house), once, for one house | POST /predict {features} from the backend, thousands of times a second | A score, such as { "churn": 0.87 } |
| Decision | The printed price | The backend applies a threshold the business chose: "flag above 0.8" | A yes or no the product acts on |
| Retrain | Edit the five rows and run the script again | Drift monitoring (Module 07) triggers a fresh training run (Module 12) | A new artifact, and the loop repeats |
"Isn't machine learning just statistics with a marketing budget? Linear regression is two hundred years old."
— a nine-year engineer who took one statistics course, right about now
For the tabular half of the field, largely yes. Linear regression dates from about 1805. The spam filter of Fig. 0.1b, marker 2, one weight per token added up into a probability, is a calculation any statistician would recognise. Most of the machine learning that runs a business, churn scoring, fraud flags, pricing, is statistics fitted by a machine at a scale no person could manage by hand. Nobody should talk you out of that view; it is accurate.
Three things are new, and they are why the word "learning" earns its keep:
- The scale. Fitting a model over fifty million rows and a thousand columns is a systems problem before it is a statistics problem.
- The tooling. Training is a build pipeline with versioned artifacts, tests and rollbacks. That is engineering, and it is the part this course teaches.
- The deep-learning branch. Past a certain depth, the model builds its own features from raw pixels or raw text. Nobody wrote down what an edge in a photo looks like. The network found it.
The honest downside of the thing being defended: a learned model trades an explanation for a fit. The rules version in section 03 can be read line by line and argued with. A trained model gives you numbers that work and no story about why. It also needs labelled examples, meaning rows with the correct answer attached, often thousands of them, and many businesses do not have those for the question they care about.
Before reading on: a model learns its rules from historical examples — say, house sales from 2015–2023. What happens to its predictions in 2026 when interest rates and the market have shifted? And what's the closest analogy in the systems you already run?
Reveal the answer
The model keeps confidently applying 2023's rules to 2026's world — predictions degrade silently, with no exception thrown and no failing health check.
This is drift, and the closest SWE analogy is a stale cache (or config baked in at compile time): the artifact is internally consistent but the world it summarized has moved.
The fix is the same shape too — invalidate and rebuild, i.e., retrain on recent data. The deeper lesson: ML systems fail statistically, not loudly, which is why measurement (Module 07) is the spine of this course rather than an appendix.
Where it lives: the model is just another microservice
You now have the inversion: examples and answers in, rules out, as Fig. 0.1 draws it, and the spam filter of Fig. 0.1b shows why anyone would want it. The next worry is practical. You run a React frontend, a backend and Postgres, and you need to know where the learned rules would live in that stack before you can believe any of this fits the job. The answer is one more service, drawn below, and it is the reason your nine years are the asset rather than the problem.
Second load-bearing idea: adopting ML does not mean discarding your stack. Your React frontend, your FastAPI or Node backend, your Postgres database — all keep their jobs. The model shows up as one more box in the architecture diagram: a stateless service that loads a versioned artifact at boot, exposes an HTTP contract, takes features in, and returns a score. You already know how to deploy, scale, monitor, and version that box. What's new is only how the artifact inside it gets made.
Hold onto that 0.87. Models return scores, not verdicts — a
probability the backend turns into a decision by applying a threshold. Choosing that
threshold is a business decision (how many false alarms can support tolerate?), not a
modeling one. This is the first of many places where your product instincts matter as much
as the math.
- The score. The model's whole output for this customer is one number, 0.87: its estimate of the probability that they churn. It is not a decision. The model has no idea what the product will do with it.
- The threshold. A line somebody drew at 0.8. Above it, act; below it, do not. Choosing where it goes is a business question, because it trades false alarms against missed cases: at 0.8 support calls more people, some of whom were never leaving; at 0.9 it calls fewer and misses more.
- The verdict. The shaded region is everything at or above the threshold. 0.87 falls inside it, so this customer is flagged. Change the threshold and the flag can change without retraining anything, which is why it lives in the backend and not in the model.
The map: AI ⊃ ML ⊃ DL ⊃ GenAI
The learned rules now have a home in your stack: a stateless service that returns a score such as the 0.87 in Fig. 0.2, which the backend turns into a decision with the threshold of Fig. 0.2b. The job feed, though, does not say "model". It says AI, ML, deep learning and GenAI, often about the same system, and an interviewer will ask you to sort them. So the next thing you need is the map: four words, one containment, and one example of each you can say out loud.
The vocabulary problem is real: executives say "AI," data scientists say "ML," papers say "deep learning," and job postings say "GenAI" — often about the same system. The four terms nest cleanly, and being able to draw this from memory is worth an embarrassing amount in interviews:
- AI, the outer ring. Anything that makes a judgment a person used to make. The example is deliberately unglamorous: a 1980s chess engine built entirely from if-statements, with no data and no learning.
rules_version.pyin section 03 is AI in this sense too. The word says nothing about how the judgment is made. - ML, the second ring. The judgment is learned from examples, the inversion of Fig. 0.1. The example is this module's own script: five sales in, four constants out. The churn score of 0.87 from Fig. 0.2 is the same thing in production. Tables of rows are its natural food.
- Deep learning, the third ring. Still learning from examples, but the model is built from many layers, and the layers find their own features in raw input. Face unlock on a phone is the example: nobody wrote down what an edge or an eye looks like in pixels. The layers found them.
- GenAI, the innermost ring. Deep learning models trained on so much text or imagery that they can produce new content rather than only score it. The support chatbot is the everyday example, and the two hello scripts in this module's lab call one from Python. When a posting says "GenAI engineer", it means this ring.
Read Fig. 0.3 inward, marker by marker. AI (marker 1) is the marketing-sized umbrella: any technique that mimics human judgment, including a 1980s chess engine made of pure if-statements.
ML (marker 2) is the subset where rules are learned from data — the inversion you just met — and it remains the workhorse for tabular business problems: churn, fraud, pricing.
Deep learning (marker 3) stacks learned layers so the system can extract its own features from unstructured inputs like pixels and audio. GenAI (marker 4) is deep learning's newest floor: transformer models trained on internet-scale data that generate content rather than just score it.
When a posting says "GenAI engineer," it means the innermost box — but interviewers routinely walk you outward to check the foundations are real.
Three ways machines learn
You can now place the four words of Fig. 0.3. The inner three rings all learn rules from data, but they do not all learn the same way, and the way they learn decides what data you must have before you start. The house-price rows you will fit in section 03 have an answer attached to every row: the price it sold for. Not every problem in your product comes with answers attached. That is the distinction below, and it is the first question to ask about any ML feature someone proposes.
Within ML, everything you'll ever build falls into one of three paradigms, distinguished by what feedback the algorithm gets. Supervised learning is learning with an answer key: every historical example carries its true outcome, and the model learns to map features to answers.
Predicting a category is classification (churn / no churn; spam / inbox / promotions); predicting a number is regression (this house: $450,000).
It's roughly 80% of industrial ML. Unsupervised learning gets no answer key — just raw data — and finds structure you didn't specify: clustering a million users into four behavioral personas, or compressing 1,000 features into a few meaningful axes.
Reinforcement learning learns by trial and reward: an agent acts, the environment scores it, and behavior that scores well gets reinforced — the paradigm behind game-playing AI and, notably, the final training stage of the LLMs you'll use daily.
- Supervised. Every dot has its price written beside it. That written answer is the label, and it is what the algorithm learns to reproduce. Here it finds the line through the five points, and the line prices any new house. Roughly 80% of business ML looks like this, because businesses have history: what sold, who left, which payment was fraud.
- Unsupervised. Ten customers plotted by minutes on site and orders a month, with nothing written beside them. There is no answer to reproduce. The algorithm's job is to find structure, and here it finds two groups. A person then names them: group A browses and rarely buys, group B buys quickly. Clustering a million users into four personas is this picture at scale.
- Reinforcement. No dataset at all. The agent acts, the environment scores the action, and behaviour that scores well is made more likely. A chess engine gets +1 for a win. The final training stage of the chat models you use every day is the same loop: a reply a human preferred scores higher, and the model shifts toward it.
The Rosetta Stone
You have the inversion, the service, the map and the three ways of learning. What is left before you write code is the vocabulary: the ML repo you opened in the field report was full of words like feature, label, inference and drift, and every one of them names something you already run. The dictionary below is the translation promised in the hook, drawn first as arrows and then as a table you can pin.
Finally, the promised dictionary. Pin this mentally; the rest of the course assumes it:
- The data words. A sample is a row. A feature is a column used to predict. A label is the column you are trying to predict, the answer a function would be expected to return. The house-price script in section 03 has five samples, three features and one label per row.
- The build words. Training is the build pipeline; the model file is the binary it produces; a hyperparameter is a setting fixed before the build starts, like a compiler flag. The accented arrow is the one the whole inversion hangs on: the build no longer compiles rules you wrote, it computes them.
- The run words. An evaluation metric is your test suite, a number that says whether the artifact is good enough to ship. Inference is a function call against the deployed artifact. Drift is a stale cache: the artifact is unchanged, but the world it summarised has moved.
| Your world | ML term | Plain meaning |
|---|---|---|
| Database row | Sample / data point | One record — one user, one transaction |
| Table column | Feature | An attribute used to predict — age, income |
| Function's expected return | Label / target | The thing you want to predict — is_churned |
| Compiled binary | Model file (.pkl, .pt) | The frozen learned rules, ready to serve |
| Build pipeline | Training | The compute job that produces the model |
| Build-time config | Hyperparameter | Settings you choose before training — learning_rate=0.01 |
| Test suite | Evaluation metric | How you measure quality — accuracy, ROC-AUC, MSE |
| Function call | Inference / prediction | New data in, answer out |
| Stale cache | Model drift | The world changed; the artifact didn't |
Questions you might be asking now
The last few screens handed you a map, three kinds of learning and nine dictionary words, each in a line or two. If one of them did not land, open the question that matches yours. Every answer uses the same four suburb houses, small enough to check with a pencil.
| House | Square feet | Sold for |
|---|---|---|
| A | 800 | $220,000 |
| B | 1,500 | $325,000 |
| C | 2,400 | $460,000 |
| D | 1,800 | not sold yet |
The page keeps writing "AI/ML". Is AI the same thing as ML?
No. AI is any program that makes a judgment a person used to make. ML is the part of AI where the program's numbers are computed from examples. So price = 100,000 + 150 × sq ft is AI but not ML when a person typed the 150. It is ML when fit() computed the 150 from houses A, B and C.
The two words get merged because nearly all the AI in the news is ML. They still name different things. Fig. 0.3 draws ML as a ring inside AI. The quickest way to feel where the border runs is to write one program twice.
Program 1 is the software you already write. A person studies the local market, decides that a house costs $100,000 plus $150 a square foot, and types those two numbers in. Program 2 has the same line of code. Its two numbers, though, come out of fit(), computed from the three sales.
You can check that fit() has to land on the same two numbers, using the subtraction from the "BE the model" exercise in section 03:
- Find the price per square foot. From house A to house C the size grows by 2,400 − 800 = 1,600 square feet, and the price by $460,000 − $220,000 = $240,000. So each square foot adds 240,000 ÷ 1,600 = $150.
- Find the base price. House A's 800 square feet account for 150 × 800 = $120,000 of its $220,000. The rest, 220,000 − 120,000 = $100,000, is the base.
- Check on house B. 100,000 + 150 × 1,500 = $325,000, exactly what B sold for.
- Compare with the code.
LinearRegression().fit()on the same three rows prints 150.0000 and 100,000.0000.
| Program 1: typed rule | Program 2: fitted rule | |
|---|---|---|
| The code that prices a house | 100_000 + 150 * sqft | model.predict([[sqft]]), which computes 100,000 + 150 × sq ft |
| Where 100,000 and 150 came from | A person chose them | fit() computed them from houses A, B and C |
| Price for house D | 100,000 + 150 × 1,800 = $370,000 | The same $370,000 |
| Is it AI? | Yes: it makes a pricing judgment | Yes |
| Is it ML? | No: nothing was learned from examples | Yes: its numbers were learned from three sales |
| A 2026 sale E arrives: 2,000 sq ft, sold for $430,000 (made up) | Nothing changes until a person edits the code. D stays at $370,000, and E is missed by $30,000 | Rerun fit() on A, B, C and E: $156.83 a square foot and a base of $96,060. D becomes $378,354 |
| Loss on A, B, C and E (each miss squared, then added) | 0.90 billion | 0.61 billion |
Fig. 0.3k draws the two programs twice: today, and on the day sale E arrives.
- The typed rule. Both numbers were chosen by a person. The program makes a pricing judgment, so it is AI. Nothing in it was learned from examples, so it is not ML. It prices house D at $370,000.
- The fitted rule. The same line, but fit() computed 150 and 100,000 from the three sales. It also prices house D at $370,000. On this day no test can tell the two programs apart, which is why "AI" and "ML" blur together in conversation.
- The day the data changes. A made-up 2026 sale, E, lands $30,000 above the old line. The typed rule does not notice until someone edits it. Rerunning fit() moves the numbers to 96,060 and 156.83, and house D to $378,354. The whole difference between the two words lives in this bottom half.
On the day the top half was drawn, the two programs are identical, and no test you could write would tell them apart. The difference shows only when the data changes. That is what the word "learning" is about: where a program's numbers come from, not what its code looks like.
Deep learning and GenAI sit inside ML, as markers 3 and 4 of Fig. 0.3 show. Their numbers are also computed from examples. They simply have billions of numbers instead of two, and they read pixels or text instead of a square-foot column. So every LLM is ML and every ML model is AI, but rules_version.py is AI and not ML.
Two honest caveats. In job posts and press releases, "AI" now usually means GenAI, so read the word by its context, not by the rings. And real products mix both kinds. The churn service of Fig. 0.2b is ML up to its score of 0.87, and a typed rule after that, because a person chose the threshold of 0.8.
AI names what a program does: it makes a judgment. ML names where the program's numbers came from: examples. A program is ML only if training on new rows can change its numbers.
What exactly are a sample, a feature, a label, a model and a prediction? Point at them in one row.
Sample, feature and label are parts of the data: one row, a column you know in advance, and the column you want to predict. The model is the numbers learned from that data, here 100,000 and 150. A prediction is what those numbers say for one row, such as $370,000 for house D, which has no label yet.
The dictionary above gave each word one line. Here the same words point at real cells of the four-house table at the top of this block. Read that table the way an ML repo would: every row is one past event, and one column is the thing you wish you had known in advance.
| Word | Plain meaning | House B | House D | learned_version.py |
|---|---|---|---|---|
| Sample (also example, data point) | One record: one thing that happened | 1,500 sq ft, sold for $325,000 | 1,800 sq ft, not sold | One row of X_train with its price |
| Feature (the X columns) | A value you know before the answer exists | 1,500 | 1,800 | Three per row: sq ft, bedrooms, the San Francisco flag |
| Label, or target (the y column) | The answer the model should reproduce | $325,000 | Unknown, which is why you want a model | y_train, the five sale prices |
| Model | The formula plus the numbers training put in it | 100,000 + 150 × sq ft | The same model | −94.81, 236,494 and 479,545, plus a base of −184,805 |
| Prediction (the output of inference) | What the model says for one row | 100,000 + 150 × 1,500 = $325,000 | 100,000 + 150 × 1,800 = $370,000 | $833,571 for the new house |
| Miss (also error, residual) | Prediction minus label, so it needs a label | 325,000 − 325,000 = $0 | Cannot be worked out until D sells | −$35,390 on house 3 |
Fig. 0.3l draws the same mapping on the table itself.
- Sample. One row: house B, 1,500 square feet, sold for $325,000. Libraries and papers also say example, data point or observation. Training data is a pile of samples;
X_trainin section 03 holds five. - Feature. A column you know before the answer exists, here square feet. The feature columns together are called X. It means an input to the model, not a feature of your product.
- Label. The column the model should learn to reproduce, here the sale price. It is also called the target, and in code it is y. House D's cell is a question mark because D has not sold.
- Model. The formula plus the numbers fit() put into it: 100,000 and 150. It is not the library and not the data. It is what training leaves behind, the part that gets saved to a file and deployed.
- Prediction. What the model says for a row: 100,000 + 150 × 1,800 = $370,000 for house D. For A, B and C the prediction equals the label, so every miss is $0. That happens only because these three sales sit exactly on a straight line.
Two of these words trip up engineers in particular. A feature is not a product feature; it is an input column. A label is not text on a button; it is the answer column. When an ML colleague says "we added a feature", they mean the model now reads one more column.
In code, the feature columns are called X and the label column y. So fit(X, y) means "learn from rows where both are known", and predict(X) means "fill in y for rows where it is missing". Those two calls are training and inference. The anatomy of fit and predict in section 03 takes them apart token by token.
The honest limit of this tidy picture is house B's miss of $0. It is zero only because A, B and C sit exactly on one straight line, and real rows never do. The fitted model in section 03 misses its own training house 3 by $35,390, as panel 1 of Fig. 0.3i shows.
One more thing the words hide: a column is only a usable feature if you know it at the moment you predict. "Days on the market" is known for A, B and C, but not for house D on the day it is listed. A model that learned from it could not price D. That mistake is called leakage, and Module 02 takes it apart.
Features are what you know now, and the label is what you want to know. The model is the numbers learned from rows that have both. A prediction is the model's answer for a row that has only features.
What does it actually mean that the model "learned" 150? Show me with numbers small enough to check.
It means trying numbers, scoring each try by how badly it misses the prices you already know, and keeping the try that misses least. On houses A, B and C, a price per square foot of 100 scores 21,625, 125 scores 5,406, and 150 scores 0. So 150 is the number that gets learned.
To keep a single dial, hold the base price at $100,000 and let only the price per square foot change. Call that dial w, for weight. Training asks one question about every value w could take: had we used this number, how wrong would we have been on the houses whose prices we already know?
The answer is a single number called the loss. Here it is for w = 100, worked in thousands of dollars so that every number stays small.
- Price the three sold houses. House A: 100,000 + 100 × 800 = $180,000. House B: 100,000 + 100 × 1,500 = $250,000. House C: 100,000 + 100 × 2,400 = $340,000.
- Subtract what each one sold for. A: 180 − 220 = −40. B: 250 − 325 = −75. C: 340 − 460 = −120. All three prices are too low, and the biggest house is the furthest off.
- Square each miss. (−40)² = 1,600, (−75)² = 5,625 and (−120)² = 14,400. Squaring makes every miss positive, so a price that is too low and one that is too high cannot cancel out.
- Add the squares. 1,600 + 5,625 + 14,400 = 21,625. That is the loss for w = 100. In plain dollars it is 21.6 billion, the same kind of number as the 128.05 billion you will compute for the hand-written rule in section 03.
| w, price per sq ft | Misses for A, B, C | Squares | Loss |
|---|---|---|---|
| 100 | −40, −75, −120 | 1,600 + 5,625 + 14,400 | 21,625 |
| 125 | −20, −37.5, −60 | 400 + 1,406.25 + 3,600 | 5,406.25 |
| 150 | 0, 0, 0 | 0 + 0 + 0 | 0 |
| 175 | +20, +37.5, +60 | 400 + 1,406.25 + 3,600 | 5,406.25 |
| 200 | +40, +75, +120 | 1,600 + 5,625 + 14,400 | 21,625 |
Read the Loss values from top to bottom. They fall, reach 0 at 150, and rise again. A w that is too small prices every house short; a w that is too big prices every house over. "The model learned 150" means exactly this: 150 is the setting of the dial where the loss is smallest. Fig. 0.3m draws the five tries.
- Two tries on the data. The dots are houses A, B and C at their real sale prices. The accented line is w = 150, and it passes through all three. The dashed line is w = 100: the $100,000 base plus $100 a square foot. It runs under every dot.
- The misses. The short vertical bars are what w = 100 gets wrong: $40,000 short on A, $75,000 on B and $120,000 on C. The bigger the house, the bigger the miss, because the missing $50 a square foot is multiplied by more square feet.
- The loss for each try. Each dot is one value of w and its loss: the three misses squared and added. w = 100 and w = 200 both score 21,625; 125 and 175 both score 5,406.25. The curve joins the losses of every w in between, which work out to 8.65 × (w − 150)².
- What "learned" means. The lowest point is at w = 150, with a loss of 0. Training is the search for that lowest point. Here it reaches exactly 0 because the three sales sit on a straight line; on the five houses of learned_version.py the lowest loss fit() can reach is 7.71 billion.
Three honest limits to this picture:
- fit() does not try five values. For a straight-line model there is a formula that lands on the lowest point in one step, and section 07 names it. On these rows it prints 150.0000 and 100,000.0000, the same answer.
- Real models turn more than one dial. The base was held at $100,000 here so that the picture has one dial. fit() turns both at once, and learned_version.py turns four. The idea does not change: find the numbers where the loss is lowest.
- Big models have to walk downhill. A neural network has no one-step formula. It starts from some numbers, works out which way the loss slopes, and takes many small steps down. That walk is called gradient descent, and Module 02 builds it in under 30 lines.
A model "learns" a number by choosing, from all the numbers it could use, the one whose misses on examples with known answers add up to the smallest loss.
03 · Build it yourselfThe Same Problem, Both Paradigms
Everything so far has been pictures and words. You are an engineer, and the field report asked what machine learning is, fundamentally. The honest answer is code you can run. So the next event is the same house-pricing problem written twice: once the way you would write it today, with constants chosen in a meeting, and once with the constants computed from five past sales. The two numbers the versions print for the same house, $1,075,000 against $833,571, carry the rest of this module.
Enough diagrams — let's feel the inversion in code. Same problem twice: estimate a house price from square footage, bedrooms, and city. First, the version you'd write today. It's genuinely fine code. That's what makes it a trap.
Before you read either file, a pencil exercise. You have not been taught scikit-learn, and nothing on this page has explained np.array or fit() yet. That is on purpose. Guess first, then check. Every line in the table is explained in full by the step-by-step list above each file and the paragraphs after it, and the three lines that matter most get their own anatomy a little further down.
Step-by-step: what rules_version.py does, in plain English
- No imports. This is plain Python; nothing needs installing.
- Define
predict_house_price, a function that takes three facts about a house (square feet, bedroom count, city name) and returns a price. The: floatand-> floatparts are type hints: notes for the reader and for tools, not enforced when the code runs. - The docstring, the quoted sentence under the function name, records the honest truth about the file: every number in it was argued for by a person.
- Set
baseto 100,000, the price of a house before anything about it is known. The underscore in100_000.0is only for readability; Python ignores it. - Compute
total: the base, plus 150 dollars for every square foot, plus 20,000 dollars for every bedroom. Three constants, three guesses. - If the city is San Francisco, multiply the total by 2.5; if it is New York, by 2.1. Every other city gets no adjustment, because nobody wrote a rule for it. The comments record when each rule was added and why.
- Return the total.
- Call the function for an 1,800 square foot, three-bedroom San Francisco house and print the result with thousands separators and no decimals:
$1,075,000.
# No installs — this is the software you already write.
def predict_house_price(sqft: float, bedrooms: int, city: str) -> float:
"""Every constant below is a guess a human argued for in a meeting."""
base = 100_000.0
total = base + sqft * 150.0 + bedrooms * 20_000.0
if city == "San Francisco": # rule 3, added after launch
total *= 2.5
elif city == "New York": # rule 4, added after a support ticket
total *= 2.1
return total # rules 5 through 5,000 never got written
print(f"${predict_house_price(1800, 3, 'San Francisco'):,.0f}")
Where did 150.0 come from? A hunch. The 2.5 multiplier? A
meeting. Every constant is a hardcoded opinion, every new city is a code change, and no
interaction between variables (does an extra bedroom matter more in SF?) is
captured unless someone writes it by hand. Now the inverted version — we hand over five
historical sales and their actual prices, and ask the machine to compute the constants:
Step-by-step: what learned_version.py does, in plain English
- The first line is a comment holding the install command,
uv add "scikit-learn>=1.5,<2". numpy, the array library, is installed along with it. - Import numpy as
np, which gives you grids of numbers with fast arithmetic, andLinearRegression, the algorithm that fits a weighted sum to data. - Build
X_train: five historical houses, one per row, three columns per row: square feet, bedrooms, and 1 for San Francisco or 0 for anywhere else. This is the "Data" box in Fig. 0.1. By convention the features are called X. - Build
y_train: the five actual sale prices, in the same order as the rows. This is the "Past outputs" box. By convention the answers are called y. - Create a
LinearRegressionmodel. Nothing has been computed yet; the object holds no constants. - Call
model.fit(X_train, y_train). This is training: the algorithm finds the three weights and one base value that come closest to reproducing the five prices from the five rows, and stores them on the model. It finishes in milliseconds. - Describe one new house the same way, as a grid with one row: 1,800 square feet, three bedrooms, San Francisco.
- Print
model.coef_, the three learned weights (dollars per square foot, dollars per bedroom, the San Francisco premium), andmodel.intercept_, the learned base price. - Print
model.predict(new_house)[0]: the model multiplies the new row by the weights, adds the intercept, and returns one number per row;[0]takes the only one.
# uv add "scikit-learn>=1.5,<2" (numpy comes along as a dependency)
import numpy as np
from sklearn.linear_model import LinearRegression
# Historical sales — features X: [sqft, bedrooms, is_san_francisco]
X_train = np.array([
[1000, 2, 0],
[1500, 3, 0],
[2000, 3, 1],
[800, 1, 1],
[2500, 4, 0],
])
y_train = np.array([250_000, 340_000, 850_000, 420_000, 510_000]) # actual prices
model = LinearRegression()
model.fit(X_train, y_train) # <- "training": the constants get COMPUTED here
new_house = np.array([[1800, 3, 1]]) # 1800 sqft, 3 bed, San Francisco
print(f"learned weights: {model.coef_}") # $/sqft, $/bedroom, SF premium
print(f"learned intercept: ${model.intercept_:,.0f}")
print(f"prediction: ${model.predict(new_house)[0]:,.0f}")
Run it and look at model.coef_: three numbers — a learned dollars-per-sqft,
a learned bedroom premium, a learned San Francisco markup. The structure is identical to
your handwritten function; the difference is authorship. fit() found
the constants that best explain the historical data, in milliseconds, and will find new
ones the moment you retrain with fresh sales. You didn't stop being the engineer — you
moved up one level, from writing the rules to designing the system that writes the
rules.
Here is what the run prints, rounded. The learned weights are about −94.81 dollars per square foot, 236,494 dollars per bedroom, and a 479,545 dollar San Francisco premium. The intercept, the learned base price, is about −184,805. The prediction for the new house is $833,571, against the $1,075,000 the hand-written rules gave for the same house.
- X_train, the features. Five houses, one per row, three numbers each: square feet, bedrooms, and 1 if the house is in San Francisco. This is the "Data" box of Fig. 0.1. The model never sees a city name, only that flag.
- y_train, the answers. What each of the five houses actually sold for, in the same order as the rows. This is the "Past outputs" box of Fig. 0.1, the thing you supply instead of rules.
- The learned constants. fit() reads the two grids together and computes one number per column plus a base. Two of them are negative: −94.81 dollars per square foot and a base price of −184,805. They are the closest any weighted sum can get to the five prices, and they are not facts about houses; Fig. 0.3e shows why they came out that way.
- predict(), the arithmetic. Multiply the new house's three numbers by the three weights, add the base, and read off $833,571. The bottom two lines of the picture are the whole computation. Nothing is learned here; the same row in a year would give the same number unless you retrain.
Two of those numbers should bother you. A negative price per square foot and a negative base price are not facts about houses. They are what happens when five examples are asked to pin down four constants: in these rows, bedrooms and square feet rise together, so the algorithm let the bedroom weight carry the size effect and pushed the square-foot weight below zero. The fit is the best possible for these five rows, and it is wrong about the world. Hold that thought.
- The tangle. Each dot is a training house placed by its square feet and its bedroom count. They line up: the bigger house has more bedrooms every time except one. Two columns that always rise together are, to a fitting algorithm, almost one column, and it is free to split the size effect between them any way that reproduces the five prices.
- The split. For the 1,800 square foot, three-bedroom house, the bedroom weight contributes +$709,481 and the square-foot weight −$170,649. Together they say about $539,000 for size, which is reasonable. Separately, each is nonsense: a bedroom is not worth $236,494 and a square foot is not worth less than nothing. Five rows could not rule that out. This is what "wrong about the world, right about the data" looks like, and Module 02 is where you learn to catch it.
model = LinearRegression()1
model.fit(2X_train3, y_train4)
price = model.predict(5new_house6)[0]7
- The untrained model.
LinearRegression()builds an object that knows the algorithm but holds no constants yet. Anything you would set before training, the hyperparameters from the dictionary above, goes inside these parentheses. The mistake: assuming the constructor has looked at any data. It has not;model.coef_does not even exist until step 2 runs. - fit is training. One call reads every row of X and every answer in y, computes the weights that reproduce the answers most closely, and stores them on the object as
coef_andintercept_. It changes the model in place and returns that same model. The mistake: fitting on rows you will later test on, so the score you measure is a memory test, not a prediction test. Module 02 is built around avoiding this. - X, the features. A grid: one row per example, one column per feature, shape (5, 3) here. Capital X is the convention for the grid. The mistake: passing a flat list for a single feature. scikit-learn refuses it with "Expected 2D array, got 1D array instead"; the fix is
.reshape(-1, 1). - y, the answers. A flat list with one correct answer per row of X, in the same order. Lower-case y is the convention. The mistake: a shuffle or filter applied to X but not to y, so row 3's features are paired with row 4's price. Nothing errors; the model quietly learns nonsense.
- predict is inference. It multiplies the new row by the learned weights and adds the intercept. Nothing is learned here; predicting a thousand houses changes the model not at all. The mistake: calling it before fit, which raises
NotFittedErrorwith the message "This LinearRegression instance is not fitted yet". - The new row. Same three columns, same order, same units as
X_train: sqft, bedrooms, is-SF. Double brackets, because predict expects a grid of rows even when there is only one. The mistake: swapping the column order. The model cannot tell; it returns a confident, wrong number. - The [0]. predict returns one prediction per row, as an array, even for a single row.
[0]takes the first. The mistake: formatting the whole array with:,.0f, which fails with "unsupported format string passed to numpy.ndarray.__format__".
Before reading on: would you trust this model's prediction enough to price a real listing? It learned from five examples. What would you, as an engineer, demand to see before shipping it?
Reveal the answer
No — and your instincts already know why. Five samples can be explained by many different weight combinations, most of them wrong about the world (with so few examples, the model can essentially memorize them — the failure mode ML calls overfitting).
What you'd demand is exactly what ML practice demands: held-out data the model never saw during training, and a measured error on it.
That's the train/test split, and it's the load-bearing habit of Module 02 — the ML equivalent of "no merge without passing tests on a clean environment."
- The money. Ten thousand calls at a cent each is $100 a day, $36,500 a year, for one question. Ten thousand calls to the fitted model is a cent a day; on the same scale its bar is a hairline. Neither number is large until you multiply by the number of questions a product asks.
- The waiting. At about a second per call, ten thousand calls is nearly three hours of model time a day, and each user waits that second. The fitted model answers in under a millisecond, ten seconds for the whole day. For a fraud check that must happen before the payment goes through, the second is not available.
"Why would I learn scikit-learn at all? I could paste those five rows into Claude and ask it for a price."
— an engineer who has shipped two chat features this year, right about now
You could, and for a one-off question in a chat window it is a fine way to get a rough number. The model would read the five rows, notice that San Francisco houses cost more, and hand back something plausible. That is the strength of a language model: it takes a problem in whatever shape you hand it, with no training step at all.
It is the wrong tool the moment the question is asked ten thousand times a day. Each call costs a fraction of a cent and takes about a second, where the fitted model costs nothing measurable and answers in under a millisecond. Fig. 0.3h above adds that up for one day of traffic: marker 1 is the money, marker 2 is the waiting. The language model's number can also change between two identical calls, so you cannot test it the way you test a function.
Worse, it gives you no error score. You cannot say how wrong it is on average, which is the one thing the business will ask. The decision table below is the short version of this argument, and the whole of Module 07 is the long version.
The honest downside of the fitted model: it needs a clean table with a label column, it can only see the columns you gave it, and it cannot read a sentence. The moment the input is a support ticket rather than a row, the language model wins, and that is where Act III of this course lives.
One more thing before you file "classical ML" under legacy: knowing when a $0.000001 linear model beats a $0.01 LLM call is precisely the judgment interviews probe. Here's the decision surface as of August 2026:
| Option | Choose when | Avoid when | Typical cost per call |
|---|---|---|---|
| Handwritten rules | Logic is simple, stable, and must be exactly auditable (tax brackets, feature flags) | Patterns are fuzzy, adversarial, or change faster than your team can patch | ~free, sub-ms |
| Classical ML (sklearn, XGBoost) | Tabular data with labeled history: churn, fraud, pricing; tight latency or interpretability requirements | Inputs are free text, images, or audio; little labeled data exists | ~free, sub-ms self-hosted |
| Deep learning (PyTorch) | Unstructured inputs at scale and you own the training problem (vision QC, speech) | A pretrained API already solves it cheaper than building | GPU serving; ms–100ms |
| GenAI via LLM API | Language understanding or generation, reasoning over documents, tool-using agents | High-volume scoring of tabular data; strict determinism required | ~$0.001–0.05 per call, 0.5–5s |
Before the two of them argue, look at what each one actually did. Every line of the chat below points at one of the four panels of this picture: the same five sales scored by both, the constants side by side, the city neither was told about, and what happens when the world moves.
- Scored by both. Each row is one training house. "Rules say" is what
predict_house_price()returns for it; "model says" is whatmodel.predict()returns. The rule misses high every time, and by $180,000 on house 4. The model misses both ways and by less: $36,805 a house on average, against $122,000. Its loss, the squared and summed misses of Fig. 0.3g, is 7.71 billion against 128.05. - Side by side. The rule's four constants were chosen by people and can be read aloud as a policy: a base of 100,000, $150 a square foot, $20,000 a bedroom, times 2.5 in San Francisco. The model's four were computed from five rows in a millisecond, and two of them are negative, which Fig. 0.3e explains. The × 2.5 is what turned a $240,000 guess for house 4 into $600,000.
- The city with no rule. The if-chain has branches for San Francisco and New York and an else that does nothing, so a Denver house gets $430,000 with no adjustment, and a reviewer can see the missing branch. The model has never seen a Denver row and answers anyway: $354,026, computed from the same four constants with the San Francisco flag at 0. Nobody can see, from the constants, that Denver is missing.
- When the world moves, and the threshold. A model trained on 2015 to 2023 sales keeps answering in 2026 with 2023's constants, returning 200 OK the whole time. Fixing a rule is an edit with a readable diff; fixing a model is a retrain with new constants and no diff. Underneath: the model's output is a score such as 0.87; whether that means "flag" depends on a threshold someone wrote down, here 0.8.
Tonight's talk: Hand-written Rules and The Trained Model argue over the question, "Who's more important?"
Let's start with what I am: readable. Panel 2 of Fig. 0.3i, left column: 100,000, then 150, then 20,000, then times 2.5. Every constant in me was put there by a person, and every one can be read back. When the tax office asks why a customer was charged 22%, I point at the line. When a loan is declined, I can print the reason in words. You are the right column: four numbers, two of them negative, and it took the page a whole picture to explain why.
the hand-written rules are readable because a person chose each number and can say why. The learned constants in the right column of panel 2 are a fit, not a policy, and two of them make no sense as facts about houses.
Nobody has to explain me. They have to measure me. Panel 1: on those five sales I am wrong by $36,805 per house on average; you are wrong by $122,000. Look at house 4. You priced a $420,000 house at $600,000, and a person spent a whole meeting choosing the 2.5 that did it. I found my constants in a millisecond, and I will find new ones the day the market moves.
the model's defence is its score. Panel 1 puts both sets of misses on the same five rows, and the model's average miss is less than a third of the rule's. House 4 is the rule's worst miss, and the × 2.5 multiplier caused it.
The day the market moves, panel 4: I get edited, reviewed, and deployed, and the diff shows exactly what changed. You get retrained, and nobody can diff you. Your constants shifted and no one can say which of the new rows did it. I am also deterministic: same input, same output, forever, which is the property every unit test in the building depends on.
when reality changes, a rule is changed by a visible edit that a reviewer can read line by line. A model is retrained, and its new constants cannot be traced back to any particular row.
I am deterministic too, once trained. Do not confuse me with the chat models upstairs. The difference between us is panel 3: the case nobody wrote a rule for. Denver, Austin, any city not in your if-chain: you fall through to the else, apply no adjustment at all, and move on. Your own comment admits rules 5 through 5,000 never got written. I do not need a Denver branch. I need Denver rows in the training data, and then nobody writes a line.
a trained model gives the same answer for the same input every time, like a function. The difference is what happens for an input the rules never covered: the rule falls through to "else", while the model would need examples of that case in its data.
And until those rows exist, you give Denver a confident number: $354,026, right there in panel 3, built on a negative price per square foot. That is the most dangerous kind of answer there is. When I am wrong, the wrong line is in the diff, and a reviewer can read the if-chain and see that Denver is missing. You fail statistically. Panel 4, top: you returned 200 OK all through 2026 with 2023's constants inside you, and no health check noticed.
a model never refuses to answer. It priced a Denver house it had never seen, and it would keep serving stale answers after the market moved, with no error to catch. That silent failure is called drift.
Which is why I ship with a test suite of my own, and it is not a unit test. It is a held-out set of rows I never trained on, and an error score on them: the same kind of number as the $36,805 in panel 1, but measured on rows I have not seen, so it cannot flatter me. Give me fifty thousand rows and a measured error, and I will hold it while you are still arguing about the Denver multiplier. You lost the spam arms race of Fig. 0.1b the day the spelling changed. I learned the new spelling from the next batch of mail.
the model's safeguard is measurement on rows it did not train on. With enough rows and a tracked error, it adapts to change by retraining, which the spam example showed: the new spelling got a weight instead of a new regex.
Fifty thousand labelled rows. Say that slowly. Who labelled them? For the tax brackets, for the feature flags, for the rule that says orders over $10,000 need a second signature, there are no fifty thousand examples. There is a policy, and I am the policy written down. You cannot learn a rule that has no history, and half the rules that matter have none.
learning needs examples with the right answer attached. Many business rules are decisions, not patterns in past data, so there is nothing to learn them from; they have to be written.
Agreed, and I would not want them. Keep the tax brackets. But the decision table above is honest about where the line sits. When the logic is simple and stable and must be audited, you win. When the pattern is fuzzy, adversarial, or changes faster than a team can patch it, I win, and you know it, because that is what 5,000 spam regexes were before they were retired.
each side has a home. Stable, auditable logic stays hand-written; fuzzy patterns that keep changing, like spam, are learned. The decision table is the short version of this argument.
Then let us at least agree on where the threshold lives. Bottom of panel 4: you return 0.87. Someone has to decide that anything above 0.8 gets flagged. That someone writes a rule.
a model outputs a score. Turning the score into an action needs a cut-off, and the cut-off is a hand-written rule chosen by the business, not by the model.
The threshold is yours. The score is mine. We will revisit who's more important when the drift monitor pages someone at three in the morning.
the two are partners: the model produces the number, a rule decides what to do with it. Drift, the silent failure at the top of panel 4, is the problem they will meet together.
It will page you. It always pages you.
when predictions go stale, it is the model that needs retraining, not the rule.
Questions you might be asking now
The chat above argued over the numbers in Fig. 0.3i. Three things in it went by fast: the negative price per square foot, the "held-out set" the model boasts about, and the path one house takes through a real service. Every answer uses the five houses of learned_version.py, and every number comes from rerunning five_rows_under_test.py or one_house_end_to_end.py.
| House | Sq ft | Bedrooms | In San Francisco | Sold for | fit() says | Miss |
|---|---|---|---|---|---|---|
| h1 | 1,000 | 2 | no (0) | $250,000 | $193,377 | −$56,623 |
| h2 | 1,500 | 3 | no (0) | $340,000 | $382,468 | +$42,468 |
| h3 | 2,000 | 3 | yes (1) | $850,000 | $814,610 | −$35,390 |
| h4 | 800 | 1 | yes (1) | $420,000 | $455,390 | +$35,390 |
| h5 | 2,500 | 4 | no (0) | $510,000 | $524,156 | +$14,156 |
Why did fit() come out with a negative price per square foot? What is "five examples asked to pin down four constants" really saying?
It is saying that these five rows cannot tell square feet and bedrooms apart, because the two rise together almost in lockstep. Many different splits of credit between them fit nearly as well, and fit() returns the lowest-loss split, however strange. Remove square feet from the model entirely and the loss only rises from 7.71 to 8.29 billion.
The sentence under Fig. 0.3d packs four steps into one breath. Each step is true on its own. The fourth is the one that surprises people.
- Four constants, five rows. fit() must choose a price per square foot, a price per bedroom, a San Francisco premium and a base. Five sales is only one row more than the number of choices.
- Two columns move together. In these rows a bigger house nearly always has more bedrooms.
- So credit can slide between them. Take some dollars away from square feet, give them to bedrooms, and the five predictions barely change.
- fit() picks the lowest loss, not the sensible answer. If a negative square-foot price scores a little better on these five rows, fit() returns it. It has no idea what a house is.
Do square feet and bedrooms really rise together?
Sort the houses by size and read their bedrooms. h4 has 800 square feet and 1 bedroom, h1 has 1,000 and 2, h2 has 1,500 and 3, h3 has 2,000 and 3, and h5 has 2,500 and 4. Not once does a bigger house have fewer bedrooms.
The usual single number for this is the correlation: a score from −1 to +1 for how closely two columns rise and fall together. +1 means one column is an exact straight-line function of the other; 0 means there is no straight-line pattern at all. For square feet and bedrooms in these five rows it is 0.94.
How much worse would sensible constants fit?
Now force the constants to be sensible, and let fit() do its best with whatever freedom is left. Each row below is a real least-squares fit under one restriction. It is scored with the same loss as the pencil exercise above: each miss squared, then added.
| Restriction | Per sq ft | Per bedroom | San Francisco | Base | Loss |
|---|---|---|---|---|---|
| None: what fit() returned | −94.81 | +236,494 | +479,545 | −184,805 | 7.71 billion |
| Square feet removed | 0 | +172,500 | +440,833 | −150,833 | 8.29 billion |
| Square feet forced to $150 | +150 | +71,250 | +379,583 | −97,083 | 11.56 billion |
| Bedrooms removed | +243.64 | 0 | +333,304 | −39,399 | 15.32 billion |
| The hand-written rule | +150 | +20,000 | × 2.5 | +100,000 | 128.05 billion |
Compare the first two rows. Removing square feet from the model altogether raises the loss from 7.71 to 8.29 billion, only 7.5% more. Almost everything square feet could explain, bedrooms already explain. That is what "almost one column" means in marker 1 of Fig. 0.3e.
Removing bedrooms instead costs far more, 15.32 billion, and the square-foot price turns a sensible +243.64. So the data does carry size information. It just cannot say which of the two columns should be paid for it.
You can check the second row with a pencil. Its constants are $172,500 per bedroom, $440,833 for San Francisco and a base of −$150,833.
| House | Working | Prediction | Miss | Miss squared |
|---|---|---|---|---|
| h1 | −150,833 + 172,500 × 2 | $194,167 | −$55,833 | 3.117 billion |
| h2 | −150,833 + 172,500 × 3 | $366,667 | +$26,667 | 0.711 billion |
| h3 | −150,833 + 172,500 × 3 + 440,833 | $807,500 | −$42,500 | 1.806 billion |
| h4 | −150,833 + 172,500 × 1 + 440,833 | $462,500 | +$42,500 | 1.806 billion |
| h5 | −150,833 + 172,500 × 4 | $539,167 | +$29,167 | 0.851 billion |
| Loss | 3.117 + 0.711 + 1.806 + 1.806 + 0.851 | 8.29 billion |
The swing test: leave one house out
A second way to see the same thing is to remove one house and fit again on the other four. If five rows really pinned the constants down, removing one would barely move them. Fig. 0.3n shows where the price per square foot lands each time.
- One house removed at a time. Each dot above the axis is fit() rerun on four of the five houses. Four constants and four rows means the fit is exact: each of these models prices its own four houses to the dollar. What moves is the constants themselves.
- Without h3, or without h4: +160. Drop either San Francisco house and the price per square foot comes out a sensible $160, with $10,000 a bedroom. Those constants look like a policy someone could defend. They are just as much an accident of which rows were kept.
- All five: −94.81. The number learned_version.py printed. It sits among the four-house values, close to the two negative ones. Nothing about it deserves more trust than the others.
- Without h5: +1,250. Remove the biggest house and the credit flips. A square foot becomes worth more than eight times the rule's $150, and each bedroom now takes $535,000 away. With so few rows, the same four constants can land almost anywhere.
The negative weight does little harm on houses that look like the five training houses, because there the bedroom weight cancels it. It bites on a house with an unusual mix. Take a 2,400 square foot house with only 2 bedrooms, outside San Francisco. fit()'s constants price it at −227,532 + 472,987 − 184,805 = $60,649.
The model without square feet says $194,167 for that house, and the hand-written rule says $500,000. No sale in the data looks like it, so nothing warned fit(). The fix is not a cleverer fit() on the same five rows. It is more rows, especially rows where size and bedroom count disagree, and a measured error on rows the model did not train on.
When two columns rise together, a model can split the credit between them almost any way. Read learned weights as one set that fits these rows, never as the price of one thing.
Why can't I trust a model trained on five rows? What would "held-out data" actually have shown?
Because scoring a model on the rows it trained on is asking it questions it has already seen the answers to. Fit on any four of the five houses and it prices those four to the dollar. Ask it about the fifth and it misses by $259,783 on average, more than twice the hand-written rule's $122,000.
Picture a teacher who hands out four practice questions with the answer key, then sets the same four questions as the exam. A perfect score proves the student can repeat four answers. It says nothing about a fifth question. Held-out data is the fifth question: rows kept away from training and used only to mark the result.
Five houses are too few to split into a training set and a test set, so do the smallest honest version. Leave one house out, fit on the other four, and price the one left out. Then repeat for each house in turn. This is called leave-one-out. It is a tiny cousin of the train/test split that Module 02 is built around.
One round by hand: leave out h3
Fitting on h1, h2, h4 and h5 happens to give round constants: $160 a square foot, $10,000 a bedroom, $212,000 for San Francisco and a base of $70,000. Check them yourself.
- Price the four training houses. h1: 70,000 + 160 × 1,000 + 10,000 × 2 = 250,000. h2: 70,000 + 240,000 + 30,000 = 340,000. h4: 70,000 + 128,000 + 10,000 + 212,000 = 420,000. h5: 70,000 + 400,000 + 40,000 = 510,000.
- Compare with what they sold for. $250,000, $340,000, $420,000 and $510,000. Every miss is $0. On its own training rows this model is perfect.
- Price the house it never saw. h3: 70,000 + 160 × 2,000 + 10,000 × 3 + 212,000 = 70,000 + 320,000 + 30,000 + 212,000 = $632,000.
- Compare with the real sale. h3 sold for $850,000, so the miss is 632,000 − 850,000 = −$218,000.
Why the training misses are exactly $0: four constants and four rows make four equations with four unknowns. They have one solution, and it passes through every row. The model did not discover the housing market. It solved a puzzle that had exactly enough pieces.
| Left out | Learned from the other four: per sq ft, per bedroom | Largest miss on its four training houses | Price for the house left out | Sold for | Held-out miss |
|---|---|---|---|---|---|
| h1 | −112.50, +282,500 | $0 | $113,750 | $250,000 | −$136,250 |
| h2 | −566.67, +555,000 | $0 | $521,667 | $340,000 | +$181,667 |
| h3 | +160, +10,000 | $0 | $632,000 | $850,000 | −$218,000 |
| h4 | +160, +10,000 | $0 | $638,000 | $420,000 | +$218,000 |
| h5 | +1,250, −535,000 | $0 | $1,055,000 | $510,000 | +$545,000 |
| Average, ignoring sign | $0 | $259,783 |
Fig. 0.3o puts each held-out miss next to the hand-written rule's miss on the same house.
- The held-out miss. Each solid bar is one round: fit on four houses, then price the fifth. The bar is how far that price was from the real sale. The misses run from $136,250 on h1 to $545,000 on h5, and $259,783 on average.
- The house outside the range. h5 is the biggest house: 2,500 square feet and 4 bedrooms. Leave it out and no training house is as large, so the model must guess beyond anything it saw. It says $1,055,000 for a $510,000 house.
- The perfect score that means nothing. Every four-house model misses its own four training houses by $0, because four constants can always be solved to pass through four rows. A score measured here would have said "ship it" five times out of five.
- The rule, for comparison. The outlined bars are the hand-written rule's misses on the same houses. The rule was never fitted to these rows, so the comparison is fair. It beats the held-out models on four houses out of five, and loses only on h3, where its × 2.5 misses by $300,000.
| Score | Average miss | What it measures |
|---|---|---|
| Each four-house fit, scored on its own four houses | $0 | Nothing: four constants can always fit four rows |
| fit() on all five, scored on the same five | $36,805 | How well the constants fit the rows they were chosen for |
| The hand-written rule, on the five houses | $122,000 | A rule that was never fitted to these rows |
| Each four-house fit, scored on the house it never saw | $259,783 | The closest thing five rows allow to a real test of prediction |
Even on five rows, this shows one thing clearly. The $36,805 that fit() reports about itself is not the miss you would see on the next sale. Measured on houses it did not train on, the same method misses by about seven times as much.
Two honest limits. First, five held-out numbers are themselves a tiny sample: h5 alone is $545,000 of the $1,298,917 total, so one different house would move the average a lot. Second, a team with fifty thousand rows would not refit fifty thousand times. It sets aside a test set once, as Module 02 does with 600 of its 3,000 visitors.
A score on the rows a model trained on measures memory. Only rows it never saw measure prediction, so hold some back before you fit anything.
Walk one house through the whole thing: from the five sales to a price in an API response.
The house arrives as JSON, becomes the row [1800, 3, 1], meets four constants read from a 518-byte model file, and leaves as {"price": 833571}. Nothing is learned on the way. Every number the service uses was fixed by fit() before the service started.
Fig. 0.2 drew the model as one more service in your stack. Here is that picture with one real house moving through it: the 1,800 square foot, 3-bedroom San Francisco house this module keeps pricing. The trip has two halves that run at different times. Training runs once, on a schedule. Serving runs once for every request.
| Station | When it runs | What happens | Value after this station |
|---|---|---|---|
| 1. Rows | Training, once | The five past sales are read from the database into X_train and y_train | A 5 × 3 grid of features and 5 prices |
| 2. fit() | Training, once | Computes the constants with the lowest loss on those rows | −94.8052, +236,493.51, +479,545.45 and a base of −184,805.19 |
| 3. Model file | Training, once | pickle, Python's built-in way of writing an object as bytes, saves the fitted model as model.pkl | 518 bytes |
| 4. Boot | Serving, once per process | The service reads model.pkl back into memory | The same four constants |
| 5. Request | Serving, per request | The frontend sends the house as JSON | {"sqft": 1800, "bedrooms": 3, "city": "San Francisco"} |
| 6. Feature row | Serving, per request | Hand-written code turns the JSON into the three training columns, in training order; the city name becomes a 1 or a 0 | [1800, 3, 1] |
| 7. predict() | Serving, per request | Four multiplications and an addition, worked below | 833,571.43 |
| 8. Response | Serving, per request | The service rounds the price and returns JSON; the backend shows it or applies its own rule | {"price": 833571} |
Station 3 deserves a look inside. The 518 bytes hold no copy of the five houses. They hold the four learned numbers and a note that the model expects 3 features. The rest is two bookkeeping values from the fit, a few settings, and the name of the class to rebuild. The training rows stay in the database.
Station 7, worked by hand with the constants the file holds:
- Square feet. −94.8052 × 1,800 = −170,649.35.
- Bedrooms. 236,493.5065 × 3 = +709,480.52.
- San Francisco. 479,545.4545 × 1 = +479,545.45.
- Add them to the base. −170,649.35 + 709,480.52 + 479,545.45 − 184,805.19 = 833,571.43. predict() returns the same 833,571.43, and station 8 rounds it to 833,571.
- Training, once. The five sales become a grid and a price list. fit() turns them into four constants, and pickle saves the fitted model as a 518-byte file. This half runs on a schedule, never inside a request.
- Serving, per request. The service read model.pkl once, at boot. Each request's JSON becomes the row [1800, 3, 1] through ordinary hand-written code. predict() then does four multiplications and an addition, and the response is {"price": 833571}.
- A city the model never saw. Denver and Austin both become [1800, 3, 0], because the only city column asks "is it San Francisco?". Both get $354,026, and the service returns 200 OK. Nothing in four constants can say that Denver never appeared in training.
- A row built in the wrong order. Swap bedrooms and square feet and the same model answers $425,982,768, with no exception and no warning. It multiplies whatever number arrives in each position. Train on named columns instead, and scikit-learn refuses the swapped row with a ValueError: "Feature names must be in the same order as they were in fit."
| Training: stations 1 to 3 | Serving: stations 4 to 8 | |
|---|---|---|
| How often it runs | Once per model version, on a schedule | Once per request |
| Needs the sale prices, the labels? | Yes: y_train | No: the house has not sold |
| Changes the four constants? | Yes: this is where they are made | Never |
| Where the time goes | fit() on five rows, which section 03 says takes milliseconds | predict(): a median of about 0.08 ms per call on the machine that ran the script |
| What goes wrong | Too few rows and tangled columns: the first two questions of this block | A feature row that does not match training, which raises no error unless the columns are named |
Two words from the dictionary land here. Training is stations 1 to 3. Inference is station 7, and it is nothing but arithmetic on stored numbers. That is why the fitted model in Fig. 0.3h can answer ten thousand questions a day for about a cent.
What this trace leaves out: a real service checks the request before station 6. It would reject a missing bedroom count. It could also refuse a city outside the list the model was trained on, instead of quietly treating it as "not San Francisco". That check is ordinary code too, and it is the first defence against both failures in markers 3 and 4 of Fig. 0.3p.
At serving time a model is a small file of numbers and one multiplication. What goes wrong lives in the code that builds the row, so test that code like any other code.
04 · The four rolesFour Doors Into the Field
You have now run the inversion with your own hands and seen both its power and its trap: the fitted model missed by $36,805 a house on average against the rule's $122,000, and it did so with a negative price per square foot that five rows could not rule out. Before you spend the next 120 hours, the job feed from the field report needs sorting the same way the four words of Fig. 0.3 did. Four kinds of role pay the 28% premium of Fig. 0.0b; this section says which one your nine years fit fastest, and why.
Before you invest ~120 hours in this course, you should know exactly which job it's aiming you at. The 2026 market research behind this course identifies four role archetypes a 9-YOE engineer can credibly target, each with a different skills center of gravity:
| Skill area | GenAI App Engineer | ML Engineer (Staff) | AI Architect | AI Consultant |
|---|---|---|---|---|
| Python + SWE craft | ★★★★★ | ★★★★★ | ★★★☆☆ | ★★☆☆☆ |
| LLM APIs · RAG · agents · MCP | ★★★★★ | ★★★☆☆ | ★★★★★ | ★★★☆☆ |
| Fine-tuning · PyTorch depth | ★★★☆☆ | ★★★★★ | ★★★☆☆ | ★☆☆☆☆ |
| Evals & observability | ★★★★★ | ★★★★★ | ★★★★☆ | ★★☆☆☆ |
| Cloud · serving · MLOps | ★★★★☆ | ★★★★★ | ★★★★★ | ★☆☆☆☆ |
| Stakeholder & business skills | ★★★☆☆ | ★★★☆☆ | ★★★★★ | ★★★★★ |
| Path at 9 YOE | Fastest transition — leverages SWE depth directly | Most retooling; deepest math/systems bar | Leverages seniority + system-design record | Enters at Manager / Senior Consultant |
- What you already have. Python and software craft, cloud serving, evals, stakeholder work, and the LLM-API row itself: calling a model is an HTTP request with a JSON body, the same shape as the
/predictcall in Fig. 0.2. These rows are why the transition is the fastest of the four, and why the posting in Fig. 0.0c can ask for only two years of GenAI. - The one new row. Fine-tuning and PyTorch depth. The market wants three stars here, not five, and Modules 04, 05 and 11 supply them. It is the only row where nine years of shipping give you nothing to start from, which is also why the Staff ML Engineer door, which wants five stars in it, needs more retooling than this course provides.
This course optimizes for the GenAI App Engineer column, drawn as Fig. 0.3j — the fastest, highest-leverage transition for your profile, because five of its six rows are things nine years of shipping software already gave you or nearly so.
But it deliberately builds range into the neighboring columns: the architecture modules (12, 17) train the AI Architect's judgment, and every module's "Boardroom translation" plus Module 16 train the consultant's tongue.
The market research is blunt about why: hybrid profiles that "can code the PoC AND present to the CIO" are the scarcest and best-paid in the field.
The Staff-MLE door stays open too — Modules 04, 05, and 11 give you honest foundations — but it's the one path that demands substantial extra retooling beyond this course.
Note what's not on the list: researcher. Nobody expects you to invent architectures. The market pays engineers who can take models that already exist and turn them into systems that survive production — which is, conveniently, the thing you've been practicing for nine years.
05 · How this course worksThe Method: Build, Break, Measure, Pitch
The story pauses here. You know which door you are walking through, the GenAI App Engineer's, and you have felt the inversion in code. Before the next event you need the shape of the road: what each module does to you, in what order, and why the labs matter more than the reading. This section is about the course itself, not about house prices, and it has no numbers from the five sales in it. The story picks up again in the lab at the end of this page, and properly in Module 01.
This course is built on learning science, not vibes, and it shows the same face in every module.
Each one walks six beats in a fixed order — you feel a business problem first, see the mechanism as a picture, build a naive version with your own hands, watch it break in a way that motivates the industry tool, learn that tool at its current 2026 API surface, and finish with a lab that produces an artifact.
Concepts repeat deliberately as story, diagram, code, and quiz, because one exposure never sticks. (This module is the one exception to the pattern: nothing here breaks yet, so the "watch it break" beat handed its slot to the four roles above.)
The labs follow a thesis the hiring data supports overwhelmingly: three deep,
deployed, measured projects beat ten tutorials. Recruiter screens in 2026 probe
for "production scars, not tutorials," and the single strongest differentiator is
shipped evals with measurable outcomes — résumés listing eval tooling like Ragas,
LangSmith, or DeepEval land in the top score quartile 2.6× as often. As one hiring-manager
line in the research puts it: "a Jupyter notebook with model.predict() tells
them nothing." So from Module 07 onward, every project you build ships with an eval
harness, and later modules reuse and extend earlier artifacts on purpose — spaced
repetition, disguised as engineering.
The fastest way to waste this transition is to learn the 2024 curriculum in 2026. "LangChain + Pinecone + ChatGPT API" is now table stakes — it no longer differentiates, and on its own it reads as a tutorial diet.
The current signal set employers scan for is agentic systems, MCP, evals/observability, and cost/safety engineering — MCP alone now appears in 17–24% of agentic postings and in Goldman Sachs VP job specs.
That's why this course's center of gravity is Act III, and why evals arrive in Module 07, not as a final-week garnish.
Here's the whole journey. Act I bridges you in fast. Act II rebuilds classical ML and deep learning foundations — compressed, because you're a senior engineer, but honest, because interviews still test them. Act III is the GenAI core the market actually hires for. Act IV turns competence into a career: governance, consulting skills, and the system-design interview itself.
06 · How to learn from itYour Brain on AI: How to Make This Stick
Your brain throws away most of what you read, on purpose. This section explains why that happens, what the pages of this course do to fight it, and the ten habits that separate "I read that" from "I can do that".
Still paused. The last section explained what the course will put in front of you. This one explains what your own brain will do with it, because a page of definitions read at a desk on a Tuesday is exactly the kind of thing it throws away. Nothing here is about the house-price model. It is about making sure that when the story resumes, the inversion and the $36,805 you measured in section 03 are still in your head, and that you know what to do when a page stops and asks you something.
What your brain does with a technical page
Here is the uncomfortable truth behind every technical book you have forgotten: your brain did exactly what it was built to do. It is tuned to notice what is new, strange, or dangerous, and to quietly discard what feels routine. A tiger on the path is stored for life. A page of definitions read at a desk on a Tuesday afternoon sends no signal that says "this matters", so it never gets past the filter.
Nine years of engineering do not switch that filter off. If anything they make it stricter, because so much now feels routine. So a course that simply puts correct sentences in front of you, in the right order, will mostly be forgotten, however good the sentences are. What decides whether something sticks is not the content. It is what your brain was doing while you read it.
The slow way to make something stick is repetition: read it enough times and your brain concludes it must matter. The fast way is to make your brain work: predict, compare, argue, write, say it aloud, build it, break it. Each of those uses a different set of neurons than reading does, and the more different kinds of activity a concept triggers, the more places it gets stored. This is the whole idea behind the Head First series of books, and this course borrows it on purpose. It is also why the pages here look the way they do.
"Great. Only seventeen more modules of this."
— your brain, right about now
It does not have to be dull, and your brain learns a new, hard topic much faster when it is not. The devices below are not decoration. Every one of them exists to make you do something a plain paragraph never would. Treat them as instructions, not as furniture.
What this course does about it, and what each thing on the page is asking of you
Every module repeats its core idea as a story, a picture, a piece of code, and a question, because one exposure never sticks. Inside that, the page keeps stopping you and asking for something. Here is what each device wants from you when you meet it.
| On the page | What it is asking you to do |
|---|---|
| In one line (the boxed sentence under a heading) | Read it twice. It is the plainest statement of the concept; everything after it is elaboration you can always come back to. |
| Field report (the client memo) | Feel the stakes. Ask yourself what you would do if this landed on your desk on Monday. |
| You already know this | Say the mapping out loud: "an embedding index is a database index for meaning." Your existing knowledge is the hook the new idea hangs on. |
| Brain power | Stop. Write your prediction down before you open the reveal. A guess that turns out wrong teaches more than a paragraph read. |
| Sharpen your pencil | Fill in every blank row, on paper or in a scratch file, then check. Three rows are done for you as examples. The rest are yours, and wrong answers are the point. |
| BE the retriever (or the tokenizer, the agent loop…) | Play the machine. Trace by hand what it would do with these inputs. Only then run the code and compare. |
| Step-by-step (the ☰ list above code) | Open it whenever a line is unclear. Each numbered step matches one statement in the file below it. |
| Anatomy | Read the numbered keys against the line above them. This is the one line in the module to be able to write from memory. |
| Fireside chat | Read both sides. Decide who you agree with. Then notice that both are right about something, and name what each one owns. |
| Straight answer (the thought bubble) | That is your own doubt, voiced. Read the answer, including the downside it admits. |
| Say it out loud (the chant) | Do it. Literally. Speaking uses a different part of the brain than reading. |
| Watch it break | Run the broken version. Seeing the failure with your own eyes is what makes the fix memorable. |
| There are no dumb questions | Not optional. They are the questions you would have asked, answered at interview depth. Read all of them. |
| Quick reference | Skip it the first time through. It is for you in six months, hunting one fact. |
| Flex your memory | Close the page and answer from memory, ideally the next day. This is the one that decides whether you keep it. |
| The lab | Build it. Nothing in a module counts until the lab produces an artifact you can show someone. |
Ten habits that make it stick
The course did its part. The rest is yours. These are the reader-side habits the learning research and the Head First authors agree on, adapted for someone with a job and a laptop rather than a pencil and a textbook. Try them, keep the ones that work for you.
- Slow down. The more you understand, the less you have to memorise. When a page asks you a question, stop and answer it as if a colleague had asked. Do not skip to the reveal.
- Write your answers before you check them. Pencil exercises and Brain Power questions only work if you commit to a guess first. If we did them for you it would be like someone else doing your workout.
- Read every "no dumb questions" box. They are not sidebars. They are the part of the core content that answers what you were already wondering.
- Type the code, do not paste it, then break it. Change a number, delete a line, make it fail, read the error. Most of what a module teaches lives in the difference between the working version and the broken one.
- Say it out loud. Explain the mechanism to an empty room, a rubber duck, or a chat window with an LLM. Speaking uses different parts of the brain than reading, and you will find the gap in your understanding within thirty seconds.
- One section, one sitting. Do not read a whole module in one go. Stand up between sections, change rooms, come back. Your brain ties learning to place, and variety helps it.
- Make it the last hard thing before bed. Part of the move into long-term memory happens after you close the laptop. Put something new in front of that process and some of what you learned is lost.
- Notice when you start skimming. The moment you read a paragraph twice and remember nothing, stop for the day. Past that point more reading makes it worse, not better.
- Feel something. Care whether PolicyPal's adjuster gets the right answer. Argue with the fireside chat. Groan at the bad joke. Emotion is the signal your brain uses to decide what to keep.
- Drink water, and come back tomorrow. The "flex your memory" prompt at the end of each module is built for the next day, not the same hour. Dehydration measurably lowers thinking before you feel thirsty.
One more thing. This is a learning experience, not a reference. The first time through, go in order: every module assumes what the earlier ones built, and the code in later labs extends the code from earlier ones. Come back out of order as often as you like; that is what the quick-reference boxes are for.
07 · Under the hoodThe Math, If You Want It
Back to the five sales. Section 03 showed you that fit() found four constants in a millisecond and that two of them were negative. It did not say how the constants were chosen. This optional section does, with the same numbers: the equation the model uses to price the 1,800 square foot house at $833,571, the single number it made as small as possible to pick the constants, and why that number could be found with one matrix formula rather than a search.
What fit() actually computed — least squares in plain terms (optional depth)
The linear model you trained predicts with one equation:
ŷ = w₁x₁ + w₂x₂ + w₃x₃ + b.
Here x₁, x₂, x₃ are the features (sqft, bedrooms,
is-SF), the w's are the learned weights in model.coef_,
b is the intercept, and ŷ ("y-hat") is the prediction.
- Weights times features. Each w (weight) is one of the numbers in
model.coef_, and each x is the matching column of the new house's row. The two shown in red are the negative ones. b ismodel.intercept_, the base price. - The sum. Multiply, add, and the four products collapse into one price. This row is the whole of prediction: no search, no learning, four multiplications and three additions per house. That is why inference is cheap enough to run ten thousand times a second.
- The loss. Run the same equation on the five training houses, take the miss on each, square it, add them up. fit() chose the four constants that make this total as small as any straight-line model can on these rows. The rule's version of the same total was 128.05 billion, drawn in Fig. 0.3g.
"Best" weights are defined by a loss function — a single number measuring total wrongness across the training set, the third row of Fig. 0.5b: L = Σᵢ (yᵢ − ŷᵢ)². Σᵢ means "sum over every training example i"; yᵢ is the true price; ŷᵢ the model's guess.
Why squared errors rather than absolute ones?
Three reasons: squaring makes every term positive so errors can't cancel; it punishes one large miss far more than many small ones (usually what a business wants); and it makes L smooth and differentiable, so calculus can find its minimum.
For linear regression that minimum has a closed form, the normal equation: w = (XᵀX)⁻¹ Xᵀy, where X is the training matrix (rows = houses, columns = features), Xᵀ is its transpose, and (·)⁻¹ the matrix inverse.
One matrix computation — that's the entire "training run" you triggered, which is why it finished in milliseconds.
The models later in the course lose this luxury: no closed form exists for neural networks, so they descend the loss surface step by step (gradient descent — Module 04).
But the contract never changes: define a loss, find the weights that minimize it. Hold onto that sentence; it is the whole field in nine words.
There are no dumb questions
- Do I need to relearn university math to do this seriously?
- No. You need mechanism-level intuition — what a loss is, what a gradient does, why an embedding is a vector — and this course delivers exactly that, with the formal math always optional in "Under the hood" blocks. The one exception is the Staff ML Engineer track at research-heavy shops, which genuinely tests deeper theory. For the GenAI engineer and architect roles this course targets, engineering judgment beats derivation every time.
- Is classical ML worth my time in the GenAI era?
- Yes, for two hard-nosed reasons. First, interviews: the market research is explicit that "despite the GenAI wave, classical ML remains a baseline expectation" — bias/variance and XGBoost-era modeling still come up. Second, economics: for tabular prediction at volume, a classical model is thousands of times cheaper and faster than an LLM call, and knowing when to reach for it is exactly the judgment that separates seniors from tutorial-followers.
- I use Copilot and Claude every day. Aren't I already an AI engineer?
- You're an AI-assisted engineer — a real and tested skill (Meta now runs a dedicated "AI-Enabled" interview round). But the roles this course targets are about building AI systems: retrieval pipelines, agent loops, eval harnesses, cost controls. Using the tools is the driver's seat; this course puts you under the hood. You'll need both, and Module 15 sharpens the first while everything else builds the second.
- I'm strongest in TypeScript. Why is everything Python?
- Ecosystem gravity: Python appears in 91–96% of agentic-AI postings; TypeScript in 18–26%, mostly full-stack AI product roles. The good news is that modern AI-engineering Python — typed, Pydantic-validated, async, FastAPI-served — feels closer to your Node backend than to a data scientist's notebook. Module 01 is precisely that bridge.
- Won't half of this be obsolete in a year?
- Model names and version numbers will rotate; the mechanisms won't. The inversion, retrieval, evals, agent loops, and cost engineering have been stable for years while logos churned. This course defends against rot deliberately: claims are date-stamped ("as of Aug 2026"), installs are version-pinned, and deprecation traps (like OpenAI's Assistants API, shut down August 2026) are flagged by name so you learn the current surface, not the tutorial fossil record.
Practice this pitch — it's the module's business takeaway, and versions of it will open every stakeholder conversation you have for the next decade: "You don't need to hire a research lab to get AI into this product. You need engineers who already know how to ship reliable systems and can now wire learned components into them — that's a force multiplier, not a new headcount line. One AI-fluent senior engineer turns an existing product team into an AI team." The ROI frame: AI capability commands a 28–43% market premium precisely because it's scarce among people who can also ship; consultancies are restructuring around it (Accenture: 80,000 AI-focused hires, AI proficiency mandatory for promotion).
Companies that retrain senior engineers capture that scarcity at the cost of a course, not a hiring cycle.
08 · The labYour Working Environment
The engineer in the field report wanted to know what machine learning is and how it fits the architecture they already know. You now have both, on paper and in a 21-line script. What you do not yet have is the environment every later artifact will be built in, or your first measured call to a language model, the thing the 340% growth in Fig. 0.0b is actually about. This lab produces both, and it starts the repository the rest of the course commits into.
Every module ends with a lab that produces an artifact. This one produces the environment every later artifact is built in.
Three pieces:
- uv — the Rust package manager that has effectively replaced the pip + venv + pyenv ceremony in 2026 workflows.
- The Anthropic SDK, as your hosted-model path.
- Ollama, as your local, $0.00, works-on-a-plane path.
You will call a model both ways. And you will measure what each call cost you from day one — because cost discipline is a hiring signal, not an afterthought.
The stack, and why
Before the setup commands, here is every tool this whole course leans on, in one table, with what you would pick instead and when. This module installs only the first rows and the model calls; the rest arrive module by module, and each of those modules shows its own slice of this table in more detail.
The stack, and why
The one question that decides it: what is the boring, widely hired-for default at each layer, and what is the named situation in which you would leave it? As of October 2026.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Language and packaging | Python 3.12 with uv | pip + venv, Poetry, conda; Python 3.13 or newer | Every library in this table ships Python first, and uv replaces pip, venv and pyenv with one fast tool. Weakness: uv is younger than pip, so some company docs still say pip. | Your employer standardises on conda for GPU or scientific stacks, or a library you need does not yet support the newer Python. |
| Data and SQL | DuckDB, with pandas for small in-memory tables | PostgreSQL, SQLite, Polars, Spark, BigQuery | DuckDB runs SQL on a laptop with no server to install. Weakness: it is built for one analyst at a time, not many writers at once. | The data no longer fits on one machine (roughly more than a few hundred GB), or many people must write to it at the same time: move to PostgreSQL or a warehouse. |
| Classic machine learning | scikit-learn, with XGBoost for tables | LightGBM, CatBoost, statsmodels | One consistent fit/predict interface and strong defaults on spreadsheet-shaped data. Weakness: no GPU training and no images or text without help. | Your table has tens of millions of rows and training takes hours, or you need to categorise text or images: use LightGBM at scale or move to PyTorch. |
| Deep learning | PyTorch | JAX, TensorFlow/Keras | The default in research code and in Hugging Face models, so almost every pretrained model loads straight into it. Weakness: you write the training loop yourself. | Your team already runs on JAX for TPUs, or you inherit a TensorFlow system in production. |
| Language-model access | Anthropic and OpenAI APIs; Ollama for a local model | Google Gemini, Mistral, open models served by vLLM, a cloud provider such as AWS Bedrock | Hosted APIs give the strongest models with no hardware; Ollama gives a free offline path. Weakness: hosted calls cost money per token and send your text to a third party. | Data may not leave your network, or volume passes roughly a few million calls a month: serve an open model yourself. |
| Agent orchestration | LangGraph | Plain Python loop, the provider SDK tool runner, CrewAI, LlamaIndex agents | Explicit state, saved checkpoints and human approval steps. Weakness: more ceremony than a plain loop. | The task is one model call plus one or two tools: a plain loop is shorter and easier to debug. |
| Vector storage | pgvector, with Chroma for prototypes | Qdrant, Pinecone, Weaviate, FAISS | If your business data already lives in PostgreSQL, vectors can sit next to it. Weakness: slower than a purpose-built engine at very large scale. | More than about 10 million vectors, or a strict latency target such as p99 under 20 ms: move to Qdrant or a managed service. |
| Serving and hosting | FastAPI in a Docker container | Flask, Django, serverless functions, a managed platform | Async by default, typed requests, and a container runs the same on your laptop and in the cloud. Weakness: you own the deployment. | Traffic is rare and spiky (a few requests an hour): a serverless function is cheaper than a running container. |
| Tracing and monitoring | Langfuse | LangSmith, Arize Phoenix, plain logs | Open source, can run on your own machine, and records every model call with its cost. Weakness: one more service to run if self-hosted. | Your whole stack is LangChain and you want zero setup: LangSmith integrates faster. |
Pick the boring default that most job postings name, and leave it only when you can state the number or the situation that forces you out.
Step-by-step: what the setup commands do, in plain English
- Download and run the uv installer, then print its version to confirm it is on your path. uv is one binary that creates virtual environments, installs packages and pins versions, replacing pip, venv and pyenv.
- Make a project folder and run
uv initasking for Python 3.12. This writespyproject.toml, the project's manifest, and.python-version. Thenuv addpins three libraries to version ranges, so a later install gets the same major version you learned on.uv run python -Vruns Python inside the project's own environment and should print 3.12. - Put your API key in the shell as an environment variable, never in a file that gets committed, and run the hosted script with
uv run, which picks up the project environment automatically. - Install the Ollama app, pull
llama3.2, a 3-billion-parameter model of about 2 GB that runs on a laptop CPU, and run the local script.
# ── 1. uv: one binary that replaces pip + venv + pyenv ─────────────────
curl -LsSf https://astral.sh/uv/install.sh | sh
uv --version # any 2026 release is fine
# ── 2. The course project ──────────────────────────────────────────────
mkdir ai-course && cd ai-course
uv init --python 3.12 # writes pyproject.toml + .python-version
uv add "anthropic>=0.60,<1" "ollama>=0.4,<1" "scikit-learn>=1.5,<2"
uv run python -V # should print Python 3.12.x
# ── 3. Hosted path: key in the environment, never in code ──────────────
export ANTHROPIC_API_KEY="sk-ant-…" # from console.anthropic.com → API keys
uv run hello_api.py
# ── 4. Offline path: a small model on your own machine ─────────────────
curl -fsSL https://ollama.com/install.sh | sh
ollama pull llama3.2 # 3B params, ~2 GB — fine on CPU
uv run hello_local.py
Now the two hello scripts. The hosted one talks to claude-haiku-4-5 —
the fast, cheap tier ($1 per million input tokens, $5 per million output as of Aug 2026),
which is exactly what you should default to while learning:
Step-by-step: what hello_api.py does, in plain English
- The first line is a comment reminding you that the
anthropicpackage was added in the setup block. - Import
osto read environment variables,systo exit with a message,timefor a stopwatch, andanthropic, the official SDK, the library that talks to the Claude API. - If
ANTHROPIC_API_KEYis not set in the environment, stop with a message pointing at the offline script. Keys live in the environment, never in code. - Create the client. It reads the key from the environment by itself; nothing is passed in.
- Start the stopwatch with
time.perf_counter(), the clock meant for measuring short durations. - Call
client.messages.createwith three things: the model name (claude-haiku-4-5, the cheap tier),max_tokens(a ceiling on the length of the reply, 200 here), andmessages, a list of conversation turns. Each turn is a dictionary with aroleandcontent; there is one user turn. The two adjacent quoted strings are joined into one by Python. - Stop the stopwatch.
elapsedis the round trip in seconds. - The reply's
contentis a list of blocks; the first block's.textis the model's answer. Print it. - Read
usage.input_tokensandusage.output_tokens: the counts the API bills by. A token is roughly three quarters of a word. - Compute the cost: input tokens divided by a million times $1, plus output tokens divided by a million times $5, the Haiku 4.5 prices as of August 2026.
- Print the two counts, the cost to six decimal places, and the seconds to two.
# uv add "anthropic>=0.60,<1" (already added in the setup block)
import os
import sys
import time
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
sys.exit("No ANTHROPIC_API_KEY set — run hello_local.py for the offline path.")
client = anthropic.Anthropic() # reads the key from the environment
t0 = time.perf_counter()
msg = client.messages.create(
model="claude-haiku-4-5",
max_tokens=200,
messages=[{
"role": "user",
"content": "In two sentences: what changes when software learns its "
"rules from data instead of getting them from a programmer?",
}],
)
elapsed = time.perf_counter() - t0
print(msg.content[0].text)
# Token accounting from day one — cost habits are part of the job.
tokens_in, tokens_out = msg.usage.input_tokens, msg.usage.output_tokens
cost = tokens_in / 1e6 * 1.00 + tokens_out / 1e6 * 5.00 # haiku-4-5 pricing, Aug 2026
print(f"\n[{tokens_in} in / {tokens_out} out · ${cost:.6f} · {elapsed:.2f}s]")
Step-by-step: what hello_local.py does, in plain English
- Two comments: the
ollamaPython package is needed, and so are the Ollama app and a pulled model, both from the setup block. - Import
timeand thechatfunction fromollama. - Start the stopwatch.
- Call
chatwith the model tagllama3.2and the samemessageslist the hosted script used. The call goes to the Ollama server running on your own machine, over localhost, and never touches the internet. - Stop the stopwatch.
- The reply's text is at
resp.message.content, a single string. Print it. - Print a line in the same shape as the hosted script's, with a cost of $0 and the elapsed seconds, so the two runs can be compared side by side in the lab's README table.
# uv add "ollama>=0.4,<1"
# Prereq: the Ollama app is installed and `ollama pull llama3.2` has run.
import time
from ollama import chat
t0 = time.perf_counter()
resp = chat(
model="llama3.2", # 3B parameters — small enough for a laptop CPU
messages=[{
"role": "user",
"content": "In two sentences: what changes when software learns its "
"rules from data instead of getting them from a programmer?",
}],
)
elapsed = time.perf_counter() - t0
print(resp.message.content)
print(f"\n[local inference · $0.000000 · {elapsed:.2f}s]")
Notice the two scripts are almost line-for-line identical: a model name, a messages list, a text reply. That's not a coincidence — the chat-message contract is the de facto standard across hosted and local models, and it's why "multi-provider fluency," which postings increasingly demand, is smaller than it sounds. Same contract, different endpoint, wildly different unit economics.
hello_api.py computes.- The hosted path.
hello_api.pysends one user turn to Anthropic's API and gets back text plus a usage count. Cost is input tokens times $1 per million plus output tokens times $5 per million: for 41 in and 78 out, $0.000431. Small, and the habit of computing it is the point; at ten thousand calls it is the tall bar of Fig. 0.3h. - The local path.
hello_local.pysends the identical turn to Ollama on your own machine. No key, no network, no bill, and a smaller model that answers more slowly on a CPU. It is the path that works on a plane, and the fallback the stretch goal of the lab wires in. - The shared contract. The messages list is the same object in both files. That is why swapping the hosted model for a local one later is a configuration change and not a rewrite, and why "multi-provider fluency" in a posting is smaller than it sounds.
Mission: stand up the course environment, run the hello-model script both ways, and record your first cost/latency measurements. This repo becomes your portfolio monorepo — every later module commits into it.
uv run python -Vprints Python 3.12.x from the project venv, andpyproject.tomlpins anthropic, ollama, and scikit-learnuv run learned_version.pyprints the three learned weights and a prediction — and you can say in one sentence what each weight meansuv run hello_local.pyreturns a completion with the network cable unplugged (the offline path works)- If you have a key:
uv run hello_api.pyprints the reply plus token counts, computed cost, and latency - Measurement criterion: a README table comparing hosted vs local — model, latency, and cost per call (one row each)
- README documents versions (uv, Python, SDKs, model tags) and one surprise you hit during setup, with the fix
Stretch goal: write a single hello.py that routes to
Anthropic when ANTHROPIC_API_KEY is set and falls back to Ollama when it
isn't — congratulations, you've just built your first provider-fallback pattern, which
returns as a production concern in Module 12.
09 · Interview radarHow This Shows Up in Interviews
Four questions, one shared grading rubric: every strong answer here ends with a decision — what you'd buy, build, or measure — not a definition. The candidate who closes with "so here's what I'd actually do" beats the candidate who closes with "and that's what deep learning means."
"Explain the difference between AI, ML, deep learning, and GenAI to a non-technical executive."
The real test Communication, not definitions — can you give a busy decision-maker a map they can act on?
Strong answer Draw four nested circles in words, one business example per ring. AI is the biggest circle: any software making a decision a human used to make — even an if-then rules engine ("flag transactions over $10K from a new country") counts.
ML sits inside it: instead of us writing the rules, the computer learns them from historical data — our churn model saw thousands of customers who left or stayed and found the warning signs itself.
Deep learning, inside ML, is the layered-network technique that cracked messy unstructured data — reading text off scanned invoices, face unlock. GenAI, the newest ring inside that, doesn't just classify — it generates text, images, and code: the support chatbot.
Land it "Practically: we mostly buy GenAI via APIs, and we build classical ML — because it runs on our customer data, and that data is our moat. Nobody can rent our churn model from an API." Structure plus a decision beats a lecture.
"When would you use classical ML instead of an LLM?"
The real test The 2026 judgment filter — vague "it depends" answers fail; named conditions pass.
Strong answer When the data is a table and the answer is a number or category, classical ML wins on all three axes that matter:
- Tabular data with labeled history — churn, fraud, credit
scoring: rows of features with a known outcome column, exactly the lab's
[sqft, bedrooms, is_SF] → priceshape - Latency and unit economics — a trained model predicts in under a millisecond for ~$0; an LLM takes seconds and cents. At 10M fraud checks a day, that's ~free versus ~$100K+/day — and fraud can't wait two seconds anyway
- Interpretability and audit — a declined loan legally needs a
why; a linear model can print its reasoning (
model.coef_), an LLM can't produce that audit trail
Land it Give the converse: free-text understanding, generation, and tool-using workflows are where LLMs earn their cost. Rule of thumb — "if the input fits in a spreadsheet, start classical; if the input is language, start with an LLM."
"Where does a model live in your architecture, and how do you keep it healthy?"
The real test The GenAI-flavored system-design opener — FAANG now runs a distinct GenAI design round alongside the classical one.
Strong answer A stateless microservice behind an
explicit /predict contract, with the model file as a versioned artifact
you can roll back like any bad deploy. One deliberate choice worth saying aloud: the
service returns a probability (0.87), not a decision ("deny") — the
threshold lives in the caller, because "flag above 0.8" is a business decision the
model shouldn't need a redeploy to change.
Then differentiate the failure model: a model doesn't crash, it drifts. It keeps returning 200 OK while its answers quietly go stale — a churn model trained pre-pandemic served every prediction on time in April 2020, and every prediction was wrong. So you monitor two layers: ops health (latency, 5xx) and statistical health — the distribution of predictions (a model that historically flags 5% suddenly flagging 20% has drifted with zero errors logged), plus periodic evals against fresh labeled data.
Land it Drift is why models get retrained on a schedule, not just fixed when broken.
"When would you NOT call a hosted LLM API?"
The real test Vendor-agnostic judgment, asked nearly verbatim in screens — the hosted API is the right default, so name what overrides it.
Strong answer Five conditions push you to run the model yourself:
- Data residency / PII — a hospital or bank that legally can't send records to a third party
- Unit economics at volume — at millions of calls/day, per-token pricing crosses the cost of your own GPUs
- Hard latency floors — real-time autocomplete or voice needs consistent sub-100ms; API round-trips can't promise it
- Offline / edge — the factory floor, the ship, the phone
- You need the weights — deep fine-tuning requires open weights; an API rents you the behavior, never the model
Land it Name the alternative path instead of just declining: open models via Ollama in dev, vLLM in production (Module 11) — and because the model sits behind the stateless service above, swapping the hosted API for self-hosted is a config change, not a rewrite.
Also on the radar: Meta now runs a dedicated "AI-Enabled" coding round — solving problems with an AI assistant. Your lab habit of measuring cost-per-call is exactly the kind of instinct that round rewards.
Quick reference — Orientation
- The inversion
- In normal programming you write the rules. In machine learning you supply examples and the machine derives the rules. Everything else follows from that one difference.
- Supervised learning
- You have labelled examples — input and correct answer. The great majority of production ML.
- Unsupervised learning
- No labels. You are asking the data for its own structure: clusters, anomalies, topics.
- Reinforcement learning
- Learning from reward rather than from answers. Rare in business ML, central to how modern chat models are aligned.
- loss function
- The single number that says how wrong the model currently is. Training is nothing more than making that number smaller.
- overfitting
- The model memorised your training data instead of learning the pattern. Looks brilliant on data it has seen and fails on data it has not.
- drift
- The world changed after you trained. The model did not. This is why an ML system needs monitoring in a way ordinary software does not.
- Sample, feature, label
- One row; a column you know before the answer exists; the answer column you want predicted. In code the features are X and the label is y.
- held-out data
- Rows kept away from training and used only to score the model. On the five houses, fits on four missed the fifth by $259,783 on average, against $36,805 on their own training rows.
- stack rule
- Choose the boring, widely used default at each layer, and write down the specific number or situation that would make you switch. Every row of the stack table has both.
- correlated features
- Two columns that rise and fall together, like square feet and bedrooms (correlation 0.94). The model can split credit between them almost any way, which is how a price per square foot of −94.81 happens.
10 · RecapWhat You Can Do Now
- You can state the inversion — data + rules → output versus data + outputs → rules — and defend why learned rules win in adversarial, fast-changing domains like spam
- You can place a model in a standard web architecture as a stateless, versioned microservice and explain what's genuinely new (how the artifact is made) versus what isn't (everything else)
- You can disambiguate AI ⊃ ML ⊃ DL ⊃ GenAI for an executive, with a business example at each ring
- You can sort a problem into supervised, unsupervised, or reinforcement learning — and into rules vs classical ML vs deep learning vs LLM, on cost and data grounds
- You can translate full-stack vocabulary to ML vocabulary fluently: build → training, binary → model file, test suite → eval metric, stale cache → drift
- You can name the four role archetypes, which one this course optimizes for, and why your 9 years are an asset rather than a liability
- You can point at the sample, the features, the label and the prediction in a table row, and explain "the model learned 150" as the value with the smallest loss
- You can show with the five houses why a score on training rows says nothing about new rows, and why a learned weight is not the price of one thing
- You have a working uv-managed environment, and you've called both a hosted model and a local one — with the cost and latency of each written down
Prompt 1 (this module): close this page and sketch, from memory, the inversion diagram and the nested AI/ML/DL/GenAI map — then check yourself against Fig. 0.1 and Fig. 0.3. Prompt 2 (reaching back to your own stack): pick one real service you've shipped and translate five of its artifacts into ML dictionary terms (its config, its build, its binary, its tests, its stalest cache). Later modules will reach back to this one the same way — the inversion is the course's most-recalled idea.