AI State of the Art
Fundamentals/Machine Learning: The Basics/27 min
Section 4

Supervised Learning: Classification vs Regression

Listen as a podcast β†’

Introduction: Labeled Data for Learning

Imagine you need to teach a robot to recognize fruits. You show it 1,000 photos: "This one is an apple." "This one is an orange." "This one is a banana." After seeing hundreds of apples, the robot starts to see patterns: round shape, red or green color, particular texture. Then you show it an apple it's never seen before. It recognizes: "That's an apple!"

This is supervised learning. Each training example says "here's the input, here's the expected answer." The model learns to predict the answer for new inputs.

Why 'supervised'?

Because there's a "supervisor" (you or the labeled data). You tell the model: "Look, here's the right answer." The model learns. It's like having a teacher who corrects you immediately.

Supervised learning diagram with vegetables
This diagram illustrates how supervised learning works: the model is trained with labeled data (vegetables) to make predictions on new images. The labels serve as references to correct and guide the learning process.Source : Medium

The Fundamental Concept: Labeled Data

Each example for supervised learning contains two parts:

Features: the input variables that describe the problem. To predict the price of an apartment: area in sq ft, number of rooms, floor, neighborhood, year built.

Label: the answer you're trying to predict. For the apartment: its actual sale price ($350,000, $500,000, etc.).

A training dataset looks like a table:

Area (sq ft)RoomsFloorNeighborhoodPrice (USD)
48523Manhattan380,000
88041Brooklyn420,000
27015Queens210,000

The model sees these patterns and learns: "Large area + central = high price. Small area + outer borough = low price."

Label Quality is Crucial

If you mislabel your data ("This spam is a legitimate email!"), the model learns garbage. We say "garbage in, garbage out": bad data in = bad model out.

Classification: Predicting a Category

Classification is answering a yes/no question: "Cat or not cat?", "Spam or not spam?", "Sick or not sick?" The answer is a category from a finite set.

Binary Classification: Two Choices

Only two possible categories. Examples:

  • Email: spam or not spam
  • Bank transaction: fraudulent or legitimate
  • Medical imaging: malignant or benign tumor
  • Customer review: positive or negative

The model typically produces a score between 0 and 1, interpreted as "probability of being spam." If the score exceeds 0.5, we say "spam." Otherwise, "not spam."

Two classes separated by a linear boundary
This image illustrates the separation of two classes (A and B) by a linear boundary in a 2D space. It shows how a binary classifier can discriminate data into two categories.Source : Medium

Multiclass Classification: More Than Two Choices

When you have 3, 4, or 10 possible categories.

  • Handwritten digit recognition (the MNIST dataset, 70,000 hand-written digits): classes 0 through 9, so 10 categories
  • Face recognition: person A, person B, person C...
  • Document classification: sports, politics, economics, culture, science
Example of multiclass classification in 2D
This image illustrates a multiclass classification problem where three distinct categories (represented by different shapes) are separated by linear boundaries. It shows how an algorithm can learn to distinguish multiple classes simultaneously.Source : Medium

Evaluating a Classifier: The Real Metrics

The most intuitive metric is accuracy: it's simply the percentage of correct answers. But it's often misleading. Imagine you need to detect cancer. If you say "no cancer" for every patient and 99% are indeed healthy, you get 99% accuracy, but you miss every sick patient, making the model completely useless.

That's why we use two complementary metrics instead.

Precision measures the reliability of your positive predictions: among all the cases you predict as positive, how many actually are? For example, if you label 100 messages as "spam" and 80 of them are actually spam, your precision is 80%.

Recall, on the other hand, measures your ability to detect all positive cases: among all the true positives in the data, how many do you manage to find? For example, if there are 1,000 actual spams in your inbox and you detect 800 of them, your recall is 80%.

The Fundamental Trade-off

Precision and recall are often in opposition. To increase precision (fewer false alarms), you say "spam" less often... but you miss more actual spams (recall drops). The context determines the right balance: in fraud detection, you want high recall (don't miss a fraud). In movie recommendations, you want high precision (don't recommend a bad movie).

Confusion matrix and classification metrics
This image illustrates the confusion matrix for a binary classification problem and presents the formulas for the main evaluation metrics: precision, recall, specificity, and accuracy. It shows how true positives, false positives, true negatives, and false negatives are organized.Source : LinkedIn

Regression: Predicting a Numerical Value

Regression is predicting a real number, not a category. Examples:

  • House price: $450,000 (not "expensive" or "cheap," but an exact number)
  • Tomorrow's temperature: 59.5 degrees Fahrenheit
  • Revenue: $5.2 million
  • A person's age from a photo: 32 years old
Actual vs predicted scatter plot
This chart illustrates the results of a linear regression model comparing actual and predicted prices. The red line represents the ideal regression line where prediction = reality.Source : CodeSignal

Measuring Regression Quality

You can't use accuracy (these aren't categories). You use:

Mean Squared Error (MSE): the average of the squared gaps.

MSE=1Nβˆ‘i=1N(y^iβˆ’yi)2\text{MSE} = \frac{1}{N} \sum_{i=1}^{N} (\hat{y}_i - y_i)^2

Symbol by symbol: NN is the number of examples; ii numbers them, 1 through NN; yiy_i is the true value of example ii; y^i\hat{y}_i ("y-hat") is what the model predicted for that same example; the big βˆ‘\sum means "add this up across all examples"; and 1N\frac{1}{N} turns that sum into an average. In one sentence: for each example, take the gap between prediction and truth, square it, and average all those squares.

Squaring penalizes large errors heavily. If you predict $500,000 instead of $400,000 (an error of $100,000), that counts as (100,000)^2 = 10 billion in the error. The model doesn't forgive big mistakes.

Root Mean Squared Error (RMSE): the square root of MSE. It brings the result back into the original unit (dollars, not squared dollars) which makes it directly readable.

Mean Absolute Error (MAE): the average of the gaps taken without their sign and without squaring. Far more forgiving of extreme outlying values.

R-squared: measures the proportion of variance in the data that your model explains. An R-squared of 1 means the model perfectly predicts every value. An R-squared of 0 means the model is no better than just predicting the mean. In practice, an R-squared of 0.85 is often excellent for real-world noisy data.

Formulas for MAE, MSE, RMSE, and R-squared metrics
These formulas illustrate the main evaluation metrics for regression models in supervised learning. They allow quantifying the error between predicted and actual values.Source : DataTechNotes

The Algorithms: Which Tool for Which Problem

Linear Regression: The Basic That Works

The simplest one. Looks for a line (or a plane in higher dimensions) that minimizes the error.

With one input variable: y=aΓ—x+by = a \times x + b. Here xx is the observed feature (the area), yy the value to predict (the price), aa the slope ("how much the price rises when area rises by one unit") and bb the intercept ("the starting price, at zero area"). aa and bb are the learned parameters: training searches for them, and once found they are frozen. xx and yy change with every apartment.

Example: price=5,000Γ—area+50,000\text{price} = 5{,}000 \times \text{area} + 50{,}000. Each square foot adds $5,000 to a base price of $50,000.

Strengths: simple, fast, interpretable. "Each sq ft = $5,000."

Limitations: only captures linear relationships. If the price depends on area2\text{area}^2 (not just area), it misses it.

Simple linear regression with scatter plot
This image illustrates a simple linear regression where a straight line models the linear relationship between two variables X and Y. It shows how a single explanatory variable (X) can predict a target variable (Y) in a supervised framework.Source : Six Sigma DSI

Logistic Regression: The Misleading Name

Despite its name, it's a classification algorithm, not regression. It uses the sigmoid function to transform a linear output into a probability between 0 and 1.

Οƒ(z)=11+eβˆ’z\sigma(z) = \frac{1}{1 + e^{-z}}

The symbols: zz is the raw score coming out of the linear part of the model (any number, positive or negative); ee is Euler's number, the constant 2.718... used as the base of the exponential; Οƒ\sigma ("sigma") is the traditional name of this function. In one sentence: the sigmoid squashes any number into the range between 0 and 1, so it can be read as a probability.

The sigmoid has a characteristic S-shape: when z is very large (a very confident decision), the output approaches 1. When z is very small (very negative), it approaches 0. And for values of z close to zero, the transition is smooth and continuous. This property makes it useful: it transforms any real score into a value interpretable as a probability, without ever leaving the [0, 1] interval.

If Οƒ(z)>0.5\sigma(z) > 0.5, we call it "class 1." Otherwise, "class 0."

Strengths: simple, provides probabilities, interpretable.

Limitations: the decision boundary is linear. For complex problems, it's not enough.

Logistic regression curve with class points
This image illustrates how logistic regression separates two classes (0 and 1) using a sigmoid function. It shows the non-linear decision boundary generated by the model.Source : GoPenAI

SVM (Support Vector Machine): Maximum Separation

SVMs (Support Vector Machines) are algorithms that look for the optimal separation boundary between two classes. Imagine two groups of points (spam vs not spam) on a plane. SVMs look for the line that separates them with the maximum margin: the distance between the line and the closest points.

It's like wanting the widest possible highway between two groups of enemy houses.

In this two-dimensional space, the 'boundary' is the black line, the 'support vectors' are the circled points (closest to the boundary), and the 'margin' is the distance between the boundary and the blue and red lines.
In this two-dimensional space, the 'boundary' is the black line, the 'support vectors' are the circled points (closest to the boundary), and the 'margin' is the distance between the boundary and the blue and red lines.Source : Data Analytics Post

With the kernel trick, SVMs also handle non-linear problems: they project the data into a higher-dimensional space where a straight boundary becomes possible again. The image below shows the idea.

Strengths: excellent in high dimensions, robust with little data.

Limitations: slow on very large datasets, less interpretable.

Transformation from input space to feature space
The image illustrates the transformation of an input space into a feature space via a phi function. Data points that were initially not linearly separable in the input space become linearly separable in the feature space.Source : Medium

Decision Trees: The Human Algorithm

Divides the space hierarchically with binary questions.

If Area > 650 sq ft
  If Neighborhood = Central
    -> High price
  Else
    -> Medium price
Else
  -> Low price

It's exactly how a human decides.

Strengths: very readable, no need to normalize data, handles mixed numeric/categorical features.

Limitations: a strong tendency to overfit (learning the training data by heart instead of extracting a rule from it) and real instability: changing a single example can produce a completely different tree.

Decision tree for evaluating cardiac risks
This decision tree illustrates a supervised learning example for predicting heart attack risks based on age, weight, and smoking status. It shows how decision nodes and leaves classify individuals.Source : Medium

Random Forests: Many Trees, One Decision

Trains 100 or 1,000 different decision trees (each on slightly different data). For a prediction, asks all trees to vote.

100 trees vote. 60 say "spam," 40 say "not spam." Result: spam.

Strengths: very robust, little overfitting, almost no hyperparameters to tune.

Limitations: less readable than a single tree, slower to train.

Gradient Boosting: The Winning Alternative

XGBoost, LightGBM, CatBoost outperform random forests. Each new tree corrects the errors of the previous one. It's often the winner of Kaggle competitions on tabular data.

Gradient Boosting diagram
This diagram illustrates the principle of random forests where multiple decision trees (weak learners) are combined sequentially to improve prediction. Each new tree corrects the errors of the previous one, resulting in a more performant model.Source : Medium

KNN (K-Nearest Neighbors): The Lazy Algorithm

The K-Nearest Neighbors algorithm is disarmingly simple: when you need to classify a new example, look at the K closest training examples. Majority vote.

A new customer arrives. Look at their 5 nearest neighbors in the training data. 4 bought, 1 didn't. Prediction: will buy.

Strengths: no training at all, very simple.

Limitations: slow at prediction time, since it must compare the new case against every stored example; and it suffers from the curse of dimensionality, when examples are described by hundreds of variables, every point ends up roughly the same distance from every other, and "nearest neighbor" stops meaning anything.

Illustration of how the K-NN algorithm works
The image shows how a new data sample is classified into category A after applying the K-NN algorithm, illustrating its supervised classification principle based on neighbor proximity.Source : qkzk

Choosing Your Algorithm: The Practical Guide

SituationAlgorithmReason
Little data, high dimensionSVMGeneralizes well
Tabular data, max performanceXGBoost/LightGBMWins competitions
I want to understandLogistic regression, treeInterpretable
I'm starting outLinear/logistic regressionFast and basic
Images, text, audioDeep neural networksThe only family that handles raw data of this kind
Mixed data, basicRandom ForestRobust and easy
The Secret of Real Practitioners

ALWAYS start with a stupidly simple reference model: linear regression for regression, logistic for classification. Five minutes of work, and it gives you the score to beat. Only if that score is not enough do you bring out the heavy machinery.

Why This Matters

Supervised learning is the foundation of the large majority of ML (Machine Learning) applications running in production. This is how you predict prices, detect fraud, and diagnose diseases. It's the best understood paradigm, the most debuggable, and the most reliable. Mastering it means having the foundations of applied AI.

Check your understanding0 / 5

1. Predicting the exact price of an apartment (say 420,000 euros) is a problem of…

2. A cancer screening model answers Β« no cancer Β» for every patient and scores 99% accuracy, because 99% of patients are healthy. What should you conclude?

3. In bank fraud detection, which metric do you mostly want high, and why?

4. Logistic regression is used to…

5. What happens if some of the labels in the training set are wrong?