How machine learning learns: supervised vs unsupervised
Understand what machine learning really is: learning rules from examples by reducing error. Learn features and labels, regression versus classification, supervised versus unsupervised learning, and why overfitting is the main risk.
Machine learning (ML) is a way to get a computer to find a pattern in examples instead of writing the rules by hand. You show it many examples and it adjusts itself until it predicts well. This lesson explains what "learning" actually means, the two main families (supervised and unsupervised), and the vocabulary you will see in every ML course.
Rules versus learning
Suppose you want to predict how many cups Brew & Bean will sell tomorrow. With traditional programming you write the rules: "if the temperature is above 30, add 40 cups". You must discover the numbers yourself and update them when things change.
With machine learning you give the computer past days (temperature, weekend, promotion) and the cups actually sold. It finds the numbers. When new data arrives you retrain, instead of rewriting rules.
Two approaches
| Aspect | Traditional programming | Machine learning |
|---|---|---|
| You provide | Rules and data | Data and the right answers |
| You get | Answers | Rules (a trained model) |
| Best when | Rules are simple and known | Rules are too complex to write, but examples exist |
The vocabulary
Words you will see everywhere
| Term | Meaning | Brew & Bean example |
|---|---|---|
| Feature | An input column the model uses | temperature, is_weekend, promo |
| Label (target) | The answer you want to predict | cups_sold |
| Example (row, sample) | One record | One day's data |
| Model | The learned pattern: a function from features to a prediction | A formula with learned numbers |
| Parameters | The numbers the model learns | The weight for temperature |
| Training | Learning the parameters from examples | model.fit(X, y) |
| Inference (prediction) | Using the trained model on new data | model.predict(X_new) |
| Hyperparameter | A setting you choose before training | Number of neighbours, tree depth |
By convention, features are written X (a table, capital letter) and the label y (a single column, lower case).
What does "learning" mean?
Learning means reducing error. The model starts with a guess, measures how wrong it is on the training examples with a loss (a single number for the total error), changes its parameters to reduce the loss, and repeats. Here is the idea in its most basic form: try many candidate formulas cups = w * temperature + b and keep the one with the smallest error.
import numpy as np
temps = np.array([18, 22, 25, 28, 31, 34]) # feature
cups = np.array([55, 80, 95, 115, 135, 150]) # label
best = None
for w in np.arange(0, 6.01, 0.5): # candidate slopes
for b in range(-60, 61, 10): # candidate starting levels
pred = w * temps + b
error = np.mean((cups - pred) ** 2) # mean squared error
if best is None or error < best[0]:
best = (error, w, b)
print("smallest error, w, b =", best)On this tiny grid the best pair is w = 5.5 and b = -40 with a mean squared error of about 8.9. Real models do not try every combination; they use smarter methods such as calculus-based gradient descent, which you will meet in the neural networks lesson.
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(temps.reshape(-1, 1), cups) # training: scikit-learn wants a 2D table for X
print("slope:", model.coef_, "intercept:", model.intercept_)
print("prediction for 30 C:", model.predict([[30]]))scikit-learn finds slope 6.0 and intercept -53.0 (a lower error than our coarse grid) and predicts about 127 cups at 30 degrees. Every scikit-learn model follows this same pattern: create it, fit, then predict.
Supervised learning
In supervised learning every training example comes with the right answer (the label). The model learns to map features to labels, like a student practising with an answer key. There are two kinds.
Supervised learning
| Kind | Predicts | Examples | Models you will meet |
|---|---|---|---|
| Regression | A number | Cups sold, house price, delivery time | Linear regression, random forest |
| Classification | A category | Spam or not, will churn or not, which digit | Logistic regression, k-nearest neighbours, trees |
from sklearn.neighbors import KNeighborsClassifier
# features: [orders last month, average bill in Rs]
X = np.array([[1, 150], [2, 180], [1, 160], [12, 200], [15, 220], [10, 190]])
y = np.array(["occasional"] * 3 + ["regular"] * 3)
clf = KNeighborsClassifier(n_neighbors=3).fit(X, y)
print(clf.predict([[2, 170], [11, 210]]))k-nearest neighbours labels a new customer by looking at the 3 most similar customers. The output is ['occasional' 'regular'].
Unsupervised learning
In unsupervised learning there are no labels. The model looks for structure by itself, for example groups of similar customers (clustering) or a simpler description of many columns (dimensionality reduction). Nobody tells it what the groups mean: you inspect them afterwards and name them.
from sklearn.cluster import KMeans
# points described by two features; no labels given
points = np.array([[1, 1], [1.5, 2], [1, 0.5],
[8, 8], [9, 9], [8.5, 7.5],
[1, 9], [2, 8.5], [1.5, 9.5]])
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(points)
print(km.labels_)The output has three groups of three points each, such as [1 1 1 0 0 0 2 2 2]. The numbers themselves (0, 1, 2) are arbitrary names. Choosing the number of clusters is your decision. See *Clustering and dimensionality reduction* later in this track.
Other kinds of learning
Beyond the two big families
| Type | Idea | Example |
|---|---|---|
| Semi-supervised | A few labelled examples plus many unlabelled | Labelling a few thousand photos by hand, using the rest to help |
| Self-supervised | The data creates its own labels | A language model predicts the next word in text (how large language models are pre-trained) |
| Reinforcement learning | An agent learns by trial, reward and penalty | A program learning to play a game, or tuning a robot's moves |
The big risk: memorising instead of learning
A model can score perfectly on its training data and fail on new data because it memorised noise. This is overfitting. A student who memorises last year's answers will fail a new paper. That is why we always keep some data aside to test, which is the subject of *Train, validation, test and overfitting*.
Training score is not a result
Never judge a model on the same data it was trained on. A high score on training data says only that it can remember, not that it can predict.
Choosing the right family
A decision path
- 1Do you have examples with the right answer? If no, you are in unsupervised territory (or need to collect labels).
- 2Is the answer a number? Use regression.
- 3Is the answer a category? Use classification.
- 4Do you just want to group similar things or compress many columns? Use clustering or dimensionality reduction.
- 5Could a simple rule or query answer it? Then skip ML.
I want to solve this problem: [describe it in 2 to 3 sentences].
Data I have: [list columns, number of rows, whether I have the correct answers].
Tell me: (1) is this supervised, unsupervised or neither, (2) regression, classification or clustering, (3) what the features and the label would be, (4) a simple baseline to beat, and (5) one risk in my data. Use plain English and no more than 150 words.What to expect: Good answers name the label explicitly and warn about a risk such as too few rows or data leakage. If the answer does not mention a baseline, ask for one.
How this comes up in interviews
Expect "What is the difference between supervised and unsupervised learning?", "Give an example of each", "What is overfitting?" and "What are features and labels?". Use a concrete example (predict price versus group customers) and mention that supervised learning needs labelled data, which is often the expensive part.
Try it: Classify the problem
For each case, say whether it is supervised or unsupervised, and whether it is regression, classification or clustering: (a) predict a student's marks from hours studied; (b) flag a payment as fraud or not using past labelled cases; (c) group news articles by topic without any labels; (d) predict tomorrow's electricity demand in kWh.
Try it: Break the brute-force search
In the brute-force code, make the grid coarser (steps of 2 for w and 40 for b). What happens to the best error? Then try adding a seventh data point that does not fit the pattern (for example 40 degrees and 60 cups) and see how the best parameters change.
Key takeaways
- ML learns rules from examples instead of you writing them; learning means reducing a loss on training data.
- Features are the inputs (X); the label is what you predict (y).
- Supervised learning has labels: regression predicts numbers, classification predicts categories.
- Unsupervised learning has no labels and finds structure such as clusters.
- In scikit-learn the pattern is always create,
fit,predict. - Judge models only on data they did not train on, or you may reward memorising.
Check yourself
Finishing the quiz marks the lesson as done.
1. In a dataset to predict house prices, what is the label?
2. You have customer purchase data with no labels and want to find natural groups of customers. Which approach fits?
3. A model scores 100% on training data but only 60% on new data. What is the likely problem?
4. What does model.fit(X, y) do in scikit-learn?
5. Predicting whether an email is spam or not is which kind of problem?
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.