KS5H019/H119 F201 TA3 32 min read 10 question quiz 21 exam marks

F201 TA3: Big Data with Machine Learning and AI

What machine learning actually is, the three kinds of learning, how a model is trained and tested, and how to tell whether it works.

AI, machine learning and deep learning

These three are often used as synonyms and are not.

TermWhat it means
Artificial intelligenceThe broad field of making systems perform tasks that appear to need intelligence. Includes rule based systems with no learning at all
Machine learningSystems that improve at a task by finding patterns in data rather than by being explicitly programmed with rules
Deep learningMachine learning using neural networks with many layers, which is what made image, speech and language processing work

They nest: deep learning is part of machine learning, which is part of AI.

Why big data and machine learning arrived together

A learning algorithm needs examples, and its performance improves with the number of good ones. Two things made modern machine learning practical at the same moment: enough data, because systems began logging everything, and enough compute, because GPUs could do the arithmetic in parallel. Neither alone was sufficient, which is why techniques invented decades earlier only became useful recently.

The traditional approach against the learned one

To detect spam with rules, a programmer writes conditions: these words, these senders, these patterns. Every new trick needs a new rule, written by a human, forever. With machine learning, the system is given a large set of messages already labelled spam or not spam, finds the features that distinguish them, and is retrained as the tricks change. The rules are no longer written; they are derived, which is both the power and the problem, because nobody chose them and they can be hard to inspect.

The definition that earns the mark

"Machine learning is a system that learns patterns from data in order to make predictions or decisions, improving with more examples, rather than following rules written explicitly by a programmer."

Machine learning applications by sectorMachine learning applications by sector, with the techniques behind them. Retail: recommendation, demand forecasting and churn prediction, using classification and regression. Finance: fraud detection, credit scoring and money laundering checks, using classification and anomaly detection. Healthcare: image diagnosis, triage and readmission risk, using classification and deep learning. Manufacturing: predictive maintenance and visual quality inspection, using regression and anomaly detection. Transport: routing, demand prediction and autonomous control, using reinforcement learning and regression. Energy: load forecasting, grid balancing and fault prediction, using regression and anomaly detection. Agriculture: yield prediction and disease detection from imagery, using regression and deep learning. Public sector: demand planning, fraud detection and casework triage, using classification and clustering. Almost all of it reduces to classification, regression, clustering or anomaly detection: the sector changes the data and the cost of being wrong, while the technique barely changes at all.The same few techniques, across every sectorRetailrecommendation · demand forecasting · churnclassification, regressionFinancefraud detection · credit scoring · laundering checksclassification, anomaly detectionHealthcareimage diagnosis · triage · readmission riskclassification, deep learningManufacturingpredictive maintenance · visual inspectionregression, anomaly detectionTransportrouting · demand prediction · autonomous controlreinforcement, regressionEnergyload forecasting · grid balancing · fault predictionregression, anomaly detectionAgricultureyield prediction · disease detection from imageryregression, deep learningPublic sectordemand planning · fraud · casework triageclassification, clusteringAlmost all of this is classification, regression, clustering or anomaly detection.The sector changes the data and the cost of being wrong. The technique barely changes at all.
Learn the four task types properly and every application in the paper becomes one of them.

The three kinds of learning, and the tasks

TypeWhat it is givenWhat it learnsExamples
SupervisedLabelled examples: inputs with the right answerTo predict the label for new inputsSpam detection, credit scoring, image classification, price prediction
UnsupervisedUnlabelled dataStructure that was not specified: groups, oddities, dimensionsCustomer segmentation, anomaly detection, topic discovery
ReinforcementAn environment, actions and rewardsA policy of actions that maximises long run rewardGame playing, robotics, routing, energy control

The tasks within supervised learning

  • Classification predicts a category: spam or not, which of ten digits, will churn or will not
  • Regression predicts a number: a price, a demand, a time to failure

And within unsupervised learning

  • Clustering groups similar records, without being told the groups
  • Anomaly detection finds records unlike the rest, which is how fraud and faults surface
  • Dimensionality reduction compresses many variables into a few that carry most of the signal

The vocabulary of a model

TermMeaning
FeatureAn input variable the model uses
LabelThe correct answer, in supervised learning
Feature engineeringCreating useful inputs from raw data, which often matters more than the algorithm
Training setThe data the model learns from, typically most of it
Validation setHeld back to tune the model and compare options
Test setHeld back, untouched, to estimate real performance once
OverfittingLearning the training data including its noise, so performance collapses on new data
UnderfittingToo simple to capture the real pattern, so it is poor on everything
HyperparameterA setting chosen before training, such as depth or learning rate
Never evaluate on the training data

A model tested on what it learned from will look excellent and tell you nothing. The test set has to be data the model has never seen, and it is used once, at the end. Testing repeatedly on it turns it into another training set.

Supervised, unsupervised and reinforcement learningThe three kinds of machine learning, distinguished by what each one is given. Supervised learning is given labelled examples, each input paired with the right answer, and learns to predict that label for new data; its two tasks are classification, predicting a category such as spam or not spam, and regression, predicting a number such as a price or a time to failure, with practical uses including spam filtering, credit scoring and image diagnosis. Unsupervised learning is given unlabelled data with no answers at all and finds structure nobody specified; its tasks include clustering, which groups similar records, and anomaly detection, which finds records unlike the rest, with practical uses including customer segmentation and fraud or fault detection. Reinforcement learning is given an environment, a set of possible actions and a reward signal, and learns a policy of actions that maximises long run reward through trial and error with delayed consequences; it has no fixed dataset, because the data is generated by acting, and it is used in game playing, robotics, routing and energy control.Three kinds of learning, told apart by the inputSUPERVISEDGIVENlabelled examples: input + the right answerLEARNSlearns to predict the label for new data• Classification: spam or not, which digit, will churn• Regression: a price, a demand, a time to failureIN PRACTICESpam filter, credit scoring, image diagnosisUNSUPERVISEDGIVENunlabelled data: no answers at allLEARNSfinds structure nobody specified• Clustering: groups of similar records• Anomaly detection: records unlike the restIN PRACTICECustomer segmentation, fraud and fault detectionREINFORCEMENTGIVENan environment, actions, and a reward signalLEARNSlearns a policy that maximises long run reward• Trial and error, with delayed consequences• No dataset: the data is generated by actingIN PRACTICEGame playing, robotics, routing, energy control
The question that tells them apart is simple: what was the model given?
A neural network, layer by layerA small neural network drawn layer by layer from left to right. The input layer has four nodes, one per feature of the record being judged: the amount, the hour, the country and the customer's history. A first hidden layer of five nodes follows, and each of those nodes combines every input using its own set of weights. A second hidden layer of four nodes combines what the first layer produced, which is why these are called combinations of combinations. At the end a single output node produces one number, here 0.93, the probability that the transaction is fraudulent. Every line between nodes is a weight: a thicker line is a stronger weight, a teal line pushes the next node up and a coral one pushes it down. Training is the repeated process of predicting, measuring the error against the known labels and nudging all of those weights to reduce it, over and over. The network is a sequence of transformations, each one working on the output of the last, rather than a single step.amount£950hour03:12countryoverseashistorynew account0.93fraud?Inputone node perfeatureHidden 1each node mixesevery inputHidden 2mixes the mixesOutputone number outTraining:predictmeasure the errornudge every weightrepeat12345
  1. The input layer: one node per feature of the record.
  2. A hidden layer: each node combines every input, with its own weights.
  3. A second hidden layer: it combines what the first layer produced.
  4. The output layer: one number, here the probability of fraud.
  5. Training adjusts every weight, over and over, to reduce the error.
Deep learning is this, with far more layers. The depth in the name is literally the number of hidden layers.

Measuring whether a model works

The confusion matrix

For a classifier, every prediction falls into one of four cells.

Predicted positivePredicted negative
Actually positiveTrue positive (TP)False negative (FN), a miss
Actually negativeFalse positive (FP), a false alarmTrue negative (TN)

The measures that come out of it

MeasureFormulaThe question it answers
Accuracy(TP + TN) / allWhat proportion of predictions were right?
PrecisionTP / (TP + FP)When it says positive, how often is it right?
RecallTP / (TP + FN)Of the real positives, how many did it find?
F1 scorethe harmonic mean of precision and recallA single figure balancing the two

Why accuracy alone is misleading

Suppose 1 in 100 transactions is fraudulent. A model that predicts "not fraud" every single time is 99% accurate and catches nothing at all. Its recall is zero. On an imbalanced problem, accuracy measures the imbalance rather than the model, which is why precision and recall are reported together.

Precision against recall is a business decision

Tightening a model to raise precision lowers recall and vice versa. Which matters more depends entirely on the cost of each error:

  • Cancer screening: a missed case is catastrophic, a false alarm means a further test. Favour recall.
  • Spam filtering: a missed spam is an annoyance, a blocked job offer is serious. Favour precision.
  • Fraud blocking: blocking a real customer's card loses them; missing a fraud costs money. The threshold is a commercial judgement, and it is usually set so a human reviews the uncertain middle.

For regression, the equivalent measures are mean absolute error and root mean squared error, in the units of the thing being predicted, which is why an error of "£38 per order" communicates better than any coefficient.

Applications across industries

SectorApplication
RetailRecommendation, demand forecasting, dynamic pricing, churn prediction
FinanceFraud detection, credit scoring, anti money laundering, trading
HealthcareImage diagnosis, triage, drug discovery, readmission risk
ManufacturingPredictive maintenance, visual quality inspection, yield optimisation
TransportRouting, demand prediction, autonomous driving, maintenance
EnergyLoad forecasting, grid balancing, fault prediction
AgricultureYield prediction, disease detection from imagery, irrigation control
Public sectorDemand planning, fraud detection, triage of casework
Name the measure and the cost of the error

"Recall matters more here, because a missed fraudulent transaction is an unrecoverable loss while a false positive costs one customer service call, so the threshold should be set low and the borderline cases sent for human review." Measure, reason, and the operational consequence.

Training, validation, test and monitoringHow a supervised model is trained and judged. The data is split first, typically seventy per cent for training, which the model learns from, fifteen per cent for validation, used for tuning and comparing options, and fifteen per cent held back as a test set to be used once at the very end. The split happens before any exploration, because anything learned from the test set leaks into the model. Training itself is a loop: the model predicts, the error is measured against the known labels, the parameters are adjusted to reduce it, and the cycle repeats thousands of times. Validation data can be consulted as often as needed, since it is not learned from directly, and it is how model types and settings are chosen. The test set is used exactly once, because tuning against it turns it into training data and its estimate of real performance becomes worthless. After deployment the model must be monitored for drift and retrained, because the world it was trained on keeps changing.How a model is actually trained and judgedTHE SPLITTRAINING 70%the model learns from thisVALIDATIONtuning and comparisonTESTused once, at the endSplit before you explore. Anything you learn from the test set leaks into the model.predictmeasure the erroragainst the labelsadjustthe parametersrepeat, thousands of timesTraining is this loop: predict, measure the error, adjust, repeat.Validation picks between models and settings. Use it as often as you like.Test once. Tune against the test set and it becomes training data and tells you nothing.monitor for drift, and retrainA deployed model decays, because the world it was trained on keeps moving.
The test set is used once. That single rule is what makes a performance figure mean anything.
A confusion matrix with precision and recall worked throughA confusion matrix for a spam filter tested on one thousand emails. The four cells: 180 true positives, spam correctly caught; 40 false negatives, spam that got through; 20 false positives, real emails wrongly blocked; and 760 true negatives, legitimate mail correctly delivered. Four measures follow. Accuracy is true positives plus true negatives over the total, 180 plus 760 over 1000, which is 94 per cent. Precision is true positives over all predicted positives, 180 over 200, which is 90 per cent, and answers how often the filter is right when it declares something spam. Recall is true positives over all actual positives, 180 over 220, which is about 82 per cent, and answers how much of the real spam the filter found. The F1 score is the harmonic mean of precision and recall, about 86 per cent, giving one figure that balances the two. The warning underneath is the important part: a filter that simply marked nothing as spam would score 78 per cent accuracy on this same test while catching nothing at all, because on an imbalanced problem accuracy largely measures the imbalance, which is why precision and recall are always reported together.1,000 emails through a spam filterPREDICTED SPAMPREDICTED NOT SPAMACTUALLY SPAMACTUALLY NOT SPAMTRUE POSITIVE180caught spamFALSE NEGATIVE40spam that got throughFALSE POSITIVE20real email wrongly blockedTRUE NEGATIVE760correctly deliveredACCURACY(TP + TN) / all= (180 + 760) / 100094%right overallPRECISIONTP / (TP + FP)= 180 / 20090%when it says spam, how often rightRECALLTP / (TP + FN)= 180 / 22082%of the real spam, how much foundF1 SCOREharmonic mean= of 90 and 8286%one figure balancing bothA filter that marked nothing as spam would score 78% accuracy and catch nothing at all.On an imbalanced problem accuracy measures the imbalance. Always report precision and recall.
Learn these four numbers and the four formulas. It is the most reliable question in the unit.

Classifier scorer

Move the threshold and watch precision and recall trade against each other. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.

Underfitting, a good fit and overfittingThe same twenty noisy data points with three different models drawn over them. The underfitted model is a straight line: it is too simple to capture the gently curving shape of the data, so it has high error both on the training points and on anything new, because the model has too little capacity. The good fit is a smooth curve that follows the underlying pattern while passing between the points rather than through them; it accepts some error on the training data deliberately, because the noise is not worth fitting. The overfitted model is a wildly wiggling curve that passes through every single point, achieving almost zero error on the training data, and that is exactly why it fails on new data: it has learned the noise as though it were signal. A new unseen point lands far from the overfitted curve while sitting close to the good fit. Overfitting is reduced by training on more data, by using a simpler model with fewer features, and by stopping training when performance on a held-back validation set stops improving.The same twenty points, three modelsinputoutputUNDERFIT: a straight lineHigh error on the training data and on new data. The model has too little capacity.GOOD FIT: follows the patternSome error on the training data on purpose, because the noise is not worth fitting.OVERFIT: through every pointNear zero error on the training data, which is exactly why it will fail on new data.a new, unseen pointFix it with more data, a simpler model, or early stopping on a validation set.
A model with zero error on its training data has usually memorised it rather than learned anything.

Key terms you must be able to define

Artificial intelligence
The field of making systems perform tasks that appear to require intelligence.
Machine learning
Systems that learn patterns from data rather than following explicitly programmed rules.
Deep learning
Machine learning using neural networks with many layers.
Supervised learning
Learning from labelled examples to predict labels for new data.
Unsupervised learning
Finding structure in unlabelled data, such as clusters or anomalies.
Reinforcement learning
Learning a policy of actions through rewards and penalties from an environment.
Classification
Predicting which category something belongs to.
Regression
Predicting a numerical value.
Clustering
Grouping similar records without being told the groups in advance.
Feature
An input variable used by a model.
Label
The known correct answer attached to a training example.
Training data
The data a model learns from.
Test data
Held-back data, never seen in training, used to estimate real performance.
Overfitting
Learning the training data including its noise, so performance on new data collapses.
Confusion matrix
A table of true and false positives and negatives for a classifier.
Precision
Of the cases predicted positive, the proportion that really are.
Recall
Of the real positive cases, the proportion the model found.
Accuracy
The proportion of all predictions that were correct.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineArtificial intelligence
AnswerThe field of making systems perform tasks that appear to require intelligence.
DefineMachine learning
AnswerSystems that learn patterns from data rather than following explicitly programmed rules.
DefineDeep learning
AnswerMachine learning using neural networks with many layers.
DefineSupervised learning
AnswerLearning from labelled examples to predict labels for new data.
DefineUnsupervised learning
AnswerFinding structure in unlabelled data, such as clusters or anomalies.
DefineReinforcement learning
AnswerLearning a policy of actions through rewards and penalties from an environment.
DefineClassification
AnswerPredicting which category something belongs to.
DefineRegression
AnswerPredicting a numerical value.

Reach the top grade on this topic

This topic area rewards arithmetic and judgement together. Be able to compute precision and recall from a confusion matrix, state what each means in the scenario's own terms, and then say which one the organisation should optimise and what that costs. An answer that defines the terms without applying them to the scenario stays in the lower bands.

Mistakes that cost marks here

Avoid these
  • Using AI, machine learning and deep learning as synonyms.
  • Quoting accuracy on an imbalanced problem without mentioning precision and recall.
  • Evaluating a model on its training data.
  • Confusing overfitting with underfitting.
  • Describing clustering as supervised. Nobody provides the groups.
  • Treating a model's output as fact rather than as a prediction with an error rate.
Fun fact

A model that predicts a rare disease by always answering 'no' can be 99% accurate and completely useless. That single observation is why accuracy is never reported alone, and it is the most reliable exam question in this topic area.

Knowledge check

0 of 10 answered
1Which type of learning uses labelled training data?
2Grouping customers into segments without being told the segments is:
3A model predicts a house price. What kind of task is that?
41 in 100 transactions is fraud. A model predicts 'not fraud' every time. What is its accuracy and recall?
5What is overfitting?
6Precision answers which question?
7For cancer screening, which measure should usually be favoured?
8Why must the test set be kept separate from training?
9Which is reinforcement learning?
10Deep learning is best described as:
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

21 marks
1State the difference between supervised and unsupervised learning.2 marks
State

Mark scheme0 / 2
  • LSupervised learning uses labelled data to predict a known target
  • LUnsupervised learning finds structure in unlabelled data
Model answer

Supervised learning is trained on labelled examples, where each input has a known correct answer, and learns to predict that answer for new data. Unsupervised learning is given unlabelled data and finds structure within it, such as clusters of similar records or anomalies, without being told what to look for.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A spam filter was tested on 1,000 emails. It correctly identified 180 spam emails, wrongly flagged 20 legitimate emails as spam, and missed 40 spam emails.Calculate its precision and recall, and explain which matters more for a spam filter.6 marks
Calculate

Mark scheme0 / 6
  • LPrecision is calculated as 180/200
  • LPrecision is stated as 90%
  • LRecall is calculated as 180/220
  • LRecall is stated as about 82%
  • LPrecision is identified as more important for a spam filter
  • LJustified by the cost of the error
Model answer

Precision is true positives divided by all predicted positives: 180 / (180 + 20) = 180 / 200 = 90%. Recall is true positives divided by all actual positives: 180 / (180 + 40) = 180 / 220 = 81.8%. For a spam filter, precision matters more. A false negative means one piece of spam reaches the inbox, which costs the user a moment's irritation and nothing else. A false positive means a legitimate email is hidden in a folder the user may never check, and if that email is a job offer, an invoice or a medical appointment the consequence is serious and the user is not even aware anything was lost. A spam filter is therefore tuned to be cautious about declaring spam, accepting a lower recall in exchange for very high precision.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain what overfitting is and describe two ways it can be reduced.5 marks
Explain

Mark scheme0 / 5
  • LOverfitting is learning the training data including its noise
  • LThe consequence on unseen data
  • LOne valid mitigation
  • LIt is explained
  • LA second valid mitigation, explained
Model answer

Overfitting happens when a model learns the training data too closely, capturing not only the real pattern but also the noise and the accidents of that particular sample. The symptom is a model that performs almost perfectly on the data it was trained on and markedly worse on data it has never seen, because it has effectively memorised rather than generalised. One way to reduce it is to use a simpler model or fewer features, since a model with less capacity cannot fit the noise; a shallow decision tree, or a pruned one, is forced to find the broad pattern. A second is to train on more data, because noise does not repeat while the real pattern does, so additional examples dilute the accidental features. Alongside both, holding back a validation set and stopping training when validation performance stops improving detects overfitting as it begins rather than after the model is deployed.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A hospital is considering a machine learning model to predict which patients are at risk of readmission within 30 days.Discuss how such a model would be developed and evaluated, and the issues the hospital should consider before using it.8 marks
Discuss

Mark scheme0 / 8
  • LData and features are identified
  • LIt is identified as supervised classification with labels from history
  • LTrain, validation and test split is described
  • LAppropriate evaluation measures are chosen
  • LRecall is prioritised with a reason
  • LBias in the training data is addressed
  • LExplainability and clinical oversight are addressed
  • LLegal, ethical or monitoring issues with a judgement
Model answer

The task is supervised classification, and the labels already exist in the hospital's own history: for every past discharge it is known whether the patient was readmitted within thirty days. Features would come from the records the hospital already holds, such as age, primary and secondary diagnoses, length of stay, number of previous admissions, prescribed medication, and whether the patient lives alone, with feature engineering likely to matter more than the choice of algorithm. The data would be split into training, validation and test sets, and the split should be by time rather than at random, training on earlier years and testing on the most recent, because that is the only way to estimate how the model will behave on future patients rather than on contemporaries of its training data. Evaluation must not rest on accuracy. Readmission is a minority outcome, so a model predicting that nobody is readmitted would score well and be worthless; the hospital needs the confusion matrix and both precision and recall. Recall should be prioritised, because a missed high risk patient is a patient who comes back seriously unwell, while a false positive costs a follow-up phone call, so the threshold should be set to catch cases and the resulting workload planned for. Three issues then need settling before any use. The first is bias: if historic care was less effective for a deprived or minority group, the model learns that pattern as though it were clinical fact, so performance has to be measured separately for each group rather than only overall, and an unequal error rate treated as a defect. The second is explainability: a clinician cannot act on a score with no reason attached, and the hospital cannot defend a decision it cannot explain, so a model whose contributing factors can be surfaced is worth more here than a slightly more accurate opaque one. The third is legal and operational: this is special category health data, which means a Data Protection Impact Assessment, transparency with patients, and no solely automated decision with significant effects. Taken together, the model should be deployed as decision support that flags patients for a clinician to review, never as an automated discharge or intervention decision, with its performance and its error rates by group monitored continuously and the model retrained as practice and population change.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 21