Gen AI · Course · 04 of 7
What Is Machine Learning?
Rules vs data
- ·classic: rules + data → output
- ·ML: data + answers → rules
- ·the model = learned rules
Three families
- ·supervised (labels)
- ·unsupervised (no labels)
- ·reinforcement (reward)
- ·self-supervised → GPT/BERT
Task
- ·classification = category
- ·regression = number
- ·task picks the loss
Workflow
- ·collect → clean → features
- ·split → train → evaluate
- ·deploy → monitor → retrain
Generalization
- ·train / val / test
- ·test set is sacred
- ·overfit vs underfit
- ·bias–variance dial
When NOT to use
- ·simple fixed rules
- ·no data
- ·need guarantees / explainability
The pattern
- ·learn → predict → evaluate
- ·nearest-centroid → transformers
- ·always beat a baseline
This is the phase where the math starts paying off. You’ve built vectors, matrices, and distance; now you’ll use them to make a computer learn from examples instead of following rules you wrote by hand. We’ll map the whole field in one sitting — the three kinds of learning, the workflow, the traps — and then build the simplest thing that actually learns, from scratch.
Learning objectives
- Explain the shift from writing rules to learning from data, and what “the model” actually is
- Tell supervised, unsupervised, and reinforcement learning apart — and place self-supervised (how LLMs train)
- Distinguish classification from regression and pick the right loss
- Split data into train / validation / test and say why the test set is sacred
- Diagnose overfitting vs underfitting through the bias–variance lens
- Judge when a problem shouldn’t use ML at all
- Build a nearest-centroid classifier from scratch and beat a random baseline
The problem
You want to build a spam filter. The old way: sit down and write rules. “If it says FREE MONEY, mark spam. If it has 3+ exclamation marks, mark spam.” You spend weeks on rules. Spammers change one word. Your rules break. You write more rules. The cycle never ends.
Machine learning flips it. You hand the computer thousands of emails already labeled spam or not spam, and it figures out the patterns itself — patterns you’d never have hand-coded. When spammers adapt, you retrain on new data instead of rewriting logic. That shift — from programming rules to learning from data — is the whole idea, and it powers every recommender, voice assistant, and language model you’ve used.
Pre-lesson check
0/2 answered// question
In supervised learning, what does the model get during training?
// question
Why split data into training and test sets?
Learning from data, not rules
Traditional programming and machine learning run in opposite directions. In classic programming, you supply the rules; the program applies them to data to make output. In ML, you supply the data and the desired output, and the algorithm produces the rules.
›Traditional programming
›Machine learning
The model that falls out of training is the rules — encoded as numbers (weights / parameters). It generalizes from the examples it saw to make predictions on data it has never seen. When you “download the weights” of a model, you’re downloading learned rules.
The three families of learning
Supervised
- ·labeled input→output
- ·classification
- ·regression
Unsupervised
- ·inputs only, no labels
- ·clustering
- ·dimensionality reduction
Reinforcement
- ·actions + rewards
- ·learn a policy
- ·games, robotics, RLHF
| Family | You give it… | It learns to… | Example |
|---|---|---|---|
| Supervised | input → output pairs (labels) | map inputs to outputs | 10k photos labeled cat/dog → tell them apart |
| Unsupervised | inputs only, no labels | find structure on its own | customer histories → natural segments |
| Reinforcement | an environment + rewards | a strategy that maximizes reward | play a game: +1 win, −1 lose → find a policy |
Most of what you’ll build is supervised. Unsupervised learning shows up in preprocessing and exploration. Reinforcement learning powers game AI, robotics, and the RLHF that aligns language models.
›Semi- and self-supervised, in one more level of detail
Semi-supervised mixes a little labeled data with a lot of unlabeled data: pseudo-labeling (train on the labels you have, predict the rest, retrain on everything), label propagation (labels spread to similar neighbors through a graph), and consistency regularization (a small perturbation of an input should get the same prediction).
Self-supervised invents the task from the data’s own structure — masked-word prediction (BERT), next-token prediction (GPT), and contrastive learning (SimCLR: two crops of the same image should look alike, and unlike crops of other images). These aren’t a fourth category; they’re clever ways to manufacture supervision without humans.
Classification vs regression
The two main supervised tasks — and the one distinction that decides your loss function:
| Aspect | Classification | Regression |
|---|---|---|
| Output | discrete categories | continuous numbers |
| Question | “which category?” | “how much?” |
| Example | is this email spam? | what will the house sell for? |
| Typical loss | cross-entropy, accuracy | mean squared error (MSE), MAE |
// question
Checkpoint: a bank wants to predict the exact dollar amount a customer will spend next month. Which task, and which loss?
The ML workflow
Every project — no matter the algorithm — walks the same loop:
A humbling reality: cleaning and feature engineering usually eat 60–80% of the time, not the modeling. Good features beat fancy algorithms, and this is exactly why data management came first. Deployment isn’t the end either — data drifts, models decay, and monitoring tells you when to retrain.
Train, validation, test — and the sacred test set
This is the concept beginners most often get wrong. You must judge a model on data it never saw while training, or you’re measuring memorization.
| Split | Purpose | Typical size |
|---|---|---|
| Training | the model learns from it | 60–80% |
| Validation | tune hyperparameters, compare models | 10–20% |
| Test | one final, unbiased score | 10–20% |
Overfitting, underfitting, and the bias–variance dial
| Regime | What’s wrong | Train error | Test error |
|---|---|---|---|
| Underfitting | too simple — misses real patterns (high bias) | high | high |
| Good fit | right complexity — generalizes | low | low |
| Overfitting | too complex — memorizes noise (high variance) | very low | high |
The tell-tale sign of overfitting: a big gap between training and test scores. Bias is error from wrong assumptions (a straight line for a curved truth → underfit); variance is sensitivity to the particular training sample (a wiggly curve through every point → overfit). Total error ≈ bias² + variance + irreducible noise, and you’re hunting the sweet spot between them.
| Fix overfitting | Fix underfitting |
|---|---|
| more data; simpler model; regularization; dropout; early stopping | more complex model; more features; less regularization; train longer |
// question
Checkpoint: a model scores 98% on training data but 55% on test data. What’s going on?
When NOT to use machine learning
ML is powerful, not universal. Before reaching for a model, ask if you actually need one.
| Don’t use ML when… | Because |
|---|---|
| the rules are simple & fixed | Celsius→Fahrenheit is a formula; a model adds cost for nothing |
| you have little or no data | ML needs examples; with 10 rows there’s nothing to learn — collect first |
| errors are catastrophic & you need guarantees | models are probabilistic; they’re sometimes wrong. Use deterministic methods |
| a lookup table / heuristic already covers it | if a threshold handles 99% of cases, ML is maintenance cost with no gain |
| full explainability is legally required | most models aren’t interpretable; use simple ones (or rules) where it’s mandated |
// question
Checkpoint: which of these is the WORST fit for machine learning?
Build it: the simplest thing that learns
Meet the nearest-centroid classifier — arguably the simplest ML algorithm there is. Learn: compute the center (mean) of each class. Predict: assign a new point to the nearest center. That “nearest” is the Euclidean distance √Σ(a−b)² — the vector idea straight out of the linear-algebra lesson. No gradient descent, no iteration, no hyperparameters.
import torch
class NearestCentroid:
def fit(self, X, y): # "learn" = one mean per class
self.classes = torch.unique(y)
self.centroids = torch.stack([X[y == c].mean(dim=0) for c in self.classes])
return self
def predict(self, X): # "predict" = nearest center
dists = torch.cdist(X, self.centroids) # (n_points, n_classes) distances
return self.classes[dists.argmin(dim=1)]
# two Gaussian blobs, one per class
torch.manual_seed(42)
X = torch.cat([torch.randn(100, 2) + 1.0, # class 0 around (+1, +1)
torch.randn(100, 2) - 1.0]) # class 1 around (-1, -1)
y = torch.tensor([0] * 100 + [1] * 100)
clf = NearestCentroid().fit(X, y)
acc = (clf.predict(X) == y).float().mean()
print(f"accuracy: {acc:.2f}") # ~0.94That’s the entire algorithm: fit computes two means, predict measures distances. And it already captures the pattern every model shares — learn a representation, predict with it, evaluate.
// question
Checkpoint: in the nearest-centroid classifier, what did the model actually “learn” from the data?
What it can’t do — and why that’s the syllabus
The nearest-centroid classifier assumes each class is a single round blob and draws a straight decision boundary. It breaks when:
- a class has several clusters (the digit “1” is written many ways) — motivates k-nearest neighbors
- the boundary is curved (one class wraps around another) — motivates decision trees / neural nets
- features are on wildly different scales (distance drowns in the biggest one) — motivates feature scaling
Each limitation is the reason a later algorithm exists. That’s the whole path from here to transformers.
Use it
Run the from-scratch classifier and watch it beat the baselines as the classes separate:
python ml-fundamentals/what-is-machine-learning/ml_intro.pyRead it inline without leaving the page: · .
Ship it
This lesson produces:
- — a from-scratch
NearestCentroid, synthetic data, train/test split, and random + majority baselines - — the walkthrough, cell by cell
- / — task-type framing, baselines, and a train/test-split diagnosis
- — a prompt that turns a vague business ask into a concrete ML task (learning type, target, features, metric, baseline, pitfalls)
Exercises
- Take any dataset (Iris, Titanic) and split it 70/15/15 into train/val/test. In one sentence, explain why tuning on the test set invalidates your final number.
- List three real-world problems. For each, label it classification / regression / clustering and supervised / unsupervised. Defend the trickiest one.
- A model gets 99% on training data and 60% on test. Diagnose it in one word, then list three fixes you’d try in order.
- Change the blob
separationinml_intro.pyfrom far to nearly overlapping. Plot accuracy vs. separation and explain the trend through the bias–variance lens.
Post-lesson quiz
0/5 answered// question
A model gets 98% on training data but 55% on test data. This is…
// question
A store wants to group customers by purchase behavior with no predefined labels. Which type of ML?
// question
Which is NOT a good use case for ML?
// question
Training GPT to predict the next word in a document is an example of…
// question
What do the nearest-centroid classifier and a giant transformer have in common?
Key terms
| Term | What people say | What it actually means |
|---|---|---|
| Model | "the AI" | A function with learnable parameters that maps inputs to outputs |
| Training | "teaching the AI" | Adjusting parameters so predictions match known outputs |
| Feature | "an input column" | A measurable property the model uses to predict |
| Label | "the answer" | The known output for a training example — the error signal |
| Loss function | "how wrong it is" | A number measuring prediction error; training minimizes it |
| Overfitting | "it memorized" | Learned training-specific noise, so it fails on new data |
| Generalization | "it works on new data" | Accuracy on data the model was never trained on |
| Baseline | "a sanity check" | A trivial predictor (random / majority) your model must beat to be worth anything |
| Hyperparameter | "a setting you tweak" | A knob set before training (learning rate, model size) — tuned on validation, never test |