Book 3 · Chapter 18
Artificial Intelligence (AI)
B3·18This chapter is in the ebook.
Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.
For the whole chapter
- Topic pageArtificial Intelligence
B3·18·T - QuizArtificial Intelligence
B3·18·Q1 - LabDijkstra & A* visualiser
B3·18·X1 - LabPerceptron demo
B3·18·X2
§18.1 Graphs for AI · Machine learning
Short code B3·18·1
- FlashcardsFlashcards §18.1: Graphs, Dijkstra & A*
B3·18·F1 - FlashcardsFlashcards §18.1: Machine learning & neural networks
B3·18·F2 - Past-paper questionsPast-paper questions §18.1 (graphs-for-ai)
- Past-paper questionsPast-paper questions §18.1 (machine-learning)
Graphs: the structure AI searches
Short code B3·18·10
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Storing a graph for a program
Short code B3·18·11
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Dijkstra's algorithm: the method
Short code B3·18·12
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Dijkstra's algorithm: a full trace
Short code B3·18·13
# Dijkstra's algorithm: the depot and shops F to L
edges = """Depot F 4
Depot G 2
G F 1
G H 7
F H 5
F J 10
H J 3
G K 9
H K 2
K J 4
J L 6
K L 9"""
graph = {}
for line in edges.splitlines():
a, b, w = line.split()
graph.setdefault(a, {})[b] = int(w)
graph.setdefault(b, {})
graph[b][a] = int(w)
start = "Depot"
dist = {n: float("inf") for n in graph}
prev = {n: None for n in graph}
dist[start] = 0
visited = []
while len(visited) < len(graph):
current = min((n for n in graph if n not in visited), key=lambda n: dist[n])
visited.append(current)
for n, w in graph[current].items():
if n not in visited and dist[current] + w < dist[n]:
dist[n] = dist[current] + w
prev[n] = current
def route(n):
return route(prev[n]) + [n] if prev[n] else [n]
print("visit order:", " ".join(visited))
print("distances:", ", ".join(f"{n} {dist[n]}" for n in sorted(graph) if n != start))
print("route to L:", " -> ".join(route("L")), "=", dist["L"])Output
visit order: Depot G F H K J L distances: F 3, G 2, H 8, J 11, K 10, L 17 route to L: Depot -> G -> F -> H -> J -> L = 17
# Dijkstra's algorithm: the school site
edges = """Gate A 6
Gate B 2
B A 3
B C 8
A C 4
A D 7
C D 1
C E 5
D E 3"""
graph = {}
for line in edges.splitlines():
a, b, w = line.split()
graph.setdefault(a, {})[b] = int(w)
graph.setdefault(b, {})
graph[b][a] = int(w)
start = "Gate"
dist = {n: float("inf") for n in graph}
prev = {n: None for n in graph}
dist[start] = 0
visited = []
while len(visited) < len(graph):
current = min((n for n in graph if n not in visited), key=lambda n: dist[n])
visited.append(current)
for n, w in graph[current].items():
if n not in visited and dist[current] + w < dist[n]:
dist[n] = dist[current] + w
prev[n] = current
def route(n):
return route(prev[n]) + [n] if prev[n] else [n]
print("visit order:", " ".join(visited))
print("distances:", ", ".join(f"{n} {dist[n]}" for n in sorted(graph) if n != start))
print("route to E:", " -> ".join(route("E")), "=", dist["E"])Output
visit order: Gate B A C D E distances: A 5, B 2, C 9, D 10, E 13 route to E: Gate -> B -> A -> C -> D -> E = 13
The A* algorithm: heuristics and f = g + h
Short code B3·18·14
# A* search: the same graph, but h(N) = 12 overestimates
edges = """Dock M 5
Dock N 5
Dock P 6
M Q 6
N Q 3
N R 7
P R 5
Q Tower 5
R Tower 3"""
h = {"Dock": 11, "M": 10, "N": 12, "P": 8, "Q": 4, "R": 3, "Tower": 0}
graph = {}
for line in edges.splitlines():
a, b, w = line.split()
graph.setdefault(a, {})[b] = int(w)
graph.setdefault(b, {})[a] = int(w)
start, goal = "Dock", "Tower"
g = {start: 0}
prev = {start: None}
open_nodes = [start]
closed = []
print("current next g h f")
print(start, start, 0, h[start], h[start])
while open_nodes:
current = min(sorted(open_nodes), key=lambda n: g[n] + h[n])
open_nodes.remove(current)
closed.append(current)
if current == goal:
break
for n, w in graph[current].items():
if n in closed:
continue
new_g = g[current] + w
row = f"{current} {n} {new_g} {h[n]} {new_g + h[n]}"
if n in g and new_g >= g[n]:
print(row, "(no better than", g[n], end=")\n")
continue
print(row)
g[n] = new_g
prev[n] = current
if n not in open_nodes:
open_nodes.append(n)
path = [goal]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
print("expanded:", " ".join(closed))
print("path:", " -> ".join(reversed(path)), "=", g[goal])Output
current next g h f Dock Dock 0 11 11 Dock M 5 10 15 Dock N 5 12 17 Dock P 6 8 14 P R 11 3 14 R N 18 12 30 (no better than 5) R Tower 14 0 14 expanded: Dock P R Tower path: Dock -> P -> R -> Tower = 14
The A* algorithm: a worked search
Short code B3·18·15
# A* search: the drone from the Dock to the Tower
edges = """Dock M 5
Dock N 5
Dock P 6
M Q 6
N Q 3
N R 7
P R 5
Q Tower 5
R Tower 3"""
h = {"Dock": 11, "M": 10, "N": 7, "P": 8, "Q": 4, "R": 3, "Tower": 0}
graph = {}
for line in edges.splitlines():
a, b, w = line.split()
graph.setdefault(a, {})[b] = int(w)
graph.setdefault(b, {})[a] = int(w)
start, goal = "Dock", "Tower"
g = {start: 0}
prev = {start: None}
open_nodes = [start]
closed = []
print("current next g h f")
print(start, start, 0, h[start], h[start])
while open_nodes:
current = min(sorted(open_nodes), key=lambda n: g[n] + h[n])
open_nodes.remove(current)
closed.append(current)
if current == goal:
break
for n, w in graph[current].items():
if n in closed:
continue
new_g = g[current] + w
row = f"{current} {n} {new_g} {h[n]} {new_g + h[n]}"
if n in g and new_g >= g[n]:
print(row, "(no better than", g[n], end=")\n")
continue
print(row)
g[n] = new_g
prev[n] = current
if n not in open_nodes:
open_nodes.append(n)
path = [goal]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
print("expanded:", " ".join(closed))
print("path:", " -> ".join(reversed(path)), "=", g[goal])Output
current next g h f Dock Dock 0 11 11 Dock M 5 10 15 Dock N 5 7 12 Dock P 6 8 14 N Q 8 4 12 N R 12 3 15 Q M 14 10 24 (no better than 5) Q Tower 13 0 13 expanded: Dock N Q Tower path: Dock -> N -> Q -> Tower = 13
# A* search: the cart from the Farm to the Mill
edges = """Farm A 4
Farm B 3
A C 5
B C 7
B D 6
C Mill 3
D Mill 5"""
h = {"Farm": 10, "A": 6, "B": 10, "C": 3, "D": 4, "Mill": 0}
graph = {}
for line in edges.splitlines():
a, b, w = line.split()
graph.setdefault(a, {})[b] = int(w)
graph.setdefault(b, {})[a] = int(w)
start, goal = "Farm", "Mill"
g = {start: 0}
prev = {start: None}
open_nodes = [start]
closed = []
print("current next g h f")
print(start, start, 0, h[start], h[start])
while open_nodes:
current = min(sorted(open_nodes), key=lambda n: g[n] + h[n])
open_nodes.remove(current)
closed.append(current)
if current == goal:
break
for n, w in graph[current].items():
if n in closed:
continue
new_g = g[current] + w
row = f"{current} {n} {new_g} {h[n]} {new_g + h[n]}"
if n in g and new_g >= g[n]:
print(row, "(no better than", g[n], end=")\n")
continue
print(row)
g[n] = new_g
prev[n] = current
if n not in open_nodes:
open_nodes.append(n)
path = [goal]
while prev[path[-1]] is not None:
path.append(prev[path[-1]])
print("expanded:", " ".join(closed))
print("path:", " -> ".join(reversed(path)), "=", g[goal])Output
current next g h f Farm Farm 0 10 10 Farm A 4 6 10 Farm B 3 10 13 A C 9 3 12 C B 16 10 26 (no better than 3) C Mill 12 0 12 expanded: Farm A C Mill path: Farm -> A -> C -> Mill = 12
Dijkstra or A*? Choosing and comparing
Short code B3·18·16
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Machine learning: programs that learn from data
Short code B3·18·17
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Supervised and unsupervised learning
Short code B3·18·18
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Reinforcement learning
Short code B3·18·19
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Artificial neural networks
Short code B3·18·20
weights = [0.5, -0.25, 0.75]
threshold = 0.5
for inputs in ([1, 1, 0], [1, 0, 1], [0, 1, 1]):
total = sum(x * w for x, w in zip(inputs, weights))
output = 1 if total >= threshold else 0
print("inputs", inputs, "weighted sum", total, "output", output)Output
inputs [1, 1, 0] weighted sum 0.25 output 0 inputs [1, 0, 1] weighted sum 1.25 output 1 inputs [0, 1, 1] weighted sum 0.5 output 1
Deep learning
Short code B3·18·21
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Back propagation of errors
Short code B3·18·22
x, target = 2, 10 # one input, and the output we want
w, rate = 3, 0.125 # starting weight, learning rate
for p in range(1, 5):
output = w * x
error = target - output
print(f"pass {p}: weight {w:g}, output {output:g}, error {error:g}")
w = w + rate * error * x # adjust the weight to reduce the errorOutput
pass 1: weight 3, output 6, error 4 pass 2: weight 4, output 8, error 2 pass 3: weight 4.5, output 9, error 1 pass 4: weight 4.75, output 9.5, error 0.5
Regression methods
Short code B3·18·23
xs = [1, 2, 3, 4, 5] # hours of revision
ys = [35, 44, 51, 56, 64] # test marks
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
b = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs)
a = my - b * mx
print(f"line of best fit: y = {a:g} + {b:g}x")
for a2, b2 in ((29, 7), (30, 7)):
errors = [y - (a2 + b2 * x) for x, y in zip(xs, ys)]
print(f"y = {a2} + {b2}x: errors {errors}, total squared error {sum(e * e for e in errors)}")
print(f"prediction for 6 hours: {a + b * 6:g}")Output
line of best fit: y = 29 + 7x y = 29 + 7x: errors [-1, 1, 1, -1, 0], total squared error 4 y = 30 + 7x: errors [-2, 0, 0, -2, -1], total squared error 9 prediction for 6 hours: 71
Past-paper practice
Short code B3·18·90
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Workbook 3: Artificial Intelligence (AI)
Short code W3·18 · Advanced Theory Workbook
The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.


