impera Open Impera

IB Diploma Computer Science · Concepts of computer science

Machine learning

1What machine learning is

Machine learning (ML) is a branch of artificial intelligence in which computers learn patterns from data, instead of following rules written by a programmer.

  • In traditional programming, a person writes the rules: input + rules → output.
  • In machine learning, the computer is given examples and works out the rules: input + example outputs → a model (the learned rules), which can then make predictions on new data.

Key terms:

  • Features: the input variables used to make a prediction, such as the size, location and age of a house.
  • Label (target): the answer the model should predict, such as the house's price.
  • Training: adjusting the model's internal values (parameters) to fit the training data.
  • Inference: using the trained model to make predictions on new data.

Examples of ML in use: spam filters, recommendation systems (films, shopping), voice assistants, medical image analysis, fraud detection, self-driving cars and large language models.

Check yourself

In a model that predicts house prices, what is the label?

  • The number of bedrooms

  • The age of the house

  • The house price

  • The location

Show the answer

The house price

The others are features used to predict it.

2Types of machine learning

  • Supervised learning: the training data is labelled with the correct answers.
  • Classification predicts a category: spam or not spam, which animal is in a photo.
  • Regression predicts a number: a house price, tomorrow's temperature.
  • Unsupervised learning: the data has no labels; the model finds structure by itself.
  • Clustering groups similar items, such as segmenting customers by behaviour.
  • Association finds items that occur together ("people who buy X also buy Y").
  • Reinforcement learning: an agent takes actions in an environment and learns from rewards and penalties, by trial and error. Used for game-playing programs (such as AlphaGo) and robot control.
  • Deep learning uses neural networks with many layers. It powers image recognition, translation and generative AI.
Check yourself

A program groups thousands of customers by shopping habits, with no labels given. What kind of learning is this?

  • Supervised learning (regression)

  • Reinforcement learning

  • Unsupervised learning (clustering)

  • Supervised learning (classification)

Show the answer

Unsupervised learning (clustering)

No correct answers are provided.

3Some key algorithms

Linear regression fits a straight line (or plane) $y = mx + c$ through the data, choosing the values that minimise the error between predictions and actual values.

k-nearest neighbours (k-NN) classifies a new item by looking at the $k$ closest items in the training data and taking a majority vote.

Worked example

k-NN with k = 3

  1. Training points: A(1, 2) red, B(2, 1) red, C(6, 5) blue, D(7, 7) blue, E(5, 6) blue. New point Q(3, 2).
  2. Distances from Q: B is $\sqrt{2} = 1.41$, A is 2, C is $\sqrt{18} = 4.24$, E is $\sqrt{20} = 4.47$, D is $\sqrt{41} = 6.40$.
  3. The three nearest are B, A and C: two red, one blue.
  4. Q is classified as red.

Decision trees split the data with a sequence of yes/no questions on the features ("Is income > 30 000?"), ending in leaves that give a prediction. They are easy to explain.

k-means clustering (unsupervised): choose $k$ starting centres, assign each point to its nearest centre, move each centre to the mean of its points, and repeat until the groups stop changing.

k-nearest neighbours with k = 3: the new point takes the majority class of its neighbours

Check yourself

In k-NN, how is a new item classified?

  • By fitting a straight line through all points

  • By a majority vote of the k closest training items

  • By asking a sequence of yes/no questions

  • By random choice

Show the answer

By a majority vote of the k closest training items

The neighbours vote.

4Neural networks

An artificial neural network is loosely inspired by the brain. It is made of layers of nodes (neurons):

  • an input layer (one node per feature), one or more hidden layers, and an output layer.
  • Each connection has a weight. Each node calculates a weighted sum of its inputs, adds a bias, and passes the result through an activation function (such as a step, sigmoid or ReLU function) to decide its output.
  • Training uses backpropagation: the network's error on training examples is measured, and the weights are adjusted a little at a time to reduce it (gradient descent). This is repeated over many passes (epochs).

A neural network with two hidden layers

Worked example

One neuron (a perceptron)

  1. Inputs (1, 0, 1), weights (0.5, −0.4, 0.3), bias −0.2.
  2. Weighted sum: $0.5 \times 1 + (-0.4) \times 0 + 0.3 \times 1 - 0.2 = 0.6$.
  3. With a step activation (output 1 if the sum is above 0), the output is 1.

Convolutional neural networks (CNNs) are specialised for images: their layers scan small filters across the picture to detect edges, then shapes, then objects. Training large networks needs huge datasets and powerful hardware such as GPUs, which do many calculations in parallel.

Check yourself

What is adjusted during the training of a neural network?

  • The name of the activation function used

  • The labels attached to the training data

  • The weights and biases of the connections

  • The number of input features in the data

Show the answer

The weights and biases of the connections

Backpropagation updates the weights to reduce error.

5Data, training and evaluation

Good data matters more than clever algorithms ("garbage in, garbage out").

  • Preprocessing: clean the data (remove errors and duplicates, deal with missing values), and normalise features to a common scale. Min-max normalisation: $x' = \frac{x - \min}{\max - \min}$; a score of 70 in a range 40–100 becomes $\frac{30}{60} = 0.5$.
  • Split the data: a training set to fit the model, a validation set to tune it, and a test set, kept separate, to measure performance on unseen data.
  • Overfitting: the model learns the training data too closely, including its noise, so it performs well on training data but badly on new data. Underfitting: the model is too simple to capture the pattern. Remedies for overfitting include more data, simpler models and stopping training early.

Underfitting and overfitting: validation error is lowest in between

A confusion matrix for a classifier counts true positives (TP), false positives (FP), false negatives (FN) and true negatives (TN).

  • Accuracy $= \frac{TP + TN}{\text{total}}$
  • Precision $= \frac{TP}{TP + FP}$: of the items flagged positive, how many really were.
  • Recall $= \frac{TP}{TP + FN}$: of the real positives, how many were found.
Worked example

A disease test

  1. Out of 100 patients: TP = 40, FP = 10, FN = 5, TN = 45.
  2. Accuracy $= \frac{85}{100} = 0.85$.
  3. Precision $= \frac{40}{50} = 0.80$. Recall $= \frac{40}{45} = 0.89$.
  4. For disease screening, high recall matters most: missing a sick patient (a false negative) is worse than a false alarm.
Check yourself

A model scores 99% on its training data but 60% on new data. What is the problem?

  • Underfitting

  • Overfitting

  • Too much test data

  • Normalisation

Show the answer

Overfitting

It memorised the training data instead of the general pattern.

6Ethics and limitations of machine learning

  • Bias: a model learns whatever patterns are in its data, including unfair ones. Facial recognition systems have been less accurate for darker-skinned women when trained mostly on lighter-skinned men; hiring tools trained on past decisions can copy past discrimination.
  • Explainability: deep networks are often "black boxes" whose decisions are hard to explain, a problem for loans, medicine and justice.
  • Privacy: training needs large amounts of personal data, raising questions of consent and surveillance.
  • Accountability: who is responsible when an AI system causes harm?
  • Misinformation: generative AI can create convincing fake images, audio and text ("deepfakes").
  • Environmental cost: training and running large models use a great deal of electricity and water for data centres.
  • Jobs: automation changes or replaces some work, while creating new roles.

Responses include diverse and representative datasets, testing for bias, transparency about how systems work, human oversight of important decisions, and regulation such as the EU's AI Act.

Check yourself

Why might a hiring algorithm be unfair even if no one programmed it to discriminate?

  • Algorithms can never be biased, so it must be fair

  • It runs on GPUs, which round off the numbers

  • It uses too little data about each candidate

  • It learns from past decisions that contained bias

Show the answer

It learns from past decisions that contained bias

Models reproduce patterns in their training data.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera