Unit 4 of 5 · about 54 minutes
4.1 Types of machine learning
Machine learning is a set of methods that allow computers to learn patterns from data rather than following rules written out explicitly by a programmer. In data science, it is used mainly to make predictions, classify cases and discover structure in data. This lesson introduces the main types and when each is useful.
Features and targets
Two terms appear throughout machine learning. Features (also called inputs, predictors or independent variables) are the pieces of information used to make a prediction, such as a customer's tenure, recent purchases and number of support calls. The target (also called the label, outcome or dependent variable) is the thing being predicted, such as whether the customer will cancel.
Supervised learning
In supervised learning, the model learns from historical examples where the correct answer is known. It studies the relationship between features and target and then applies what it has learned to new cases where the target is unknown. There are two main kinds:
- Regression predicts a number, such as next month's sales, the price a house is likely to sell for or the time a delivery will take.
- Classification predicts a category, such as whether an email is spam, whether a transaction is fraudulent, or which of several product types a customer is most likely to buy.
Common supervised methods
- Linear regression fits a straight-line relationship between features and a numerical target. It is simple, fast and easy to explain, and is often a strong starting point.
- Logistic regression, despite its name, is a classification method that estimates the probability of a case belonging to a category.
- Decision trees split data using a sequence of simple yes-or-no questions. They are easy to visualise, but a single tree can be unstable.
- Ensemble methods, such as random forests and gradient-boosted trees, combine many trees to produce more accurate predictions. They are among the most effective methods for structured, tabular data.
- Neural networks are flexible models made of many connected layers. They excel at unstructured data such as images, audio and text, and underpin modern generative AI, but often need large amounts of data and are harder to interpret.
Unsupervised learning
In unsupervised learning, there is no target to predict. Instead, the model looks for structure in the data. The two most common tasks are:
- Clustering: grouping similar cases together, for example segmenting customers by purchasing behaviour. The results need interpretation by people who understand the business, since the algorithm does not know what the groups mean.
- Dimensionality reduction: summarising many variables into a smaller number that capture most of the variation, which helps with visualisation and can simplify later modelling.
Unsupervised methods are also used for anomaly detection, identifying unusual cases such as faulty sensor readings or suspicious transactions.
Other approaches
Reinforcement learning trains a system to take actions that maximise a reward through trial and error. It is used in areas such as robotics and game playing and is less common in everyday business analytics. Time series forecasting deals specifically with predicting values that change over time, taking account of trends and seasonal patterns.
Remember: the simplest method that meets the need is usually the best choice. Simple models are easier to explain, check and maintain, and complex methods do not always perform better on real business problems.
When machine learning is not the answer
Machine learning is not always appropriate. It may be unnecessary when a clear rule works well, such as flagging every invoice above a fixed value for approval. It may be unsuitable when there is little historical data, when the target is poorly defined or recorded inconsistently, or when decisions must be fully explainable and a model cannot provide that. It can also be risky when the patterns in past data reflect unfair practices that should not be repeated.
Common mistakes
- Choosing a sophisticated algorithm before establishing a simple baseline.
- Predicting a target that does not reflect what the business actually cares about, such as predicting clicks when the goal is purchases.
- Including features that will not be available at the time a prediction is needed.
- Treating clusters as natural facts rather than useful but debatable groupings.
In practice
Think of a decision in your area that might benefit from prediction. Write down the target, the features that would be available at the moment the decision is made, and whether the task is regression or classification. Then describe a simple rule or baseline that the model would need to beat, such as "predict the same value as last month". If a basic rule already performs well enough, machine learning may not be worth the extra effort.
4.2 Training, testing and avoiding overfitting
A model is only useful if it performs well on new data that it has not seen before. It is surprisingly easy to build a model that looks excellent on the data used to create it but fails in real use. This lesson explains how data scientists test models honestly and avoid the most common traps.
Training and test data
The basic principle is to split the available data. The training set is used to fit the model. The test set is kept aside and used only at the end to estimate how the model will perform on new cases. A common split is around 70 to 80 per cent for training and the rest for testing, though the right proportion depends on how much data is available.
Many projects also use a validation set, or a technique called cross-validation, to compare different models and settings during development, so that the test set remains untouched until the final check.
Overfitting and underfitting
Overfitting occurs when a model learns the training data too closely, including its noise and random quirks, rather than the general patterns. It performs very well on training data but poorly on new data. Imagine a student who memorises the answers to past exam papers without understanding the subject: they do well on those papers but struggle with new questions.
Underfitting is the opposite: the model is too simple to capture the real patterns, so it performs poorly on both training and test data.
The aim is a model that captures genuine patterns without memorising noise. A large gap between training performance and test performance is a classic warning sign of overfitting. Techniques to reduce it include using simpler models, gathering more data, removing irrelevant features and applying regularisation, which penalises unnecessary complexity.
Cross-validation
With limited data, a single split can give a misleading result by chance. Cross-validation addresses this by splitting the training data into several parts, or "folds". The model is trained on all but one fold and tested on the remaining one, and this is repeated so that each fold serves once as the test. The results are averaged, giving a more reliable estimate of performance and its variability.
Data leakage
Data leakage happens when information that would not be available at prediction time finds its way into the training data. It produces models that look remarkably accurate in testing and then fail in practice. Common examples include:
- using a feature recorded after the outcome, such as "account closure reason" when predicting whether an account will close;
- carrying out cleaning or scaling steps on the whole dataset before splitting it, so test data influences training;
- having the same customer appear in both training and test sets when predictions are meant for new customers;
- randomly splitting data that is ordered in time, so the model effectively learns from the future.
Tip: if a model's performance looks too good to be true, assume leakage until you have ruled it out. Check which features are most influential and ask whether each would genuinely be known at the moment of prediction.
Time-based splits
When predictions will be made about the future, the most realistic test is to train on older data and test on more recent data. For example, train on data from the first two years and test on the third. This mirrors how the model will actually be used and reveals whether patterns hold over time.
Feature engineering
Much of the improvement in a model often comes not from the algorithm but from feature engineering: creating informative features from raw data. Examples include the number of days since a customer's last purchase, the average order value over the past three months or whether a date falls on a public holiday. Good features usually come from domain knowledge, which is why collaboration with people who understand the business is so valuable.
Common mistakes
- Evaluating a model on the same data used to train it.
- Repeatedly adjusting a model to improve its test score, which gradually turns the test set into training data.
- Ignoring the order of time in data used for forecasting.
- Failing to document which data, features and settings produced the final model.
In practice
If you are reviewing a model built by others, ask how it was tested. Was there a separate test set, and was it untouched during development? Were the data split by time if the model predicts future events? Which features are most important, and would they be available when predictions are made? These questions require no programming knowledge but help to uncover the problems that most often lead to disappointing results.
4.3 Evaluating models and putting them to use
Once a model has been trained and tested, you need to decide whether it is good enough to use. This requires choosing appropriate measures of performance, comparing the model with sensible alternatives and thinking about how it will be used, monitored and explained. Good evaluation always connects technical results to the real-world decision the model supports.
Evaluating regression models
For models that predict numbers, common measures include:
- Mean absolute error (MAE): the average size of prediction errors, in the same units as the target. An MAE of 2.5 days for delivery times is easy to understand.
- Root mean squared error (RMSE): similar, but gives more weight to large errors, which is useful when big mistakes are particularly costly.
- R-squared: the proportion of variation in the target explained by the model. It is widely reported but can be misleading on its own.
Evaluating classification models
For classification, the starting point is the confusion matrix, which counts the four possible outcomes when predicting a yes-or-no target:
| Actually positive | Actually negative | |
|---|---|---|
| Predicted positive | True positive | False positive |
| Predicted negative | False negative | True negative |
From these counts, several measures are calculated:
- Accuracy: the proportion of all predictions that are correct.
- Precision: of the cases predicted positive, the proportion that really are positive.
- Recall (or sensitivity): of the cases that really are positive, the proportion the model finds.
The accuracy trap
Accuracy can be very misleading when one outcome is rare. Suppose only 1 in 100 transactions is fraudulent. A model that simply predicts "not fraud" every time is 99 per cent accurate and completely useless. In such cases, precision and recall are far more informative.
There is usually a trade-off between precision and recall. Many classifiers produce a probability, and you choose a threshold above which a case is flagged. A lower threshold catches more true cases (higher recall) but creates more false alarms (lower precision). The right balance depends on the costs of each kind of error. Missing a fraudulent transaction may be expensive, while a false alarm may only require a quick check, so a fraud team might accept lower precision in return for higher recall.
Remember: no single measure is "best". Choose measures that reflect the real costs and benefits of right and wrong predictions in your context, and agree them with stakeholders before modelling begins.
Compare with a baseline
A model's performance means little in isolation. Always compare it with a baseline, such as predicting the average, predicting the most common class, using last period's value or applying the current business rule. If a complex model barely beats a simple baseline, the extra cost and complexity may not be justified.
Interpretability
Stakeholders often need to understand why a model makes its predictions, and in some contexts there may be legal or ethical expectations of explanation. Simple models can be interpreted directly. For complex models, techniques exist to show which features most influence predictions overall and for individual cases. Explanations help build trust, reveal errors and support fair use.
Deployment and monitoring
A model that performs well today may degrade over time as customer behaviour, products, prices or the wider economy change. This is known as model drift or data drift. Once a model is in use, monitor its inputs and performance, set thresholds that trigger review, and plan for regular retraining. Keep a record of the model's purpose, data, performance, limitations and owner, sometimes called a model card.
Common mistakes
- Reporting only accuracy for a problem where one outcome is rare.
- Choosing the probability threshold without considering business costs.
- Not comparing the model with a simple baseline.
- Checking performance only overall and not for important subgroups.
- Deploying a model with no plan for monitoring.
In practice
For a classification problem in your area, write down the cost of a false positive and the cost of a false negative in practical terms. Decide which matters more and therefore whether precision or recall should be prioritised. Identify a simple baseline the model must beat. Then list two signals that would tell you the model is no longer performing well once it is in use. This short exercise is the core of responsible model evaluation.
Case study: Predicting equipment faults at a water utility
Fenwater, a fictional regional water company, wanted to predict which pumps were likely to fail within the next month so that engineers could inspect them in advance. Its data team trained a model on five years of maintenance records, sensor readings and pump characteristics.
The first version reported excellent performance. A senior engineer questioned one of the most influential features: a field showing whether a pump had been placed on a "watch list". The team discovered that engineers usually added pumps to the list after early signs of failure, so the feature was effectively leaking the outcome. Once it was removed, and the data was split by time rather than randomly, performance fell to a more realistic level.
Failures were rare, so the team focused on recall and precision rather than accuracy. After discussing costs with operations staff, they chose a threshold that caught most failures while keeping the number of inspections manageable. The model clearly outperformed the existing rule of inspecting pumps by age. The team set up monthly monitoring and agreed to retrain the model each year.
Activity
Choose a prediction problem relevant to your work, such as forecasting demand or identifying customers at risk of leaving. Define the target and three features that would be available at prediction time, and state whether it is a regression or classification task. Describe how you would test the model, which performance measures you would use and the baseline it must beat.
Compare with a model answer
A good answer defines a precise target, for example "whether a subscriber cancels within the next 60 days", and recognises this as classification. It lists features genuinely available in advance, such as months since joining, change in usage over the last quarter and number of support contacts, and explicitly excludes anything recorded after cancellation.
For testing, it proposes training on older data and testing on the most recent months to mirror real use. Because cancellations are relatively uncommon, it chooses precision and recall rather than accuracy, and explains which matters more given the cost of a retention offer compared with losing a customer. The baseline is realistic, such as flagging customers whose usage dropped sharply, and the answer mentions monitoring after deployment.
Key takeaways
- Supervised learning predicts a known target through regression or classification, while unsupervised learning finds structure such as clusters.
- The simplest method that meets the need is usually the best starting point, and a baseline should always be established.
- Models must be tested on data they have not seen, and a large gap between training and test performance signals overfitting.
- Data leakage, where information unavailable at prediction time enters training, makes models look far better than they are.
- Accuracy can mislead when outcomes are rare; precision, recall and thresholds should reflect the real costs of each kind of error.
Unit check
Create a free account to answer the check, save your progress and receive your free certificate.
Create a free account Log in