Velamuvi AIAcademy

Lesson 1 of 12 · The Setup

Learning From Labels

What supervised learning really does: a model searches for the rule that best matches labelled examples. Learn where labels come from and why quality matters.

  • 13 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Describe supervised learning as a search for a rule that matches labelled examples
  • Tell the difference between the parameters a model learns and the settings you choose
  • Train a model with the fit and predict pattern every scikit-learn model shares
  • Explain where labels come from, what they cost and how to check their quality
  • Show how wrong labels make a model worse

The idea in plain words

Supervised learning means learning from examples that come with the right answers. You give an algorithm many examples, each with its features (what you know) and its label (the answer), and it works out a rule that turns features into answers. It is called supervised because the labels act like a teacher marking homework: for every example, the algorithm can check whether its rule got the answer right.

In Introduction to Machine Learning you met features (X), labels (y), training and test sets, and your first scikit-learn models. This course goes one level deeper: what training actually does, the main families of supervised models, and how to use them well in practice.

PartLessons
The SetupLearning from labels, regression vs classification, loss functions, generalisation
Core AlgorithmsLinear models, tree-based models, instance-based models, probabilistic models
In PracticeChoosing an algorithm, baselines, imbalanced classes, and a complete churn prediction project

Every supervised learning method has the same three ingredients:

  1. Labelled examples: rows of features, each with its label.
  2. A family of possible rules: the kind of rule the model can express, such as a straight line or a set of yes/no questions. The adjustable numbers inside the rule are its parameters.
  3. A score and a search: a way to measure how well a rule matches the labels, and a method for finding the best-scoring rule. Finding it is called training (or fitting).

Here is the smallest possible supervised learning problem. Ten students, one feature (hours studied) and one label (passed the exam or not). The family of rules is "pass if hours ≥ t", and the one parameter to learn is the threshold t. The program tries each threshold and scores it by how many labels it matches:

Try it yourselfPython
hours  = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
passed = [0, 0, 0, 1, 0, 0, 1, 1, 1, 1]   # the labels: 1 = passed

def accuracy(threshold):
    correct = 0
    for h, label in zip(hours, passed):
        guess = 1 if h >= threshold else 0
        if guess == label:
            correct += 1
    return correct / len(hours)

for t in range(2, 10):
    print(f"pass if hours >= {t}: {accuracy(t):.0%} of labels matched")
Output
pass if hours >= 2: 60% of labels matched
pass if hours >= 3: 70% of labels matched
pass if hours >= 4: 80% of labels matched
pass if hours >= 5: 70% of labels matched
pass if hours >= 6: 80% of labels matched
pass if hours >= 7: 90% of labels matched
pass if hours >= 8: 80% of labels matched
pass if hours >= 9: 70% of labels matched

The best rule is "pass if hours ≥ 7", which matches 9 of the 10 labels. No threshold matches all ten, because the student who passed after 4 hours doesn't fit the pattern. That is normal: real labels always contain some cases a simple rule can't explain.

That loop is training. Real algorithms search far more cleverly, over thousands or millions of parameters at once, but the goal is the same: find the parameter values whose predictions best match the labels.

The same search in scikit-learn

A decision tree that may ask only one question (max_depth=1) belongs to the same family of rules: one feature, one threshold. Let scikit-learn do the search:

Try it yourselfPython
from sklearn.tree import DecisionTreeClassifier, export_text

hours  = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]   # X: one feature per row
passed = [0, 0, 0, 1, 0, 0, 1, 1, 1, 1]                        # y: the labels

model = DecisionTreeClassifier(max_depth=1)   # a setting we choose: one question only
model.fit(hours, passed)                      # training: search for the best question

print(export_text(model, feature_names=["hours"]))
print("Predictions for 2, 6.8 and 9 hours:", model.predict([[2], [6.8], [9]]))
print("Training accuracy:", model.score(hours, passed))
Output
|--- hours <= 6.50
|   |--- class: 0
|--- hours >  6.50
|   |--- class: 1

Predictions for 2, 6.8 and 9 hours: [0 1 1]
Training accuracy: 0.9

The tree found the cut-off 6.5, halfway between 6 and 7 hours: the same rule as our loop, with the same 90%. Notice the two kinds of number:

  • 6.5 is a parameter: the model learned it from the labels.
  • max_depth=1 is a hyperparameter: you chose it before training, and it limits which rules the search may consider.

Every supervised model in scikit-learn works this way. fit(X, y) searches for the parameters, predict(X_new) applies the learned rule to new rows, and score(X, y) measures how well predictions match labels. Only the family of rules changes from model to model, and the Core Algorithms part of this course tours the main families.

Where labels come from

Features are often easy to collect. Labels are usually the expensive part, because someone or something has to provide the right answer for every training example.

SourceExampleThe catch
People label by hand (annotation)Doctors mark tumours on scans; staff tag support messages as complaintsSlow and costly, and people disagree
Outcomes recorded laterDid the customer cancel within 30 days? Was the loan repaid?You must wait for the outcome, and define it precisely
Actions people takeClicks, purchases, pressing "Report spam"Cheap and plentiful, but noisy: people click by accident
MeasurementsA house's sale price, a sensor readingMeasurement errors and missing values

A model can only be as good as the labels it learns from. If past loan decisions were unfair to some group of people, a model trained to copy those decisions learns the unfairness too. Before training, ask: what exactly does this label mean, who decided it, and could it be wrong?

How good are your labels?

A standard check is to have two people label the same items independently and compare. The program below compares two people who each labelled 12 support messages as complaint (1) or not (0):

Try it yourselfPython
from sklearn.metrics import cohen_kappa_score

# Two people labelled the same 12 support messages: 1 = complaint, 0 = not
anna = [1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0]
ravi = [1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0]

agree = sum(a == r for a, r in zip(anna, ravi))
print(f"They agree on {agree} of {len(anna)} messages ({agree / len(anna):.0%})")
print(f"Cohen's kappa: {cohen_kappa_score(anna, ravi):.2f}")
Output
They agree on 9 of 12 messages (75%)
Cohen's kappa: 0.50

75% agreement sounds decent, but two people guessing at random would also agree fairly often. Cohen's kappa corrects for that: 1 means perfect agreement, 0 means no better than chance. A kappa of 0.50 says the two people often see the same message differently. The usual fix is not a better algorithm but a clearer labelling guide: write down what counts as a complaint, with examples, and relabel the messages people disagreed on.

Wrong labels make worse models

How much do wrong labels matter? The program below trains the same decision tree on a medical dataset (breast tumour measurements, labelled malignant or benign), after deliberately flipping a share of the training labels. The test labels stay correct, so the test accuracy shows how much the model was misled:

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=0, stratify=y)

rng = np.random.default_rng(0)
for noise in [0.0, 0.1, 0.2, 0.3, 0.4]:
    y_noisy = y_train.copy()
    flip = rng.random(len(y_noisy)) < noise     # choose rows to corrupt
    y_noisy[flip] = 1 - y_noisy[flip]           # 0 becomes 1, 1 becomes 0
    model = DecisionTreeClassifier(random_state=0).fit(X_train, y_noisy)
    print(f"{noise:.0%} wrong labels -> test accuracy {model.score(X_test, y_test):.2f}")
Output
0% wrong labels -> test accuracy 0.91
10% wrong labels -> test accuracy 0.84
20% wrong labels -> test accuracy 0.67
30% wrong labels -> test accuracy 0.64
40% wrong labels -> test accuracy 0.54

With clean labels the tree scores 0.91. With 20% of labels wrong it drops to 0.67, and at 40% it is barely better than a coin toss. The model faithfully learned the mistakes, because matching the labels is all training ever does. A tree this deep is especially easily fooled, since it can grow a branch for every wrong label; the Generalisation lesson shows how simpler models resist noise better.

Common mistakes

Practice

Practice exercise

Train a one-parameter spam filter by hand: find the threshold on the number of links that best matches the labels.

Your solutionPython
links = [0, 1, 0, 3, 5, 2, 7, 4, 6, 1, 8, 2]   # links in each email
spam  = [0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1]   # label: 1 = spam

# Try every threshold t from 1 to 8 with the rule: spam if links >= t.
# Keep the t that matches the most labels (the first one if there is a tie),
# then print, for example:
# Best rule: spam if links >= 3 (75% match)
best_t, best_acc = None, 0

print(f"Best rule: spam if links >= {best_t} ({best_acc:.0%} match)")
Knowledge check

What does a supervised learning algorithm use the labels for during training?

Summary

  • Supervised learning finds a rule that maps features to labels, using examples whose labels are known.
  • Training is a search: the model's parameters are adjusted until its predictions best match the labels. Hyperparameters, such as max_depth, are settings you choose.
  • Every scikit-learn model uses fit(X, y), predict(X_new) and score(X, y); X must be a table with one row per example.
  • Labels come from people, later outcomes, user actions or measurements, and they are often the costliest part of a project.
  • Label quality limits model quality: check agreement between labellers (for example with Cohen's kappa) and fix unclear definitions before training.

Next: Regression vs Classification, and how the kind of label decides the kind of model.

Finished reading? Tick it off to track your progress.