AS & A Level Computer Science · Area 2 · A Level content

Artificial intelligence

AI problems are solved by searching a graph, so you need to turn a problem into nodes and weighted edges and then trace Dijkstra's algorithm or A through it. On the learning side you must explain what machine learning, deep learning and reinforcement learning are, how supervised and unsupervised learning differ, how a neural network is trained by back propagation, and what regression is used for. Marks are lost by describing a neural network as a 'brain', by giving A a heuristic that overestimates, or by treating deep learning and machine learning as alternatives.

Not started

Syllabus coverage

  • Show understanding of how graphs can be used to aid artificial intelligence (AI)
  • The purpose and structure of a graph
  • Use A* and Dijkstra's algorithms to perform searches on a graph
  • Candidates will not be required to write algorithms to set up, access, or perform searches on graphs
  • Show understanding of how artificial neural networks have helped with machine learning
  • Show understanding of deep learning, machine learning and reinforcement learning and the reasons for using these methods
  • Understand machine learning categories, including supervised learning and unsupervised learning
  • Show understanding of back propagation of errors and regression methods in machine learning

Part of the AS & A Level Computer Science syllabus 9618.

Why AI starts with a graph

Almost every decision an artificial intelligence (AI) system makes can be written as a search: which route, which move, which sequence of actions reaches the goal. Before a program can search, it needs a model of the problem, and the model used here is a graph. A graph is an abstract data type made of nodes (also called vertices) and edges (also called arcs), so it stores objects and the relationships between them and nothing else.

To use a graph for AI, the nodes are the states the problem can be in and the edges are the moves from one state to another. In a route planner the nodes are towns and the edges are the roads. In a sliding-tile puzzle each node is one arrangement of the tiles and each edge is one legal move. In a board game each node is a position and each edge is a legal move to the next position. The complete set of states and moves is called the state space, and once the problem is expressed this way, solving it means finding a path from the start node to a goal node.

The point of using a graph is scale. A map of a country, a chess position or a delivery round has far too many possibilities for a person to check, but a graph lets a program store them compactly and hand them to an algorithm that explores them in a sensible order. That is why the graph is the first half of AI and the search algorithm is the second half: the graph says what the possibilities are, and the algorithm decides which ones to look at.

  • Node (vertex): the object or state being represented - a town, a board position, a web page, one arrangement of a puzzle.
  • Edge (arc): a link between two nodes showing a relationship or a legal move - a road, a move, a hyperlink.
  • Undirected edge: the link works both ways, like a two-way road. Directed edge: it works one way only, like a one-way street, and a graph made of directed edges is a directed graph or digraph.
  • Weight: a number on an edge giving its cost - distance, time, fuel or money. In an unweighted graph every edge counts as equal.
  • Path: a sequence of edges from one node to another. Its cost is the sum of the weights along it, and the shortest path is the one with the lowest total cost, not necessarily the fewest edges.
  • Adjacency matrix: an n by n two-dimensional array in which the cell at row i, column j holds the weight of the edge from node i to node j, or 0 if there is no edge.
  • Adjacency list: for each node, a list of the nodes it is joined to together with the weights, so only the edges that actually exist are stored.
RepresentationHow it is storedAdvantageDrawback
Adjacency matrixA two-dimensional array, n rows by n columns, holding a weight or 0 in each cellTesting whether two nodes are joined is a single array access, and adding or removing an edge is quickIt always uses n squared cells, so a large graph with few edges wastes a great deal of memory
Adjacency listOne list per node, holding the neighbours of that node and the edge weightsIt stores only the edges that exist, so it is far more memory-efficient for a sparse graph such as a road networkFinding whether one particular edge exists means searching the list of one node
The graph is the problem, the search is the method. A question that asks how a graph aids AI wants both halves: states and moves stored as nodes and edges, and then an algorithm that finds a path through them instead of trying every possibility.

Dijkstra's algorithm: shortest path from one node

Dijkstra's algorithm finds the path of lowest total weight from a chosen start node to a destination. It keeps a tentative distance for every node, set to 0 for the start, infinity for all the others, together with a record of the node each one was reached from.

At each step it selects the unfinalised node with the smallest tentative distance and marks it finalised, meaning its distance is now known to be the true shortest distance. It then relaxes each neighbour: it compares the distance the neighbour already has with the distance to the current node plus the weight of the edge between them, and keeps the smaller value, updating the previous-node record whenever it improves.

The algorithm repeats until the destination is finalised, or until every reachable node has been finalised. Reading the previous-node records backwards from the destination gives the shortest path itself. A simple implementation scans all the nodes to find the smallest each time and is O(n squared); a priority queue reduces this to O((n + e) log n), where e is the number of edges. The table below traces it on a graph with edges A-B 4, A-C 2, C-B 1, C-D 8, B-D 5, B-E 12 and D-E 2, taking A as the start and E as the destination.

  • Every edge weight must be zero or positive; negative weights break the algorithm.
  • It works on directed and undirected graphs, and it finds the shortest distance to every node, not only to one destination.
  • Its result is always the true shortest path, with no estimate involved.
  • On a very large graph it behaves like a ripple spreading out equally in all directions, so it spends time exploring routes that lead away from the destination.
StepNode finalisedDistance from AUpdates to neighbours
1A0B = 4 via A; C = 2 via A
2C2B improved to 3 via C; D = 10 via C
3B3D improved to 8 via B; E = 15 via B
4D8E improved to 10 via D
5E10None - destination finalised
The cheapest route is not the one that looks most direct. A to E costs 10 along A -> C -> B -> D -> E, while the route that goes straight to B first costs 16. Follow the total cost, never the number of edges.

A*: searching towards the goal

The A algorithm is a shortest-path search that uses a heuristic, which is an estimate of the remaining cost from a node to the goal. For each node it calculates f = g + h, where g is the cost of the best route found so far from the start, h is the estimate from that node to the destination, and f is therefore the estimated total cost of a route through that node. At every step A expands the unfinalised node with the smallest f.

The heuristic has to be admissible: it must never overestimate the true remaining cost. The straight-line distance between two points on a map is admissible for road travel, because no road can be shorter than the straight line between its ends, and the number of tiles out of place is admissible for a sliding-tile puzzle, because each tile needs at least one move. With an admissible heuristic A* is guaranteed to return a shortest path, and it usually expands far fewer nodes than Dijkstra's algorithm because the h term pulls the search towards the goal.

The worked example uses the same graph as before, with heuristic values A 9, B 6, C 7, D 2 and E 0, which you can read as an estimate of the distance still to travel to E. A* expands A, then C with f = 9, then B with f = 9, then D with f = 10, then E and stops: the route found is A -> C -> B -> D -> E with cost 10, the same answer Dijkstra gave, and every node that was expanded lay on or near the best route. On a graph this small both algorithms expand the same five nodes; the saving from the heuristic appears on a large graph, where nodes that lead away from the destination are given a high f and are never expanded at all.

Node expandedg (cost so far)h (estimate to E)f = g + h
A099
C279
B369
D8210
E10010
h must be an underestimate. An admissible heuristic may be wrong, but it must always be wrong on the safe side - it may say the goal is further away than it really is, never nearer. If h = 0 for every node then f = g and A* behaves exactly like Dijkstra's algorithm.

Dijkstra or A*: choosing the right search

Both algorithms find a shortest path, so the choice is about what information you have and what answer you need. Dijkstra's algorithm needs nothing but the weighted graph, and it gives the shortest distance to every node, which is what a network router wants when it has to fill in a routing table for every destination.

A needs a heuristic that can be calculated for any node, and it is worth the effort when there is a single destination and a good estimate is available, as in a satellite navigation system, a game character finding its way across a map, or a robot planning a route through a room. The better the heuristic, the fewer nodes are expanded, so A can be dramatically faster on a large graph.

The risk with A* is a heuristic that overestimates. The answer can then be a route that is not the cheapest, and a very poor heuristic can make the search wander further than Dijkstra would have. Dijkstra also has a weakness of its own: it cannot cope with negative edge weights, and it can waste time expanding large parts of the graph that lie in the wrong direction.

FeatureDijkstra's algorithmA* algorithm
Information usedEdge weights onlyEdge weights plus a heuristic h for each node
Order of expansionSmallest distance from the start, gSmallest estimated total cost, f = g + h
What it returnsThe shortest path and distance to every nodeA shortest path to the chosen goal
GuaranteeAlways shortest, provided no weight is negativeShortest only if the heuristic never overestimates
Typical useRouting tables, distances to all nodes, no reliable estimate availableMaps, games and robotics, where one destination matters and a distance estimate exists
Same family, different information. A* is not a different kind of search from Dijkstra; it is Dijkstra with an estimate added, so if h is always zero the two are the same algorithm.

Machine learning, deep learning and reinforcement learning

Machine learning is the approach in which a program is not given the rules for a task. Instead it is given examples, and it builds a model from them that can be used to make predictions or decisions about new, unseen data. A programmer who writes a spam filter by hand lists the words and rules that mark a message as spam; a machine learning system is given thousands of messages already marked spam or not spam and works out the pattern for itself.

There are several reasons for choosing this approach. For some tasks nobody can write the rules down - describing exactly how to recognise a face, a spoken word or a handwritten letter in code is effectively impossible. For others the rules exist but there are far too many of them to write and maintain. Data also changes: fraud patterns, prices and language shift over time, and a model retrained on new examples keeps up in a way that a fixed set of rules cannot. Machine learning also finds patterns in very large data sets that a person would never notice, and its accuracy tends to improve as more training data is supplied.

Deep learning is machine learning that uses an artificial neural network with many hidden layers. Its advantage is that it learns the features it needs directly from raw data - the edges and shapes that make up a face, the sounds that make up a word - instead of relying on a person to decide in advance which measurements matter. That is why deep learning transformed image, speech and language tasks, and why it needs large amounts of data and considerable computing power.

Reinforcement learning is different again. There is no set of labelled examples and no correct answer supplied. An agent takes actions in an environment, receives a reward or penalty for what happens, and learns a policy - which action to take in each state - by trial and error, with the aim of maximising the total reward over time. It suits problems that are a sequence of decisions rather than a single judgement: playing a game, controlling a robot, or balancing the cooling in a data centre, where a good move now may only pay off many moves later.

  • Machine learning: a model is learned from data, then used to predict or decide on new data, instead of rules being written by hand.
  • Deep learning: machine learning with a many-layered neural network, which learns its own features from raw data such as pixels or sound.
  • Reinforcement learning: an agent learns by acting, receiving rewards and adjusting its behaviour, with no labelled examples at all.
  • Reasons for machine learning: the rules are unknown or too complex, there are too many rules, the data keeps changing, or the patterns are too subtle or too large for a person to find.
  • Reasons for deep learning: the input is raw and high-dimensional, feature selection is itself difficult, and accuracy improves with more data and processing power.
  • Reasons for reinforcement learning: the task is a sequence of decisions with delayed rewards, and the best action is not known in advance.

Supervised, unsupervised and reinforcement learning

Machine learning is divided into categories according to the kind of data and feedback available. In supervised learning every training example carries a label, which is the correct answer. The model learns the mapping from input to output and is then judged on how well it predicts the label for data it has not seen. If the label is a category, such as spam or not spam, the task is classification; if the label is a number, such as a price, the task is regression. The cost of supervised learning is the labelling: somebody has to mark up thousands of examples, and errors in the labels teach the model the wrong thing.

In unsupervised learning there are no labels. The model is given the inputs alone and looks for structure: grouping similar records into clusters, or finding items that occur together. A retailer can feed a year of transactions into a clustering algorithm and discover groups of customers who buy in similar ways, without anyone having decided in advance what those groups are. Because there is no correct answer to compare against, the output has to be interpreted by a person, and there is no straightforward way to score how right it is.

Reinforcement learning is a third category, and it is neither of these. The data is not a fixed data set at all: the agent generates its own experience by acting, and the feedback is a reward signal rather than a label. Learning is slow because the agent must try many actions, and the design of the reward matters enormously, because the agent will optimise whatever is rewarded, including a badly chosen reward that encourages the wrong behaviour.

Supervised learning is the category to reach for when you have historical examples with known outcomes; unsupervised learning when you want to explore data and find groups or associations you did not know were there; reinforcement learning when the problem is a series of decisions in an environment that responds to what the agent does.

CategoryData usedWhat is learnedTypical task
SupervisedInputs with the correct output (labelled data)A mapping from input to output that generalises to new dataClassifying an email as spam or not spam; predicting a house price
UnsupervisedInputs only, with no labelsStructure in the data: clusters, groupings, associationsGrouping customers by buying behaviour; finding products bought together
ReinforcementExperience generated by acting, with rewardsA policy saying which action to take in each stateLearning to play a game; controlling a robot or a cooling system
Ask what feedback the system gets. A correct answer for each example means supervised; no answers at all but a search for groups means unsupervised; a reward after acting means reinforcement.

Artificial neural networks

An artificial neural network (ANN) is a model built from layers of simple processing units. The input layer has one unit for each feature of the data, such as the brightness of each pixel in an image. One or more hidden layers sit between the input and the output, and the output layer produces the result - a class, a probability or a number.

Each connection between a unit in one layer and a unit in the next carries a weight, which is a number saying how strongly that input affects that unit. A unit calculates the sum of every input multiplied by its weight, adds a bias that shifts the total, and passes the result through an activation function that decides what the unit passes on. The activation function is what allows the network to represent a curved, non-linear relationship rather than only a straight-line one, which is why a network can separate classes that no straight line could separate.

Running data forward through the network from input to output is called a forward pass, and it is how a trained network makes a prediction. The weights are what the network has learned: they start as small random numbers, and training is the process of adjusting them until the outputs match the training data. Because each hidden unit combines many inputs, the hidden layers can build up intermediate features - an early layer responding to edges, a later layer to combinations of edges that form a shape - which is what makes a network able to work from raw data.

ANNs helped machine learning because they removed two of its main limits. A person no longer has to decide which features of the data to measure, since the network learns useful combinations of the raw inputs for itself. And a network with enough units can approximate very complex relationships, so it copes with noisy, high-dimensional data such as images, audio and text, where classical statistical methods struggled.

  • Input layer: one unit per feature; it passes the data into the network unchanged.
  • Hidden layer(s): units that combine the inputs, applying weights, a bias and an activation function; more layers allow more abstract features.
  • Output layer: produces the prediction - one unit for a yes or no decision, one per class for a classification, or one for a numeric value.
  • Weight: the strength of a connection, adjusted during training; the set of all weights is what the network has learned.
  • Bias: a constant added inside each unit, which shifts the activation so that the unit can fire even when all its inputs are zero.
  • Activation function: the non-linear step that decides the output of a unit, so the network can model curves rather than only straight lines.
  • Forward pass: data flowing from the input layer to the output layer to produce a prediction from the current weights.
A network is not a brain. Say layers, weights, bias and activation, and say that the weights are set by training - not that it 'thinks' or 'works like a human brain', which earns nothing.

Back propagation of errors

A new network has random weights, so its first predictions are poor. Back propagation of errors is the training method that fixes them. The training data goes through a forward pass and produces an output, which is compared with the correct, known output. The difference between them is the error, measured by a loss function such as the sum of the squared differences.

That error exists only at the output layer, but the weights that caused it are spread through every layer, and the hidden units have no target values of their own. Back propagation solves this by working backwards: the error at the output is used to calculate how much each weight in the last layer contributed to it, that share is passed back to the previous layer, and the process continues layer by layer to the input. The calculation uses the derivative of the activation function, which is why the activation function must be differentiable.

Each weight is then adjusted in the direction that reduces the error, by an amount controlled by the learning rate - a large rate learns quickly but can overshoot, a small rate is stable but slow. This adjustment is gradient descent. One pass through the whole training set is an epoch, and training repeats for many epochs until the error stops falling. If training continues too long the network can memorise the training examples, including their noise, and then perform badly on new data.

Back propagation is what made multi-layer networks practical. Before it, there was no way to set the weights of the hidden layers, because no one knows what a hidden unit ought to output; after it, a network with many hidden layers could be trained from examples, which is the basis of deep learning.

  • Forward pass: present one training example and calculate the network's output.
  • Calculate the error: compare that output with the known correct output using a loss function.
  • Backward pass: propagate the error back through the layers, working out each weight's share of the blame using the derivatives of the activation functions.
  • Update the weights: change each weight slightly in the direction that reduces the error (gradient descent), scaled by the learning rate.
  • Repeat: do this for every example, for many epochs, until the error is acceptably small or stops improving.
Back propagation is training, not prediction. Prediction is the forward pass with the weights fixed; back propagation is the backward pass that changes the weights afterwards.

Regression methods

Regression is a supervised learning method that predicts a continuous numeric value rather than a category. The simplest form, linear regression, fits a straight line to the training data: y = mx + c, where x is the input, y is the predicted value, m is the gradient and c is the intercept. Training chooses m and c so that the line is as close as possible to the data points, normally by least squares, which minimises the sum of the squared vertical distances between each point and the line.

With more than one input the method becomes multiple regression, which fits an equation with one coefficient per input - for example predicting a house price from its floor area, number of rooms, age and distance from the centre. Each coefficient says how much the predicted value changes when that input rises by one unit while the others stay the same, so the model can be inspected as well as used.

Regression is not restricted to straight lines: the inputs can be transformed, or a curve fitted, to capture a relationship that bends. A related method, logistic regression, produces a probability between 0 and 1 and is therefore used for classification even though its name contains the word regression - the output is a probability that an item belongs to a class, which is then turned into a decision by a threshold.

In machine learning terms, regression is the supervised task you choose when the answer is a number: a price, a temperature, a demand, a lifespan. It is a good first method because it is fast, needs comparatively little data, and its coefficients can be explained to a person, but it assumes the relationship has the shape you have chosen, so it underfits a problem whose pattern is genuinely complex - which is one of the reasons deep networks are used instead.

  • Simple linear regression: one input, a straight line, y = mx + c.
  • Multiple regression: several inputs, one coefficient each, so the effect of each can be separated.
  • Least squares: the fitting method that minimises the total squared distance between the data points and the line.
  • Logistic regression: predicts a probability and is used for classification, not for a continuous value.
  • Use it when: the output is numeric, the relationship is fairly smooth, and you need a model that can be explained.
Regression gives a number, classification gives a label. If the question asks what regression is for, say it predicts a continuous value from input data and give a concrete example such as a price or a demand forecast.

Key terms you must be able to define

Graph
An abstract data type made of nodes (vertices) and edges (arcs), used in AI to represent the states of a problem and the moves between them, so that a search algorithm can find a path through the possibilities.
Weighted graph
A graph in which every edge carries a number, its weight, representing the cost of using that edge - distance, time, fuel or money. The cost of a path is the sum of the weights of its edges.
Adjacency matrix
A two-dimensional array of size n by n used to store a graph, in which the cell at row i, column j holds the weight of the edge from node i to node j, or 0 if no such edge exists. It allows quick testing of whether two nodes are joined but uses n squared cells.
Dijkstra's algorithm
A shortest-path algorithm that repeatedly finalises the unfinalised node with the smallest known distance from the start and relaxes its neighbours, giving the shortest distance from the start node to every node. All edge weights must be zero or positive.
Heuristic
An estimate of the cost remaining from a node to the goal, used to guide a search towards the goal. In A* it is the h in f = g + h, and it must be admissible - it must never overestimate the true remaining cost.
A* algorithm
A shortest-path search that expands the node with the lowest f = g + h, where g is the cost so far from the start and h is the heuristic estimate of the cost to the goal. It returns a shortest path if the heuristic is admissible, and usually expands fewer nodes than Dijkstra's algorithm.
Machine learning
An approach in which a program is not given hand-written rules but learns a model from data, so that it can make predictions or decisions about new, unseen data. It is used when the rules are unknown, too numerous or too complex, or when the data keeps changing.
Artificial neural network
A model of layers of simple units - an input layer, one or more hidden layers and an output layer - in which each connection has a weight. Each unit sums its weighted inputs, adds a bias and applies an activation function, and the weights are set by training rather than by the programmer.
Deep learning
Machine learning that uses an artificial neural network with many hidden layers, so that the network learns its own features from raw data such as pixels or sound. It needs large amounts of data and computing power, and it is the basis of modern image, speech and language systems.
Supervised learning
A machine learning category in which every training example is labelled with the correct output, so the model learns the mapping from input to output. It covers classification, where the output is a category, and regression, where the output is a number.
Unsupervised learning
A machine learning category in which the training data has no labels and the model looks for structure in it, such as grouping similar records into clusters or finding items that occur together. There is no correct answer to compare against, so the output must be interpreted by a person.
Reinforcement learning
A machine learning category in which an agent learns by taking actions in an environment and receiving rewards or penalties, so that it develops a policy for choosing actions that maximise the total reward over time. No labelled examples are supplied.
Back propagation
The training method for a neural network in which the error between the output and the correct output is calculated, then propagated backwards through the layers to find each weight's share of the error, and every weight is adjusted by gradient descent to reduce it.
Regression
A supervised learning method that predicts a continuous numeric value, such as a price or a demand, by fitting an equation to labelled training data. Linear regression fits a straight line by least squares, and multiple regression fits one coefficient per input.

Applied to real systems

9618 sets its questions inside systems you already use - a phone, a school network, a supermarket till, a website, a bank. These show how to apply the theory to a context you have not seen before, then you write your own.

Dijkstra in a real network: link-state routing

In a link-state routing protocol such as OSPF, every router builds a map of the whole network as a weighted graph: the nodes are routers and the edges are the links between them, weighted by a cost that reflects the link's capacity. Each router then runs Dijkstra's algorithm with itself as the start node, which gives the shortest path to every other network, and those paths become its routing table. When a link fails, the change is flooded through the network, each router rebuilds its graph and reruns the search, and traffic is rerouted automatically. This is the clearest example of the purpose of a weighted graph: the graph is the network, and the shortest-path search is what turns it into working routing decisions.

A* in games and robotics: finding a way across a map

A game character that has to cross a level, or a robot that has to cross a room, plans its route on a graph whose nodes are grid squares or waypoints and whose edges are weighted by the cost of moving between them - a longer or rougher step costs more. A* is used rather than Dijkstra's algorithm because the straight-line distance to the target is an admissible heuristic: it can never overestimate how far is left, and it steers the search towards the target instead of expanding the whole map. Because a game may need thousands of these searches every second, expanding fewer nodes directly saves processing time. If the character needs routes to many different destinations, or the map has no meaningful distance estimate, Dijkstra's algorithm becomes the better choice.

Supervised deep learning: speech recognition in a voice assistant

A voice assistant turns speech into text with a deep neural network trained on many hours of recorded speech, each clip paired with its correct transcription. The input layer takes a representation of a short slice of sound, several hidden layers learn increasingly abstract features - from raw sound frequencies to the components of speech sounds to whole words - and the output layer gives the most likely word or letter. The transcription in the training data is the label, so this is supervised learning, and the network's weights are set by back propagation. It also shows why deep learning helped: no one could write rules that map a sound wave to a word, but a many-layered network can learn the mapping from a large labelled data set.

Reinforcement learning: AlphaGo and self-play

The program AlphaGo, developed by DeepMind, first learned from a large set of recorded human games, which is supervised learning, and was then improved by reinforcement learning in which it played against itself. In the reinforcement stage there were no labels at all: the agent chose moves, reached the end of a game, and received a reward for winning or a penalty for losing, and it adjusted its policy to make winning more likely. Because a reward arrives only at the end of a game, the agent has to work out which of its many earlier moves deserves the credit - the same delayed-feedback problem that makes reinforcement learning hard. It is the standard example of a task where the correct action at each step is not known in advance and must be discovered by trial and error.

Regression in practice: forecasting electricity demand

A grid operator has years of records of demand, together with the temperature, the time of day and the day of the week for each half hour. A regression model is trained on those labelled records to predict demand as a function of the inputs, with one coefficient per input, so the effect of a colder day or a weekend can be separated out. The trained model is then used to forecast tomorrow's demand from the forecast temperature and the calendar, which is a prediction of a continuous number and therefore a regression task rather than a classification one. The same method, with the same least-squares fitting, is used for house prices, delivery times and equipment failure rates.

Flashcards

Click a card to flip it. Mark honestly — the tracker uses this.

Q1What is a graph, and what do the nodes, edges and weights represent in an AI problem?
A graph is an abstract data type made of nodes (vertices) joined by edges (arcs). In AI the nodes are the states of the problem, the edges are the legal moves between states, and a weight is the cost of a move - distance, time or money. A path is a sequence of edges from the start to a goal, and its cost is the sum of the weights along it.
Q2Describe the steps of Dijkstra's algorithm and say what it returns.
Give the start node distance 0 and every other node infinity, all unfinalised. Repeatedly select the unfinalised node with the smallest tentative distance, finalise it, and relax its neighbours: if the distance to the current node plus the edge weight is smaller than the neighbour's current distance, replace it and record the current node as its predecessor. Stop when the destination is finalised or all reachable nodes are finalised. It returns the shortest distance from the start to every node, and the shortest path is found by following the predecessor records backwards.
Q3Why does Dijkstra's algorithm fail on a graph with negative edge weights?
Because it finalises a node as soon as that node has the smallest tentative distance, assuming no later route can be cheaper. A negative weight can make a route discovered later cheaper, so a finalised distance can be too large and the error is passed on to every node reached through it. Every edge weight must be zero or positive.
Q4What is a heuristic, and what does admissible mean?
A heuristic (h) is an estimate of the cost still to go from a node to the goal. It is admissible if it never overestimates the true remaining cost - it may say the goal is further away than it is, never nearer. Straight-line distance is admissible for road travel; the number of tiles out of place is admissible for a sliding-tile puzzle.
Q5How does A* choose which node to expand, and when is it guaranteed to find the shortest path?
It calculates f = g + h for each node, where g is the cost of the best route found so far from the start and h is the heuristic estimate to the goal, and it expands the unfinalised node with the smallest f. It is guaranteed to return a shortest path if the heuristic is admissible. If h = 0 for every node, A* behaves exactly like Dijkstra's algorithm.
Q6What is machine learning, and give three reasons for using it instead of writing rules.
Machine learning is the approach in which a model is learned from data rather than rules being written by hand, so the program can predict or decide on new, unseen data. Reasons: the rules are not known or are too complex to write (recognising a face or a spoken word); there are too many rules to write and maintain; the data changes over time so a fixed rule set goes out of date; and the patterns in large data sets are too subtle for a person to find.
Q7Distinguish supervised learning from unsupervised learning.
Supervised learning uses labelled data: each training example includes the correct output, the model learns the input-to-output mapping, and it covers classification (a category output) and regression (a numeric output). Unsupervised learning uses unlabelled data: the model looks for structure such as clusters or associations, and there is no correct answer to score it against.
Q8What is reinforcement learning, and what problem does it suit?
An agent takes actions in an environment, receives a reward or penalty, and learns a policy - the best action in each state - by trial and error, aiming to maximise total reward over time. There are no labelled examples. It suits problems that are a sequence of decisions with delayed rewards, such as playing a game or controlling a robot, where the best action is not known in advance.
Q9Describe the structure of an artificial neural network and the role of the weights.
An input layer with one unit per feature, one or more hidden layers, and an output layer. Each connection has a weight saying how strongly one unit affects the next; each unit sums its weighted inputs, adds a bias and applies an activation function, which provides the non-linearity. The weights hold what the network has learned: they start random and are adjusted by training. Prediction is a forward pass through the fixed weights.
Q10What is deep learning, and why did it help machine learning?
Deep learning is machine learning with an artificial neural network that has many hidden layers. The layers learn a hierarchy of features from raw data - edges, then shapes, then whole objects - so a person does not have to choose the features in advance. That is why it works on images, audio and text, where nobody can specify the useful measurements by hand. It needs large data sets and a lot of computing power.
Q11Describe back propagation of errors.
A forward pass produces an output, which is compared with the correct output to give an error. The error is propagated backwards through the layers, using the derivatives of the activation functions, to calculate how much each weight contributed to it. Each weight is then adjusted in the direction that reduces the error (gradient descent), by an amount set by the learning rate. One pass through the training set is an epoch, and training repeats until the error stops falling.
Q12What does regression do, and what is least squares?
Regression is a supervised method that predicts a continuous numeric value, such as a price or a demand. Linear regression fits y = mx + c; multiple regression uses several inputs with one coefficient each. Least squares is the fitting method: it chooses the line that minimises the sum of the squared vertical distances between the data points and the line. Logistic regression is the exception - it outputs a probability and is used for classification.
0 of 12 marked as known

Exam-style questions

8 questions, 27 marks. Write your answer, then reveal the mark scheme and tick each point you actually made. Answering honestly here is what makes the rest of the site useful.

StateAO11 mark
State what is meant by a heuristic in a graph search algorithm.

Mark scheme — tick each point you actually made

Examiner tip: One mark, one idea: it is an estimate of the remaining cost to the goal. Do not describe how A* uses it - that is a different question.
DefineAO12 marks
Define the terms supervised learning and unsupervised learning.

Mark scheme — tick each point you actually made

Examiner tip: The single word that separates them is 'labelled'. Use it for supervised, and say explicitly that unsupervised data has no labels.
DescribeAO13 marks
Describe the structure of a feed-forward artificial neural network and explain the role of the weights.

Mark scheme — tick each point you actually made

Examiner tip: Name all three layer types, then say what a weight is and where the weights come from. Saying the network 'works like a brain' earns nothing.
ExplainAO23 marks
Explain why A* can find a route by expanding fewer nodes than Dijkstra's algorithm, and state the condition under which the route it returns is guaranteed to be the shortest.

Mark scheme — tick each point you actually made

Examiner tip: The second mark is for the consequence - fewer nodes expanded - and the third is the admissibility condition. A comparison that never mentions the guarantee loses the last mark.
DescribeAO24 marks
A weighted graph has nodes A, B, C and D. Its edges are A-B 4, A-C 2, C-B 1, B-D 5 and C-D 8, and the edges may be travelled in either direction. Dijkstra's algorithm is used to find the shortest path from A to D. Describe the order in which the nodes are finalised, the distance recorded for each, and the shortest path and its cost.

Mark scheme — tick each point you actually made

Examiner tip: Show the updates, not just the answer. The mark is for replacing the earlier distance of 10 with the better 8, and for giving the path and its cost together.
DescribeAO14 marks
Describe how back propagation of errors is used to train an artificial neural network.

Mark scheme — tick each point you actually made

Examiner tip: Four marks, four stages: forward pass, error, backward pass, weight update and repeat. Keep the forward pass - prediction - separate from the backward pass that changes the weights.
ExplainAO24 marks
Explain how regression methods are used in supervised machine learning, using one example of a task they could be applied to.

Mark scheme — tick each point you actually made

Examiner tip: Say that the output is a number and the data is labelled, describe least squares, then give the example with the inputs named. A regression answer with no example cannot reach full marks.
DiscussAO26 marks
A company is deciding whether to solve a recognition problem with a conventional rule-based program or with machine learning, and if it uses machine learning whether a deep neural network is needed. Discuss the reasons for choosing machine learning and deep learning, and the drawbacks the company should consider.

Mark scheme — tick each point you actually made

Examiner tip: Answer in two halves - why learn at all, then why deep - and give a drawback for each benefit. The final mark is for a judgement: what the choice depends on, not a repeat of the lists.

Exam technique for this topic

  • Draw the graph before you answer anything about search. Label the nodes, put the weights on the edges, and mark the start and goal. Most lost marks in this topic come from tracing an algorithm without a clear picture of the graph it is running on.
  • For Dijkstra, show a table with a row per step: the node finalised, its distance, and the updates made to its neighbours. Then state the shortest path and its total cost separately. Never finalise a node twice, and never revise the distance of a node that is already finalised.
  • For A, write the formula f = g + h and show g, h and f for each node expanded. If the question asks about correctness, say that the answer is only guaranteed shortest if the heuristic never overestimates. If it asks for a comparison, say that A uses the heuristic to avoid expanding nodes that lead away from the goal, while Dijkstra expands in all directions by distance.
  • Sort the learning categories by the feedback available: labelled examples mean supervised, no labels and a search for groups means unsupervised, rewards from acting mean reinforcement. Deep learning is not a fourth category - it is machine learning with a many-layered neural network - so never offer it as an alternative to supervised or unsupervised learning.
  • Describe training in the right order: forward pass, calculate the error, propagate it backwards, update the weights, repeat for many epochs. Keep prediction and training apart - a forward pass with fixed weights is prediction, and back propagation is what changes the weights.

Why students lose marks here

A student wroteA student wrote: 'A* always finds the shortest path because it uses a heuristic to guide the search towards the goal.'
Why it loses marksA heuristic only guarantees a shortest path if it never overestimates the remaining cost. A heuristic that overestimates makes some nodes look more expensive than they are, so A* can settle on a route that is not the cheapest, and a badly chosen one can send the search off in the wrong direction altogether.
The answer that scoresA expands the node with the lowest f = g + h, where g is the cost of the best route found so far and h is the estimated cost from that node to the goal. It returns a shortest path only if the heuristic is admissible, meaning h never overestimates the true remaining cost, because then the estimate can delay a node but can never make a cheap route look more expensive than it is. Straight-line distance is admissible for road travel, since no road is shorter than the straight line between its ends, and with such a heuristic A is both complete and optimal. With an inadmissible heuristic A* may still return a route quickly, but the route may not be the cheapest, so the guarantee is lost.
A student wroteA student wrote: 'Dijkstra's algorithm works on any weighted graph, including one with negative weights, as long as the graph is not too large.'
Why it loses marksThe size of the graph has nothing to do with it. Dijkstra finalises a node as soon as it has the smallest tentative distance, on the assumption that no route discovered later can be cheaper. A negative edge can make a later route cheaper, so a node can be finalised at the wrong distance and the error spreads to everything reached through it.
The answer that scoresDijkstra's algorithm is only valid when every edge weight is zero or positive. The reason is the finalising step: when the node with the smallest tentative distance is selected, the algorithm assumes that every other route to that node must pass through a node that is already further away and then add a weight, and with non-negative weights that can never produce a smaller total. A negative weight breaks that assumption, because a route that looks longer can become shorter when the negative edge is used, so a finalised distance may later turn out to be too large. Algorithms that can handle negative weights are different ones, and Dijkstra's algorithm cannot cope with a negative cycle at all.
A student wroteA student wrote: 'In unsupervised learning the computer is given the correct answers so that it can check whether it is right, and in supervised learning the computer works everything out for itself.'
Why it loses marksThe two definitions have been swapped. Supervised means the training data is labelled with the correct answers and the system learns from them; unsupervised means there are no labels and the system looks for structure such as clusters in the data.
The answer that scoresSupervised learning uses labelled training data: each example is supplied with the correct output, the model learns the mapping from input to output, and its performance can be measured by comparing its predictions with the labels. It covers classification, where the output is a category such as spam or not spam, and regression, where the output is a number such as a price. Unsupervised learning uses unlabelled data: the model is given the inputs only and looks for structure in them, typically by clustering similar records together or finding items that occur together. There is no correct answer to compare against, so the result has to be interpreted by a person, but no expensive labelling is needed.
A student wroteA student wrote: 'Back propagation is how the neural network produces its output, by passing the data back through the layers to the input.'
Why it loses marksThat describes a backward pass, but producing the output is a forward pass from the input layer to the output layer. Back propagation happens during training, uses the error, and changes the weights; it does not produce the network's prediction.
The answer that scoresA trained network produces its output by a forward pass: the data enters at the input layer, each unit multiplies its inputs by the weights on its connections, adds a bias and applies an activation function, and the result passes forward layer by layer until the output layer gives the prediction. Back propagation happens during training. After the forward pass, the output is compared with the known correct output to give an error; that error is then propagated backwards through the layers, using the derivatives of the activation functions, to work out how much each weight contributed to it. Each weight is adjusted slightly in the direction that reduces the error, by an amount set by the learning rate, and the whole process is repeated for many examples over many epochs.
A student wroteA student wrote: 'Deep learning is a completely different approach from machine learning, and it is used when you have a very large data set.'
Why it loses marksDeep learning is a subset of machine learning, not an alternative to it. It is defined by the use of an artificial neural network with many hidden layers, and although it does need large data sets, having a large data set is not what makes a system deep learning.
The answer that scoresMachine learning is the broad approach in which a model is learned from data instead of rules being written by hand, and it includes many methods, of which regression, decision trees and neural networks are examples. Deep learning is machine learning carried out with an artificial neural network that has many hidden layers. The depth is what matters: the layers learn a hierarchy of features, from simple edges or sounds in the early layers to whole shapes or words in the later ones, so the network can work from raw data without a person deciding which features to measure. Deep learning usually does need large labelled data sets and substantial computing power, which is why it became practical only once both were widely available, but the defining feature is the many-layered network.
A student wroteA student wrote: 'Regression is used to sort data into categories, so a regression model could decide whether an email is spam or not spam.'
Why it loses marksRegression predicts a continuous numeric value; sorting items into categories is classification. The confusion usually comes from logistic regression, which has regression in its name but outputs a probability that is then used for classification.
The answer that scoresRegression is a supervised learning method whose output is a number on a continuous scale: a price, a temperature, a demand, a lifespan. Linear regression fits a straight line y = mx + c to the training data, choosing the gradient and intercept by least squares so that the total squared distance between the data points and the line is as small as possible; multiple regression extends this to several inputs, with one coefficient each. Classification is the other supervised task, and its output is a category, such as spam or not spam, so a spam filter is a classifier rather than a regression model. Logistic regression is the exception that explains the confusion: it produces a probability between 0 and 1, which is then turned into a class by a threshold, so despite its name it is used for classification.