انتقل إلى المحتوى
لندن، المملكة المتحدة · تأسست عام 1994
العربية

Unit 2: Supervised Learning

How models learn to predict numbers and categories from labelled examples, the most widely used supervised algorithms, and how to choose between them.

Unit 2 of 5 · about 54 minutes

2.1 Regression: predicting numbers

Regression is the supervised learning task of predicting a numerical value, such as a price, a quantity, a duration or a score. It is one of the oldest and most widely used techniques in statistics and machine learning, and it is an excellent place to understand how models learn.

Linear regression

The simplest regression model, linear regression, assumes that the label can be approximated by adding up the features, each multiplied by a weight, plus a constant. Imagine predicting the price of a flat from its floor area. Plot past sales on a chart with floor area along the bottom and price up the side, and the points form a rough upward band. Linear regression finds the straight line that best fits that band. The slope of the line tells you roughly how much the price rises for each extra square metre; the point where it crosses the vertical axis is the constant, often called the intercept.

With several features, such as floor area, number of bedrooms and distance to the nearest station, the model learns one weight, or coefficient, for each. A positive coefficient means the prediction rises as that feature increases; a negative one means it falls. This makes linear models relatively easy to interpret, which is a major reason for their continued popularity in fields such as economics, finance and healthcare.

How the model learns

Learning means finding the weights that make predictions as close as possible to the actual labels in the training data. The gap between a prediction and the true value is called the error or residual. The model needs a single number summarising all the errors, called a loss function. A common choice is the mean squared error: square each error, so that large mistakes count much more than small ones and positive and negative errors do not cancel out, then take the average. Training adjusts the weights to make this loss as small as possible.

For linear regression the best weights can be calculated directly. For many other models, they are found step by step using a method called gradient descent: start with rough weights, work out in which direction each weight should move to reduce the loss, take a small step in that direction and repeat many times. Gradient descent is also how neural networks learn, so the idea is worth remembering.

Remember: Training means minimising a measure of error on the training data. A model can only be as good as the match between that measure and what you actually care about.

Beyond straight lines

Real relationships are often not straight. House prices may rise steeply with size up to a point and then level off; sales may follow seasonal patterns. Several approaches handle this:

  • Adding transformed features, such as the square of a value or the logarithm of income, allows a linear model to fit curves.
  • Including interaction features, such as size multiplied by location, captures effects that depend on combinations.
  • Using non-linear models, such as decision trees and their ensembles, which are covered later in this unit.

Regularisation

When there are many features, a model may assign large weights to features that happen to fit the training data by chance. Regularisation adds a penalty for large weights to the loss function, encouraging simpler models that generalise better. Two common versions are known as ridge and lasso regression; lasso can shrink some weights to exactly zero, effectively selecting the most useful features.

Interpreting with care

Coefficients describe associations in the data, not necessarily causes. If two features are closely related, such as floor area and number of rooms, their individual coefficients can be unstable and misleading even when predictions are good. Regression results should always be interpreted with domain knowledge.

Common mistakes

  • Extrapolating far beyond the range of the training data, for example predicting prices for properties much larger than any in the dataset.
  • Ignoring outliers, such as data-entry errors, that can pull a line badly off course.
  • Treating a strong fit on training data as proof that the model will work on new data.

In practice

Regression is a sensible starting point for many business prediction problems: forecasting demand, estimating delivery times, predicting customer lifetime value or setting prices. Even when more complex models are used eventually, a well-built linear regression provides a transparent baseline and often reveals which factors matter most. When presented with regression results, ask about the range of the data, how outliers were handled and how the model performed on unseen data.

2.2 Classification: predicting categories

Classification is the supervised learning task of assigning examples to categories, called classes. When there are two classes, such as spam or not spam, it is called binary classification. When there are more, such as routing an enquiry to billing, technical support or sales, it is multi-class classification. Classification underpins fraud detection, medical screening support, document sorting, quality inspection and many other applications.

Probabilities and thresholds

Most classification models do not simply output a class. They output a score or probability, such as a 0.83 chance that a transaction is fraudulent. A decision threshold then turns the score into a decision: for example, flag every transaction with a score above 0.5. The threshold is a business choice, not a technical one. Lowering it catches more fraud but also flags more genuine transactions; raising it does the opposite. Choosing well depends on the relative costs of the two kinds of mistake.

Logistic regression

Despite its name, logistic regression is a classification method. It works like linear regression, combining features with weights, but passes the result through an S-shaped function that squeezes any number into a probability between 0 and 1. It is fast, works well when the relationship between features and outcome is fairly simple, and its weights can be interpreted, making it widely used in credit scoring and other regulated settings.

k-nearest neighbours

The k-nearest neighbours method classifies a new example by finding the k most similar examples in the training data and taking a vote. If, of the five most similar past customers, four cancelled, the new customer is predicted to cancel. It is intuitive and needs no training as such, but it can be slow with large datasets, is sensitive to how features are scaled, and struggles when there are many features.

Decision trees

A decision tree makes predictions by asking a sequence of yes or no questions about the features, like a flowchart. For a loan application it might ask: is income above a certain level? If yes, is existing debt low? Each path ends in a leaf giving a prediction. The algorithm chooses questions that best separate the classes in the training data. Trees work for both classification and regression.

Decision trees are easy to visualise and explain, handle numerical and categorical features and capture non-linear relationships. Their main weakness is that a deep tree can keep splitting until it fits the training data almost perfectly, including its noise, and then performs poorly on new data. Limiting the depth of the tree helps.

Tip: When a classification model is proposed, always ask what threshold will be used and how it was chosen. The same model can behave very differently in practice depending on that single number.

Imbalanced classes

In many important problems one class is rare. Fraud may affect a tiny fraction of transactions; serious equipment faults may be rarer still. A model that always predicts "not fraud" could then be correct almost all the time while being completely useless. Ways to handle imbalance include:

  • Using evaluation measures that focus on the rare class, discussed in a later unit.
  • Giving errors on the rare class greater weight during training.
  • Resampling the training data so the rare class is better represented, while keeping the test data realistic.
  • Choosing the threshold carefully based on costs.

Multi-class and multi-label problems

Some algorithms handle multiple classes directly; others combine several binary models. In multi-label problems, an example can belong to several classes at once, such as a news article tagged as both "politics" and "economy". Being clear about which situation applies is part of defining the problem properly.

In practice

When designing a classification system, define the classes precisely, check that labelled examples are consistent and representative, decide what each type of error costs and agree how borderline cases will be handled, often by sending them to a person for review. A system that sorts most cases automatically and routes uncertain ones to people frequently delivers most of the benefit with much lower risk.

2.3 Ensembles and choosing an algorithm

No single algorithm is best for every problem. Experienced practitioners choose methods based on the type and amount of data, the need for interpretability, the cost of errors and practical constraints such as speed. One family of methods has proved especially effective for the kind of tabular data common in business: ensembles.

What an ensemble is

An ensemble combines the predictions of many models to produce a better overall prediction. The idea resembles asking several people for an estimate and averaging their answers: individual errors tend to cancel out, provided the people do not all make the same mistakes. In machine learning, ensembles are usually built from many decision trees.

Random forests

A random forest trains hundreds of decision trees, each on a slightly different random sample of the training data and considering a random subset of features at each split. Each tree is somewhat different, and each on its own may overfit. But when their predictions are combined, by voting for classification or averaging for regression, the result is usually far more accurate and stable than any single tree. This approach of training models on different samples and combining them is called bagging. Random forests need relatively little tuning and are a strong general-purpose choice.

Gradient boosting

Gradient boosting builds trees one after another, with each new tree focusing on correcting the errors made by the trees before it. The final prediction adds up the contributions of all the trees. Gradient-boosted trees, available in several popular open-source libraries, often achieve some of the best results on structured, tabular data, and they are widely used in industry. They do require more careful tuning than random forests to avoid overfitting.

Interpretability

Ensembles of hundreds of trees are much harder to interpret than a single tree or a linear model. Techniques for explainability help. Feature importance measures indicate which features influence predictions most overall. Methods such as SHAP values estimate how much each feature contributed to an individual prediction, which helps explain particular decisions to the people affected. Such explanations describe how the model behaves; they do not prove that features cause outcomes.

Remember: Start simple. A well-prepared linear model or small decision tree provides a baseline and helps you understand the data. Move to more complex models only when they deliver a meaningful improvement on unseen data.

Choosing an algorithm

MethodStrengthsLimitations
Linear and logistic regressionFast, transparent, good baseline, works with limited dataMisses complex non-linear patterns unless features are engineered
Decision treeEasy to explain and visualise; handles mixed dataOverfits easily; unstable with small changes to data
k-nearest neighboursSimple and intuitiveSlow on large data; sensitive to scaling and many features
Random forestAccurate, robust, little tuning neededLess interpretable; larger models
Gradient boostingOften the most accurate on tabular dataNeeds careful tuning; less interpretable
Neural networksExcellent for images, audio and text, and very large datasetsNeed lots of data and computing power; hard to interpret

Questions that guide the choice

  1. What kind of data is it: tables of numbers and categories, text, images or time series?
  2. How much labelled data is available?
  3. Must individual decisions be explained to customers, regulators or staff?
  4. How quickly must predictions be made, and on what hardware?
  5. How will the model be maintained, and by whom?

The no free lunch idea

A well-known result in machine learning, often summarised as "no free lunch", states that no single algorithm performs best across all possible problems. In practice, this means comparing several sensible candidates on validation data rather than relying on reputation. Automated machine learning (AutoML) tools can try many algorithms and settings systematically, but they still depend on good problem definition, data preparation and careful evaluation.

In practice

For a typical business problem with tabular data, a sensible sequence is: build a simple baseline, try a regularised linear model, then a random forest and a gradient-boosted model, and compare all of them fairly on the same validation data. Choose the simplest model that meets the performance requirement, and weigh any accuracy gain against the loss of transparency.

Case study: Prioritising maintenance at a water utility

Riverside Water Services, a fictional regional water company, wanted to predict which sections of water main were most likely to burst in the coming year, so that limited replacement budgets could be targeted. It had records of pipe material, age, diameter, soil type, pressure and past bursts for thousands of pipe sections.

The analytics team first built a simple baseline ranking pipes by age. They then trained a logistic regression model, a random forest and a gradient-boosted model, comparing them on data from the most recent two years that had been held back. The gradient-boosted model identified the most bursts among its highest-ranked pipes, while logistic regression came a reasonably close second.

Because engineers and regulators wanted to understand the reasoning, the team used explanation methods to show which factors drove each pipe's risk score, and engineers reviewed the top-ranked sections before approving work. Bursts were a rare outcome, so the team evaluated performance on how many actual bursts appeared in the top-ranked list rather than overall accuracy.

Activity

Choose a prediction problem from your work or a sector you know. Decide whether it is regression or classification and recommend two algorithms to compare, one simple and one more complex, giving reasons. Then explain how important interpretability is for this problem and why.

Compare with a model answer

A good answer defines the problem clearly, for example predicting whether a job applicant will accept an offer, a binary classification task. It recommends logistic regression as a transparent baseline and gradient boosting or a random forest as a more powerful alternative, explaining that the data is tabular and moderately sized.

On interpretability, it recognises the context: decisions affecting people, such as recruitment, raise fairness and legal concerns in many countries, so understanding which factors drive predictions is important and features that could act as proxies for protected characteristics must be examined carefully. It might conclude that the simpler model is preferable unless the complex one is substantially better. The best answers mention the decision threshold and human review of borderline cases.

Key takeaways

  • Regression predicts numbers; models learn by adjusting weights to minimise a loss function, often using gradient descent.
  • Classification predicts categories, usually via probabilities and a decision threshold that should reflect the costs of different errors.
  • Decision trees are easy to explain but overfit easily; ensembles such as random forests and gradient boosting are more accurate and robust.
  • Imbalanced classes require careful evaluation, weighting and threshold choice, because accuracy alone can be misleading.
  • Choose algorithms by comparing simple and complex candidates fairly on validation data, balancing accuracy against interpretability and practicality.

Unit check

Create a free account to answer the check, save your progress and receive your free certificate.

Create a free account Log in
← Unit 1 Unit 3 →
WhatsApp