Artificial Intelligence, taught from nothing to full marks.
You have attended one class. That is fine. This book assumes you know nothing, teaches every topic in the COM 713.3 syllabus in plain language, shows you the exact words and diagrams that earn marks in a Pokhara University script, and then solves every numerical that has appeared in the last seven years.
Reading order: read a unit, then immediately do that unit's solved questions. Do not read all six units first, you will forget Unit 1 by the time you reach Unit 6.
How to use this book
Four passes, roughly three weeks. It works even if you start ten days out.
| Pass | What you do | Why |
|---|---|---|
| 1 | Read Units 1-6 straight through, ignoring the boxes. Do not memorise. | You need the shape of the subject before the detail. AI is one story: an agent that searches, reasons, handles uncertainty, and learns. |
| 2 | Re-read one unit, then solve that unit's past questions with a pen, without looking at the solution. | The exam is 70% numerical/procedural. Reading a solved A* does not teach you A*. Writing one does. |
| 3 | Work through the must-do list and write full 10-mark answers to time (18 minutes each). | Your bottleneck in the hall is writing speed and structure, not knowledge. |
| 4 | Night before: the one-page revision sheet only. | New material the night before displaces what you already know. |
Blue = how to present this in the answer sheet. Yellow = write this exact thing or you lose marks. Red = the mistake students actually make here. Green = a model answer or worked solution.
How to write a 10-mark answer
The single highest-return page in this book. Most students lose 20 marks on presentation, not on knowledge.
Your paper is 4 hours for 10 questions of 10 marks. That is 24 minutes per question, so budget 18 minutes writing and keep 60 minutes spare for the two numericals that will eat time (crypt-arithmetic and A*). Never leave a question blank: an examiner cannot give marks to a blank page, but a definition plus a diagram on a half-remembered topic reliably fetches 4.
The five-part skeleton
Every theory question in this paper fits this skeleton. Use it mechanically.
| Part | Content | Marks |
|---|---|---|
| Definition | One or two sentences. Formal, textbook phrasing. Underline the term being defined. | 2 |
| Body | Types / components / steps as a numbered or bulleted list, each with one line of explanation. Never a wall of prose. | 4 |
| Diagram | Labelled, boxed, drawn with a scale, captioned "Fig: …". Even when not asked. | 2 |
| Example | A concrete one: a vacuum cleaner, a self-driving car, a spam filter. Named, not generic. | 1.5 |
| Close | One line of advantages/limitations/application. | 0.5 |
- Answer the verb. "Compare" needs a table with a criteria column. "Justify" needs a stand and reasons. "Discuss with example" without an example is capped around 6.
- Diagram in every answer. This syllabus is diagram-heavy: agents, search trees, belief networks, perceptrons, expert systems, NLP stages. A page of prose with no figure reads as memorised.
- Show every step in numericals. In A*, write the OPEN and CLOSED list at each step. In crypt-arithmetic, state the carry equations. The steps carry the marks; the final answer is worth about 2.
- Write the final answer in a box and repeat it as a sentence: "Hence the optimal path is S→4→5→6→7 with solution cost 13."
- Start every question on a fresh page and write the question number in the margin. Examiners mark in bulk.
- Answering "Explain A*" by only writing the formula f(n)=g(n)+h(n). You must give admissibility, the algorithm, a worked example, and its drawback (memory).
- Giving a truth table where a proof was asked (resolution), or a proof where a table was asked.
- In FOPL questions, forgetting the quantifiers, writing
buys(x,y) → smart(x)with no ∀. That is an automatic cut. - Rounding probability answers to "about 10%" without showing Bayes' rule substituted with numbers.
- Running out of time because crypt-arithmetic was attempted first. Do it last: it is the one question that can silently consume 45 minutes.
Question-order strategy in the hall
- 0-5 min: read the whole paper, tick the four questions you can answer cold.
- 5-90 min: those four theory questions, fast, with diagrams.
- 90-150 min: the standard numericals: Bayes, A*, resolution, ID3. These are formulaic; you will have practised them.
- 150-210 min: crypt-arithmetic and anything requiring construction (Bayesian network, decision tree).
- 210-240 min: the weakest question, plus going back to add diagrams and headings to earlier answers.
Syllabus map and where the marks live
Counted across twelve papers, 2018 Spring to 2024 Fall.
| Unit | Syllabus hours | Typical marks in paper | What is always asked |
|---|---|---|---|
| 1 · Introduction, agents | 3 | 10-20 | Turing test; agent types; PEAS; task environments |
| 2 · Problem solving & search | 9 | 20-30 | A* on a graph; crypt-arithmetic (CSP); BFS/DFS comparison; heuristics |
| 3 · Knowledge & logic | 8 | 20-30 | FOPL translation; resolution proof; CNF conversion; forward/backward chaining |
| 4 · Uncertain knowledge | 9 | 10-20 | Bayes numerical; Bayesian belief network; fuzzy logic |
| 5 · Learning | 12 | 20-30 | Supervised/unsupervised/RL; backpropagation; decision tree & ID3; genetic algorithm; perceptron/XOR |
| 6 · Expert systems & NLP | 4 | 10-20 | Expert system components + development steps; NLP stages/ambiguity |
Six topics have appeared in every single paper in some form: crypt-arithmetic, A*, resolution/FOPL, a Bayes numerical, expert system components, and supervised vs unsupervised vs reinforcement learning. That is 60 marks. Pass marks are 60. Master those six and everything else is upside.
Introduction and Intelligent Agents
Foundations of AI, history, the Turing test, rational agents, agent structures, task environments.
What Artificial Intelligence actually means
Forget the movies. In this syllabus AI has a narrow, examinable meaning: the study and construction of agents that receive percepts from an environment and perform actions that are rational, that is, actions expected to maximise some performance measure. That one sentence is the definition to write in any "What is AI?" question.
Russell and Norvig, the prescribed book, organise every definition of AI ever proposed into four boxes along two axes: thinking versus acting, and human-like versus rational. Draw this table for a guaranteed 2 marks in any introductory question.
| Human-like (measured against people) | Rational (measured against an ideal) | |
|---|---|---|
| Thinking | Thinking humanly: cognitive modelling. Make machines whose internal reasoning matches human reasoning. Tools: introspection, psychological experiment, brain imaging. | Thinking rationally: the "laws of thought". Formal logic: encode knowledge as sentences, derive conclusions by valid inference. Basis of Units 3 and 4. |
| Acting | Acting humanly: the Turing test approach. Requires NLP, knowledge representation, automated reasoning, machine learning. | Acting rationally: the rational agent approach. This is the approach the whole course takes. |
"This course adopts the acting rationally / rational agent view, because rationality is mathematically well-defined and completely general, whereas human behaviour is neither."
Foundations of AI: the disciplines it borrowed from
A "foundations of AI" question wants six to eight lines. One line each:
| Discipline | What AI took from it |
|---|---|
| Philosophy | Logic, methods of reasoning, mind as a physical system, foundations of learning and rationality (Aristotle's syllogisms, Descartes' dualism). |
| Mathematics | Formal logic, computability, decidability, algorithms, probability, NP-completeness (Boole, Gödel, Turing). |
| Economics | Utility theory, decision theory, game theory, the idea of maximising expected utility, which defines rational behaviour. |
| Neuroscience | The physical substrate of thought; the neuron model that became the artificial neural network. |
| Psychology | Cognitive science, perception, information processing view of the mind. |
| Computer engineering | Fast, cheap hardware: without it none of this runs. |
| Control theory | Homeostatic systems, feedback loops, optimising an objective over time. |
| Linguistics | Knowledge representation, grammar and syntax: the base of NLP in Unit 6. |
History of AI: the milestones worth naming
- 1943 McCulloch & Pitts propose the first artificial neuron model.
- 1950 Turing publishes Computing Machinery and Intelligence, proposing the Turing test.
- 1956 Dartmouth Conference: John McCarthy coins the term "artificial intelligence". Birth year of the field.
- 1956-1969 Early enthusiasm: Logic Theorist, General Problem Solver (GPS), LISP (McCarthy, 1958), perceptron (Rosenblatt, 1958).
- 1969 Minsky & Papert show a single perceptron cannot learn XOR → funding collapses.
- 1974-1980 First "AI winter": the reality of intractability and the knowledge bottleneck.
- 1980s Expert systems become industry (DENDRAL, MYCIN, XCON); Japan's Fifth Generation project; then a second winter.
- 1986 Backpropagation popularised: neural networks revive.
- 1997 IBM's Deep Blue defeats world chess champion Garry Kasparov.
- 1995 onwards The field turns to probability and statistics: Bayesian networks, HMMs, machine learning on data.
- 2011 onwards IBM Watson wins Jeopardy!; deep learning wins ImageNet (2012); AlphaGo beats Lee Sedol (2016); large language models (2020s).
The Turing test
Definition: Proposed by Alan Turing in 1950 as an operational definition of intelligence. A human interrogator, in a separate room, converses through a text-only channel with a human and a machine. If the interrogator cannot reliably tell which is which, the machine is said to have passed the test and is deemed intelligent. Turing called it the "imitation game".
Capabilities a machine needs to pass it
- Natural language processing: to communicate in English.
- Knowledge representation: to store what it knows and hears.
- Automated reasoning: to answer questions and draw new conclusions.
- Machine learning: to adapt to new circumstances and detect patterns.
Total Turing test
The standard test avoids physical interaction. The total Turing test includes a video signal and a hatch through which objects are passed, so the machine must also have:
- Computer vision: to perceive objects.
- Robotics: to manipulate objects and move about.
These six capabilities together are essentially the whole of AI, which is why Turing's test still structures the field.
Reverse Turing test and CAPTCHA
In a reverse Turing test the roles are inverted: a machine is the interrogator and must decide whether the entity it is talking to is a human or another machine. CAPTCHA: Completely Automated Public Turing test to tell Computers and Humans Apart, is exactly this: a server poses a distorted-text or image-selection challenge that humans solve easily and programs solve poorly.
Take a stand: yes, with a qualification: and give three reasons. (i) The judge is a machine, not a human, so the roles are reversed. (ii) The goal is to distinguish human from machine, which is the Turing test's goal. (iii) But it differs in two ways: it is administered automatically at scale, and it tests a narrow perceptual skill rather than open conversation, so passing a CAPTCHA does not imply general intelligence. Then close: "Modern OCR and CNNs now break most text CAPTCHAs, which shows the test measures a capability gap that is shrinking, not intelligence itself."
Limitations and criticisms of the Turing test
- It tests imitation of humans, not intelligence. An aeroplane is not tested by whether it fools a birdwatcher.
- It rewards deception: a machine must pretend to be bad at arithmetic to pass.
- It is not reproducible or mathematically analysable; results depend on the interrogator's skill.
- Trivial programs can fool naive judges (ELIZA, 1966), so passing is not sufficient.
- Searle's Chinese Room argument: manipulating symbols correctly does not entail understanding.
- It is anthropocentric: it cannot recognise a non-human form of intelligence.
Asked "If the Turing test is passed, does this show computers exhibit intelligence?": answer: it shows behavioural equivalence in conversation, which is evidence of intelligence under a behaviourist definition, but it is neither necessary (a superintelligent system might fail by being too fast and accurate) nor sufficient (ELIZA-style trickery). Conclude that AI moved on to the rational-agent definition for exactly this reason.
Agents, rationality and PEAS
An agent is anything that perceives its environment through sensors and acts upon that environment through actuators. The percept sequence is the complete history of everything the agent has perceived. An agent function maps every percept sequence to an action; the agent program is its concrete implementation running on the architecture.
Rational agent
Definition: For each possible percept sequence, a rational agent selects the action that is expected to maximise its performance measure, given the evidence provided by the percept sequence and whatever built-in knowledge the agent has.
- The performance measure that defines success.
- The agent's prior knowledge of the environment.
- The actions available to the agent.
- The agent's percept sequence to date.
Rational is not the same as omniscient (rationality maximises expected not actual performance), not the same as perfect, and not the same as clairvoyant. A rational agent must also explore, learn, and be autonomous: relying on its own percepts rather than only on the designer's prior knowledge.
PEAS: how to specify a task environment
Before designing an agent you specify Performance measure, Environment, Actuators, Sensors. Always answer PEAS questions as a table.
| Agent | Performance measure | Environment | Actuators | Sensors |
|---|---|---|---|---|
| Part-picking robot | Percentage of parts placed in the correct bin; parts per hour; damage rate | Conveyor belt with parts; bins; factory floor | Jointed arm, gripper/suction hand, wheels or rail motor | Camera, joint-angle sensors, force/tactile sensors, proximity sensor |
| Automated car | Safe, fast, legal, comfortable trip; fuel economy; passenger satisfaction | Roads, traffic, pedestrians, weather, traffic signals, customers | Steering, accelerator, brake, indicator, horn, display/voice | Cameras, LIDAR, RADAR, GPS, speedometer, odometer, accelerometer, engine sensors |
| Medical diagnosis system | Healthy patient, minimised cost, avoidance of lawsuits | Patient, hospital, staff | Screen display of questions, tests, diagnoses, treatments | Keyboard entry of symptoms, findings, patient answers |
| Vacuum cleaner agent | Cleanliness, energy used, time taken, noise | Room, dirt, obstacles, floor type | Wheels, brushes, suction, vacuum extractor | Dirt sensor, bump/cliff sensor, camera, wall sensor |
Types of intelligent agents
Five types, in increasing order of capability. Every one of them has appeared in a paper. Learn the one-line definition, the diagram, and a named example for each.
1. Simple reflex agent
Selects an action using only the current percept, ignoring the percept history, through
condition-action rules of the form if condition then action. Works only if the environment
is fully observable; otherwise it gets stuck in infinite loops.
Example: a thermostat; a vacuum agent whose rule is "if dirty then suck else move".
2. Model-based reflex agent
Maintains internal state: a model of the world, so it can handle a partially observable environment. The model answers two questions: how the world evolves independently of the agent, and how the agent's own actions affect the world. Example: a robot vacuum that remembers which rooms it has already cleaned; a car that remembers a vehicle it saw a moment ago and is now in its blind spot.
3. Goal-based agent
Keeps internal state and explicit goal information describing desirable situations. It asks "what will happen if I do action A, and does that bring me closer to the goal?": this requires search and planning (all of Unit 2). Slower and less efficient than a reflex agent, but far more flexible: change the goal and the behaviour changes without rewriting rules. Example: a route-finding car agent told to reach Pokhara; a chess program aiming at checkmate.
4. Utility-based agent
Goals give only a binary distinction, happy or unhappy. A utility function maps a state (or a sequence) to a real number measuring degree of happiness, so the agent can choose between conflicting goals (speed versus safety) and weigh uncertain outcomes by expected utility. Example: a taxi choosing between a fast risky route and a slow safe one; an airline pricing engine.
| Criterion | Goal-based | Utility-based |
|---|---|---|
| Decision basis | Binary: does this state satisfy the goal? | Continuous: how good is this state, numerically? |
| Conflicting goals | Cannot trade off | Trades off via utility weights |
| Uncertainty | Poorly handled | Maximises expected utility over outcome probabilities |
| Multiple solutions | Any goal-satisfying path is acceptable | Picks the best-quality path |
| Complexity | Simpler, needs only goal test | Needs a full utility function; harder to design |
| Example | GPS that finds a route to the destination | GPS that balances time, tolls, fuel and traffic risk |
5. Learning agent
Any of the above can be turned into a learning agent. Four components: this list is the answer to "explain learning agents":
- Performance element: selects external actions; this is the whole agent we described so far.
- Critic: observes the environment through a fixed performance standard and tells the learning element how well the agent is doing.
- Learning element: makes improvements to the performance element using the critic's feedback.
- Problem generator: suggests exploratory actions that are suboptimal now but lead to informative experiences (this is how the agent avoids getting stuck in a local habit).
Properties of task environments
Asked as "discuss rational agent with its various task environment". Give all seven pairs, each with a one-line definition and an example, then classify one environment (chess, taxi driving) against all seven as a closing table.
| Property | Meaning | Example |
|---|---|---|
| Fully vs partially observable | Do the sensors give access to the complete state of the environment at each point? | Chess (fully) vs taxi driving / poker (partially) |
| Single-agent vs multi-agent | Is another entity's behaviour maximising a performance measure that depends on our actions? Multi-agent splits into competitive and cooperative. | Crossword (single) vs chess (competitive) vs taxi driving (partly cooperative) |
| Deterministic vs stochastic | Is the next state completely determined by the current state and the action? (If it is deterministic except for other agents, we call it strategic.) | Chess (deterministic) vs taxi driving, dice games (stochastic) |
| Episodic vs sequential | Is experience divided into independent episodes, or does the current action affect all future decisions? | Defect-spotting on an assembly line (episodic) vs chess, driving (sequential) |
| Static vs dynamic | Can the environment change while the agent is deliberating? (Semi-dynamic: environment fixed but score changes with time, chess with a clock.) | Crossword (static) vs taxi driving (dynamic) |
| Discrete vs continuous | Are states, time, percepts and actions finite and distinct, or continuously varying? | Chess (discrete) vs taxi driving (continuous) |
| Known vs unknown | Does the agent know the "laws of physics" / outcomes of actions? This is about the agent's knowledge, not about observability. | Solitaire with published rules (known) vs a new video game (unknown) |
"The hardest case is a partially observable, multi-agent, stochastic, sequential, dynamic, continuous and unknown environment: automated taxi driving is exactly this, which is why it is still unsolved."
Human intelligence vs machine intelligence
| Basis | Human intelligence | Machine intelligence |
|---|---|---|
| Origin | Biological, evolved; carried by neurons | Engineered; programs on silicon |
| Learning | From few examples, by experience, analogy and transfer | Needs large labelled datasets; transfers poorly across domains |
| Speed & precision | Slow, error-prone in computation | Extremely fast, exact, tireless |
| Adaptability | General; adapts to entirely new situations | Narrow; degrades outside its training distribution |
| Creativity & common sense | Present | Limited; no genuine common-sense understanding |
| Emotion & ethics | Intrinsic; social and moral judgement | Simulated at best; ethics must be imposed externally |
| Memory | Associative, lossy, reconstructive | Exact, unlimited, retrievable |
| Fatigue | Tires, needs rest | Continuous operation |
Applications of AI to list in that same question: healthcare diagnosis and imaging, autonomous vehicles, natural language assistants and machine translation, fraud detection and credit scoring, recommendation systems, robotics and manufacturing, agriculture (crop and pest detection), weather and disaster prediction, expert systems, computer vision and biometrics, game playing.
↑ contentsProblem Solving and Searching
State space, uninformed and informed search, heuristics, A*, local search, adversarial search, constraint satisfaction, optimisation.
Problem solving as search
A goal-based agent solves a problem by deciding on a goal, formulating the problem, searching for a sequence of actions that reaches the goal, and then executing it. Formulating the problem means writing down five things, memorise this list, it is the standard opener for the whole unit:
- Initial state: where the agent starts. In(Kathmandu).
- Actions: ACTIONS(s) returns the set of actions applicable in state s.
- Transition model: RESULT(s, a) returns the state reached. Together, the initial state, actions and transition model define the state space, drawn as a graph whose nodes are states and edges are actions.
- Goal test: decides whether a state is a goal state.
- Path cost: a numeric cost for each path; step cost c(s, a, s′) is the cost of one action. The solution is a path from initial to goal; the optimal solution is the one with the lowest path cost.
8-puzzle: States = the 9! /2 = 181,440 reachable arrangements of eight tiles and a blank. Initial state = any given configuration. Actions = move blank Up, Down, Left, Right. Goal test = tiles in order. Path cost = 1 per move. Water-jug and the vacuum world (2 locations × dirt states = 8 states) are equally acceptable and quicker to draw.
How every search algorithm is judged
| Criterion | Question it answers |
|---|---|
| Completeness | If a solution exists, is the algorithm guaranteed to find it? |
| Optimality | Does it find the least-cost solution? |
| Time complexity | How many nodes are generated? Expressed with b = branching factor, d = depth of shallowest solution, m = maximum depth of the tree. |
| Space complexity | How many nodes must be kept in memory at once? |
Uninformed (blind) search
No information beyond the problem definition, the algorithm cannot tell a promising state from a hopeless one. It only knows whether a state is a goal.
Breadth-first search (BFS)
Expands the shallowest unexpanded node first. Implemented with a FIFO queue. Complete; optimal only when every step cost is equal; time and space O(bd). Its fatal flaw is memory: it keeps every node of the frontier.
Uniform cost search (UCS)
Expands the node with the lowest path cost g(n), using a priority queue. It is BFS generalised to unequal step costs. Complete and optimal for any non-negative step costs. Complexity O(b1+⌊C*/ε⌋) where C* is the optimal cost and ε the smallest step cost. UCS = A* with h(n) = 0: say this and you get the comparison mark free.
Depth-first search (DFS)
Expands the deepest node first, using a LIFO stack (or recursion). Space is only O(bm), which is its one great virtue. Not complete (infinite loops on cycles or infinite depth) and not optimal. Time O(bm) which can be far worse than BFS when m ≫ d.
Depth-limited search (DLS)
DFS with a cut-off depth ℓ. Fixes the infinite-path problem but becomes incomplete if ℓ < d, and is non-optimal. Time O(bℓ), space O(bℓ).
Iterative deepening search (IDS)
Runs DLS with ℓ = 0, 1, 2, … until a goal is found. The best uninformed method: it combines DFS's O(bd) memory with BFS's completeness and optimality (for unit costs). Repeating the shallow levels costs little because the bottom level dominates the node count, for b = 10, d = 5, IDS generates about 123,456 nodes against BFS's 111,111, an overhead of only ~11%.
Bidirectional search
Runs two simultaneous searches, forward from the initial state and backward from the goal, stopping when the frontiers meet. Time and space fall from O(bd) to O(bd/2), an enormous saving. Requires the goal state to be explicitly known and the actions to be reversible, and the meeting check itself costs memory.
| Strategy | Complete? | Optimal? | Time | Space | Data structure |
|---|---|---|---|---|---|
| Breadth-first | Yes (finite b) | Yes, if equal step costs | O(bd) | O(bd) | FIFO queue |
| Uniform cost | Yes | Yes | O(b1+⌊C*/ε⌋) | same | Priority queue on g(n) |
| Depth-first | No | No | O(bm) | O(bm) | LIFO stack |
| Depth-limited | No (if ℓ < d) | No | O(bℓ) | O(bℓ) | Stack + limit |
| Iterative deepening | Yes | Yes, if equal step costs | O(bd) | O(bd) | Stack, repeated |
| Bidirectional | Yes | Yes (with BFS both ways) | O(bd/2) | O(bd/2) | Two queues |
| Greedy best-first | No | No | O(bm) | O(bm) | Priority queue on h(n) |
| A* | Yes | Yes, if h admissible | Exponential | Exponential: the drawback | Priority queue on f(n) |
"Compare BFS/DFS/UCS/A*" is a recurring 10-mark question and this table plus Fig 2.1 plus one worked example is a complete answer. Note the two facts examiners check: DFS is the only one with linear memory, and BFS is optimal only for uniform step costs.
Informed (heuristic) search
Heuristic function h(n) = the estimated cost of the cheapest path from node n to a goal state, with h(goal) = 0. It injects problem-specific knowledge so the search can prefer promising branches. A heuristic is:
- Admissible if it never overestimates: h(n) ≤ h*(n), the true remaining cost. Admissibility is what makes A* optimal in tree search.
- Consistent (monotonic) if for every node n and successor n′, h(n) ≤ c(n, a, n′) + h(n′), the triangle inequality. Consistency implies admissibility and makes A* optimal for graph search.
Where heuristics come from: relax the problem. In the 8-puzzle, if a tile could move anywhere you get h₁ = number of misplaced tiles; if it could move to any adjacent square you get h₂ = total Manhattan distance. Both are admissible, and h₂ dominates h₁ (h₂ ≥ h₁ everywhere), so h₂ expands fewer nodes. Other sources: pattern databases, subproblem costs, and learning from experience.
Significance: reduces the effective branching factor, turns intractable exponential search into feasible search, guides towards the goal.
Types: admissible vs non-admissible; consistent vs inconsistent; dominating heuristics; exact vs relaxed-problem-derived; domain-specific (Manhattan distance, straight-line distance, misplaced tiles, number of attacking pairs in 8-queens).
Challenges: designing one is domain expertise, not algorithmic; a good heuristic costs time to compute (there is a trade-off between accuracy and cost); inadmissible heuristics break optimality; heuristics can mislead into local optima (greedy search); memory still grows exponentially in A*.
Greedy best-first search
Evaluation function f(n) = h(n). Expands the node that looks closest to the goal. Fast and memory-light in practice, but incomplete (can loop) and not optimal, the classic failure is Arad→Sibiu→Fagaras→Bucharest, which greedy finds but which is 32 km longer than the route through Rimnicu Vilcea and Pitesti.
A* search: the most examined algorithm in this syllabus
Algorithm: write these steps, then trace the table:
- Put the start node in OPEN with f = g + h; CLOSED is empty.
- If OPEN is empty, stop and report failure.
- Remove from OPEN the node n with the smallest f(n) and move it to CLOSED.
- If n is the goal, stop; trace parent pointers back to give the solution path and cost.
- Otherwise generate the successors of n. For each successor n′, compute g(n′) = g(n) + c(n, n′) and f(n′) = g(n′) + h(n′).
- If n′ is new, add it to OPEN. If it is already in OPEN or CLOSED with a larger g, update its g and parent (re-open it if necessary); otherwise discard it.
- Go to step 2.
- Complete (if b is finite and step costs exceed some ε > 0).
- Optimal if h is admissible (tree search) or consistent (graph search).
- Optimally efficient: no other optimal algorithm using the same heuristic is guaranteed to expand fewer nodes than A*. Proof sketch: any algorithm that does not expand all nodes with f(n) < C* risks missing an optimal solution, because such a node might lie on an optimal path; A* expands exactly those nodes.
- Drawback: it keeps every generated node in memory, so space is exponential, A* runs out of memory long before it runs out of time. Remedies: IDA*, RBFS, SMA*, memory-bounded and weighted A*.
Local search and optimisation
When the path to the goal is irrelevant and only the final state matters (8-queens, timetabling, VLSI layout), keep a single current state and move to a better neighbour. Memory is constant, and the state space may be infinite.
Hill climbing
A loop that continually moves in the direction of increasing value and terminates when no neighbour is higher. It is "greedy local search": it never looks beyond the immediate neighbours, keeps no search tree, and is sometimes described as trying to climb Everest in thick fog while suffering from amnesia.
Variants: Simple hill climbing (take the first better neighbour), steepest-ascent (evaluate all neighbours, take the best), stochastic (choose randomly among uphill moves), first-choice (generate successors randomly until a better one appears, good for many successors), random-restart (run hill climbing from random initial states until a goal is found; this one is complete with probability approaching 1).
| Problem | What happens | Solution |
|---|---|---|
| Local maximum | A peak higher than its neighbours but lower than the global maximum; the algorithm halts there. | Random-restart hill climbing; simulated annealing; backtracking to an earlier promising node. |
| Plateau / shoulder | A flat region where all neighbours have the same value, so search has no direction and wanders. | Allow a limited number of sideways moves; take a big jump; random restart. |
| Ridge | A sequence of local maxima along a slope that is not directly climbable by single moves, every single move goes downhill. | Move in several directions at once (compound moves); use a different operator set; stochastic hill climbing. |
Simulated annealing fixes all three by occasionally accepting a worse move with probability eΔE/T, where T (temperature) is lowered over time. At high T it explores almost randomly; as T → 0 it becomes ordinary hill climbing. If the schedule lowers T slowly enough it finds the global optimum with probability approaching 1. Local beam search keeps k states instead of one; genetic algorithms are beam search with sexual recombination.
Adversarial search: min-max and alpha-beta
In a two-player, zero-sum, perfect-information game (chess, tic-tac-toe), one player MAX tries to maximise the score and the opponent MIN tries to minimise it. The min-max algorithm computes the value of each node by a depth-first exploration to a terminal (or cut-off) depth, then backs values up: MAX nodes take the maximum of their children, MIN nodes the minimum. It assumes the opponent plays optimally, which is why it is suitable for chess: the resulting move is the best achievable against a perfect opponent. Complete and optimal on finite trees; time O(bm), space O(bm).
Alpha-beta pruning keeps two bounds along the current path: α = the best (highest) value MAX can guarantee so far, β = the best (lowest) value MIN can guarantee. Prune a branch when α ≥ β, because that branch can never influence the final decision.
- It returns exactly the same move as min-max: pruning loses nothing.
- With perfect move ordering, time drops from O(bm) to O(bm/2), so the program can search roughly twice as deep in the same time. Random ordering gives about O(b3m/4).
- It saves memory and evaluation-function calls, enabling real-time play.
Why the AI still struggles against aggressive human players (a 2024 question): the evaluation function is imperfect at the cut-off depth, unexpected sacrifices push the real consequence beyond the horizon (the horizon effect), and min-max assumes an optimal opponent so it plays conservatively. Fixes: quiescence search, iterative deepening with move ordering, transposition tables, opponent modelling, and learned evaluation functions.
Constraint Satisfaction Problems (CSP)
Definition: A CSP is defined by three components:
- X: a set of variables {X₁ … Xₙ}.
- D: a set of domains {D₁ … Dₙ}, one per variable, listing its allowed values.
- C: a set of constraints specifying allowed combinations of values.
A state is an assignment of values to some variables; it is consistent if it violates no constraint, complete if every variable is assigned, and a solution if it is both. The key idea is that the goal test is decomposed into constraints, so the solver can prune whole regions of the space at once instead of treating states as black boxes.
Types of constraints: unary (one variable: SA ≠ green), binary (two variables, SA ≠ WA), higher-order/global (Alldiff, the cryptarithmetic column sums), and preference/soft constraints (turned into an optimisation problem). Examples: map colouring, N-queens, Sudoku, timetable scheduling, job-shop scheduling, crypt-arithmetic.
Solving techniques to name: backtracking search (depth-first, one variable at a time); forward checking (delete inconsistent values from neighbours' domains immediately); constraint propagation / arc consistency (AC-3); and the ordering heuristics: MRV (minimum remaining values: pick the most constrained variable), degree heuristic (tie-break on the variable involved in most constraints), LCV (least constraining value: pick the value that rules out fewest choices for neighbours). Local search with the min-conflicts heuristic solves million-queens problems in seconds.
Crypt-arithmetic: the guaranteed 10 marks
Every paper since 2018 contains one. It is a CSP: variables are the letters, domains are {0…9}, constraints are all letters have different digits, no leading letter is zero, and one column-sum equation with carries per column.
- Each letter stands for exactly one digit, 0-9.
- Each digit is used by at most one letter (Alldiff).
- No leading letter of any word may be 0.
- The arithmetic must hold column by column, from the units column leftwards.
- Each column carry cᵢ ∈ {0, 1} for addition of two numbers (0, 1 or 2 for three addends).
- If the sum has one more digit than the longest addend, that extra leading digit must be the final carry, so it is 1.
- The solution must be verified by substituting back into the original sum.
The method, in the order you should write it
- Write the sum in column form, label columns from the right as c₁, c₂, … and mark the carries.
- Fix the forced digits first: the leading digit of a longer answer is 1; letters that repeat across columns give the strongest equations.
- Write one algebraic equation per column, of the form (digit + digit + carry-in) = result digit + 10 × carry-out.
- Substitute known values and reason about parity and ranges to narrow the domains, this is constraint propagation.
- Only when the domains are small, try candidates (backtracking); reject any that repeat a digit.
- Verify by full addition and state the mapping in a table.
All seven crypt-arithmetic problems set at PU, EAT+THAT, ODD+ODD, GO+TO, NINA+SING, LOGIC+LOGIC, WRONG+WRONG and BASE+BALL, are solved step by step in the solved questions section.
Genetic algorithms
Definition: A genetic algorithm is a randomised, population-based search and optimisation technique inspired by Darwinian natural selection, in which candidate solutions encoded as chromosomes are evaluated by a fitness function and evolved through selection, crossover and mutation over successive generations.
Because evolution is an existence proof of a search algorithm that produced intelligence itself, and because it gives AI a general-purpose optimiser for problems where the search space is huge, discontinuous, noisy or has no usable gradient: neural network weight and architecture optimisation, feature selection, timetabling, TSP and routing, VLSI layout, game strategy evolution, robot controllers. Unlike hill climbing, a GA maintains a population, so it escapes local optima; unlike exhaustive search, it samples the space intelligently.
Steps of a genetic algorithm
- Encoding / representation. Represent a candidate solution as a chromosome, usually a binary string, but permutations or real vectors are also used.
- Initialise population. Generate N random chromosomes.
- Fitness evaluation. Score each chromosome with a fitness function f(x) that measures how good that solution is.
- Selection. Choose parents with probability related to fitness, roulette-wheel, tournament, rank or elitist selection.
- Crossover (recombination). With probability pc (typically 0.6-0.9) pick a crossover point and swap the tails of two parents to make two offspring. Variants: single-point, two-point, uniform.
- Mutation. With a small probability pm (typically 0.001-0.01) flip a bit, to maintain diversity and reintroduce lost alleles.
- Replacement. Form the new generation, usually keeping the best individuals (elitism).
- Termination. Stop when the fitness converges, an optimal solution is found, or a generation limit is reached. Return the fittest chromosome.
Encoding: 5-bit binary, so 01101 = 13. Population (N = 4): 01101 (13), 11000 (24), 01000 (8), 10011 (19).
Selection (roulette wheel): 11000 and 10011 are most likely to be picked; 01000 is likely to die out. Suppose we pick 01101, 11000, 11000, 10011.
Crossover after bit 4 on pair (0110|1, 1100|0) → offspring 01100 (12) and 11001 (25). Crossover after bit 2 on (11|000, 10|011) → 11011 (27) and 10000 (16).
Mutation: flip one bit of 11011 → 11111 (31).
New generation fitness: 144, 625, 729, 961: total 2459, average risen from 293 to 615, and the optimum x = 31 has appeared. Conclude: "the average fitness improves each generation, which demonstrates the hill-climbing effect of selection combined with the exploration provided by crossover and mutation."
Swarm intelligence, ant colony and particle swarm optimisation
Swarm / collective intelligence is the emergence of global intelligent behaviour from the local interactions of many simple agents with no central control, ants, bees, bird flocks, fish schools. It is used when the search space is large, dynamic and distributed, and when robustness matters more than a guaranteed optimum: routing, scheduling, clustering, robot swarms, feature selection.
Ant Colony Optimisation (ACO)
Real ants deposit pheromone on their path; shorter paths are traversed more often per unit time, so they accumulate pheromone faster, so more ants follow them, a positive feedback loop that converges on the shortest route. Evaporation prevents premature convergence on a bad path.
Algorithm:
- Initialise pheromone τij on every edge to a small constant; place m ants on random nodes.
- Each ant builds a complete tour, choosing the next node j from i with probability pij = [τij]α[ηij]β ⁄ Σ [τik]α[ηik]β, where ηij = 1/dij is the visibility (heuristic desirability), α weights pheromone and β weights distance.
- Evaporate: τij ← (1 − ρ)·τij, with evaporation rate ρ ∈ (0,1).
- Deposit: each ant adds Δτ = Q / Lk to the edges of its tour, where Lk is its tour length: shorter tours deposit more.
- Record the best tour; repeat from step 2 until the iteration limit or convergence.
Answer to "can search optimisation be performed with swarm intelligence?": yes: ACO solves TSP, vehicle routing, network routing and job scheduling; it is adaptive to changing graphs, inherently parallel and robust to failure of individual agents, at the cost of no optimality guarantee, several parameters to tune (α, β, ρ, Q, m) and slow theoretical convergence.
Particle Swarm Optimisation (PSO)
A population of particles flies through the search space; each remembers its own best position pbest and knows the swarm's best gbest. On each iteration:
Steps: initialise positions and velocities randomly → evaluate fitness → update pbest and gbest → update velocity and position by the equations above → repeat until convergence → return gbest. PSO is simpler than a GA (no crossover or mutation, few parameters) and works naturally on continuous problems such as neural network weight tuning.
↑ contentsKnowledge, Logic and Inferencing
Knowledge representation, propositional logic, rules of inference, first-order predicate logic, CNF, resolution, forward and backward chaining.
Knowledge and its representation
Knowledge is information about the world in a form that an agent can use to decide what to do: facts, relationships, rules, procedures and heuristics. A knowledge-based agent keeps a knowledge base (a set of sentences in a formal language), TELLs it new percepts, and ASKs it what action to take; the answer follows by inference.
Types of knowledge
- Declarative: knowing that: facts and assertions. "Kathmandu is the capital of Nepal."
- Procedural: knowing how: rules, procedures, strategies. "To start the car, turn the key."
- Meta-knowledge: knowledge about knowledge: which rule to apply, how reliable a source is.
- Heuristic: rules of thumb from an expert's experience.
- Structural: knowledge of concepts, relationships and hierarchies between objects.
Knowledge representation schemes
| Scheme | Idea | Strength / weakness |
|---|---|---|
| Logical representation | Propositional and first-order logic sentences with formal syntax and semantics. | Precise, sound inference; but rigid and can be computationally expensive. |
| Semantic network | Graph of nodes (objects/concepts) and labelled arcs (relations such as is-a, has-a). | Intuitive, inherits properties naturally; but no standard semantics and inefficient for large networks. |
| Frames | A record-like structure of slots and fillers describing a stereotyped object or situation. | Organised, supports defaults and inheritance; but inflexible for exceptions. |
| Production rules | if-then rules operating on working memory, driven by an inference engine. | Modular, easy for experts to write, the basis of expert systems; but hard to keep consistent as rules multiply. |
| Scripts | Frame-like description of a stereotyped sequence of events (the restaurant script). | Good for narrative understanding in NLP. |
Properties of a good representation: representational adequacy (can express everything needed), inferential adequacy (can derive new knowledge), inferential efficiency (can do so quickly, with guidance), acquisitional efficiency (new knowledge can be added easily).
Frames represent the same knowledge as a table of slots and values, which is easier to compute with:
Semantic nets and frames are used in reasoning under uncertainty by attaching certainty factors or probabilities to links and slots, and they underpin ontologies and the knowledge base of an expert system.
Propositional logic
A proposition is a declarative sentence that is either true or false. Symbols P, Q, R combine with connectives ¬ (not), ∧ (and), ∨ (or), → (implies), ↔ (if and only if).
| P | Q | ¬P | P ∧ Q | P ∨ Q | P → Q | P ↔ Q |
|---|---|---|---|---|---|---|
| T | T | F | T | T | T | T |
| T | F | F | F | T | F | F |
| F | T | T | F | T | T | F |
| F | F | T | F | F | T | T |
A sentence is valid (a tautology) if true in every model, satisfiable if true in some model, unsatisfiable if true in none. KB ⊨ α ("KB entails α") means α is true in every model in which KB is true; the whole of logical inference is machinery for deciding entailment. The key identity used by resolution is: KB ⊨ α if and only if (KB ∧ ¬α) is unsatisfiable: this is proof by refutation / contradiction.
Rules of inference: list these in any "rules for inference" question
| Rule | Form | Example |
|---|---|---|
| Modus Ponens | P → Q, P ⊢ Q | "If it rains the ground is wet"; it rains ⟹ the ground is wet. |
| Modus Tollens | P → Q, ¬Q ⊢ ¬P | Ground is not wet ⟹ it did not rain. |
| And-elimination | P ∧ Q ⊢ P | : |
| And-introduction | P, Q ⊢ P ∧ Q | : |
| Or-introduction | P ⊢ P ∨ Q | : |
| Disjunctive syllogism | P ∨ Q, ¬P ⊢ Q | : |
| Hypothetical syllogism | P → Q, Q → R ⊢ P → R | Chaining implications. |
| Resolution | P ∨ Q, ¬P ∨ R ⊢ Q ∨ R | The single rule needed for a complete proof procedure. |
| Universal instantiation | ∀x P(x) ⊢ P(a) | FOL only. |
| Existential instantiation | ∃x P(x) ⊢ P(k), k a new constant | FOL only. |
Useful equivalences for rewriting: P → Q ≡ ¬P ∨ Q; P ↔ Q ≡ (P → Q) ∧ (Q → P); De Morgan ¬(P ∧ Q) ≡ ¬P ∨ ¬Q and ¬(P ∨ Q) ≡ ¬P ∧ ¬Q; contraposition P → Q ≡ ¬Q → ¬P; distributivity P ∨ (Q ∧ R) ≡ (P ∨ Q) ∧ (P ∨ R).
It has no way to talk about objects, their properties or relations. To say "all humans are mortal" you must write one proposition per human. It cannot express quantification, cannot generalise, and the knowledge base grows unmanageably. It is also purely declarative and cannot handle uncertainty.
First-order predicate logic (FOPL)
FOPL adds objects, relations and quantifiers to propositional logic.
- Constants: Ram, Nepal, 3: specific objects.
- Variables: x, y, z.
- Predicates: likes(x, y), Student(x): relations returning true/false.
- Functions: father(x), plus(x, y): return objects, not truth values.
- Connectives: ¬ ∧ ∨ → ↔ as before.
- Quantifiers: ∀ (universal, "for all") and ∃ (existential, "there exists").
∀ goes with →, ∃ goes with ∧.
"Every student is smart" = ∀x student(x) → smart(x). Writing ∀x student(x) ∧ smart(x) claims
everything in the universe is a smart student: wrong.
"Some student is smart" = ∃x student(x) ∧ smart(x). Writing ∃x student(x) → smart(x) is
trivially satisfied by any non-student, wrong.
Advantages of FOPL: asked directly in 2018
- Expressive: represents objects, their properties, relations among them, and general rules over all objects, which propositional logic cannot.
- Concise: one quantified sentence replaces thousands of propositions, so the knowledge base is compact and maintainable.
- Well-defined syntax and semantics, so inference is sound and complete (resolution refutation).
- Declarative and modular: knowledge is separate from the inference engine, so new facts can be added without rewriting procedures.
- It is the basis of logic programming (Prolog) and of the rule bases of expert systems.
- Supports variables, functions and equality, allowing complex real-world statements.
Propositional vs predicate logic: the comparison table
| Basis | Propositional logic | Predicate logic (FOPL) |
|---|---|---|
| Basic unit | A whole proposition (P, Q) | Objects, predicates, functions, quantified variables |
| Quantifiers | None | ∀ and ∃ |
| Expressive power | Low: cannot generalise over objects | High: can state general rules over all objects |
| Ontological commitment | Facts only | Facts, objects and relations |
| Knowledge base size | Grows with the number of objects | Compact and reusable |
| Decidability | Decidable (truth tables always terminate) | Semi-decidable: proofs of entailment terminate, disproofs may not |
| Example | "Ram is a student" = P (an atom with no internal structure) | student(Ram); ∀x student(x) → studies(x) |
Unification and substitution
Unification finds a substitution θ that makes two logical expressions identical: UNIFY(p, q) = θ where SUBST(θ, p) = SUBST(θ, q). Example: UNIFY(knows(Ram, x), knows(y, Sita)) gives θ = {y/Ram, x/Sita}. Rules: a variable may bind to any term; two different constants never unify; the occur check forbids binding x to a term containing x. Unification is what lets Generalised Modus Ponens and resolution work on quantified sentences.
Conjunctive Normal Form (CNF)
Definition: A sentence is in CNF when it is a conjunction of clauses, where each clause is a disjunction of literals: (A ∨ ¬B) ∧ (C ∨ D ∨ ¬E).
- The resolution inference rule operates only on clauses, and resolution is the single rule that is sound and refutation-complete for first-order logic: so every proof procedure needs its input in CNF.
- CNF is a uniform, standard form: quantifiers and implications are removed, so an automated theorem prover needs to handle only one syntactic shape.
- Every propositional or first-order sentence has a logically equivalent CNF (equisatisfiable after Skolemisation), so nothing is lost.
- It makes the search mechanical and machine-friendly: clause sets are just lists of literals, easy to index and match.
The eight steps of CNF conversion
- Eliminate ↔: α ↔ β becomes (α → β) ∧ (β → α).
- Eliminate →: α → β becomes ¬α ∨ β.
- Move ¬ inwards (De Morgan): ¬(α ∧ β) → ¬α ∨ ¬β; ¬(α ∨ β) → ¬α ∧ ¬β; ¬¬α → α; ¬∀x P → ∃x ¬P; ¬∃x P → ∀x ¬P. The result is negation normal form.
- Standardise variables apart: rename so that each quantifier uses a unique variable.
- Skolemise: remove ∃. An ∃ not inside any ∀ becomes a new constant (a Skolem constant); an ∃ inside ∀x becomes a function of x (a Skolem function), e.g. ∀x ∃y loves(x, y) → ∀x loves(x, F(x)).
- Drop universal quantifiers: all remaining variables are implicitly universally quantified.
- Distribute ∨ over ∧: (α ∧ β) ∨ γ → (α ∨ γ) ∧ (β ∨ γ).
- Flatten and separate clauses, writing each conjunct on its own line.
Both CNF problems that PU has ever set, P → ((Q ∧ ¬R) ↔ S) and
"Everyone who loves all animals is loved by someone", are worked out line by line in the
solved section.
Resolution and refutation
Resolution rule: from (A ∨ B) and (¬B ∨ C) infer (A ∨ C). The complementary literals B and ¬B cancel. In FOL the literals must first be made identical by unification, and the resulting substitution is applied to the resolvent.
- Convert all sentences of the knowledge base into FOPL.
- Convert each into CNF and list the clauses, numbered.
- Negate the goal and convert it to CNF; add it to the clause set.
- Repeatedly resolve pairs of clauses containing complementary literals, unifying as needed, adding each resolvent to the set.
- If the empty clause □ (NIL) is derived, a contradiction exists, so the negated goal is false and hence the goal is proved. Draw the derivation as a tree.
Forward and backward chaining
Both work on Horn clauses (clauses with at most one positive literal, i.e. rules of the form P₁ ∧ P₂ ∧ … → Q), which is why they are efficient enough for real expert systems.
Forward chaining (data-driven) starts from the known facts, finds all rules whose premises are satisfied, adds their conclusions to working memory, and repeats until the goal appears or no new fact can be derived. Backward chaining (goal-driven) starts from the goal, finds rules that conclude it, and recursively tries to prove those rules' premises as sub-goals.
| Basis | Forward chaining | Backward chaining |
|---|---|---|
| Direction | Facts → conclusions (bottom-up) | Goal → facts (top-down) |
| Also called | Data-driven, forward deduction | Goal-driven, backward deduction |
| Starts from | Available data in working memory | The hypothesis to be proved |
| Search strategy | Breadth-first in effect; derives everything derivable | Depth-first; explores only relevant rules |
| Efficiency | May derive many irrelevant facts; slower when only one query matters | Far fewer rules touched; efficient for a specific query |
| Good for | Monitoring, planning, control, design: where new data arrives continuously | Diagnosis, classification, debugging: where you test a hypothesis |
| Example systems | CLIPS, Rete-based production systems, DENDRAL | Prolog, MYCIN |
| Example | "It is raining" ⟹ derive "ground wet" ⟹ derive "match cancelled" | "Is the match cancelled?" ⟹ need "ground wet" ⟹ need "raining" ⟹ check fact |
Uncertain Knowledge and Reasoning
Probability, Bayes' rule, belief networks, knowledge engineering for uncertainty, fuzzy logic.
Why uncertainty exists, and why logic is not enough
A logical agent must believe a sentence, disbelieve it, or have no opinion. The real world does not cooperate. Consider the medical rule ∀p Toothache(p) → Cavity(p). It is wrong: toothache can be caused by gum disease, an abscess or many other things. Repairing it into Toothache(p) → Cavity(p) ∨ GumProblem(p) ∨ Abscess(p) ∨ … requires an almost unlimited list, which is the qualification problem.
Sources of uncertainty: partial observability (sensors see only part of the world), noisy or faulty sensors, non-deterministic action outcomes, incomplete or contradictory knowledge, theoretical ignorance (no complete theory of the domain exists), practical ignorance (the theory exists but the data is not available for this patient), and vague or imprecise linguistic terms ("tall", "hot").
Approaches to handling uncertainty: name all five
- Probability theory (Bayesian): degrees of belief in [0, 1], updated by Bayes' rule. The dominant approach; combined with utility it gives decision theory.
- Fuzzy logic: degrees of truth for vague predicates, not degrees of belief.
- Certainty factors: the ad-hoc [−1, 1] confidence scores used by MYCIN.
- Dempster-Shafer theory: belief functions over sets of hypotheses; distinguishes "unknown" from "equally likely".
- Non-monotonic / default reasoning: conclusions can be retracted when new facts arrive (birds fly, but Tweety the penguin does not).
Basic probability
Bayes' rule: derive it, then use it
- Name the events and write the given probabilities as symbols: "Let C = has cancer, + = positive test. Given P(C) = 0.01, P(+|C) = 0.90, P(+|¬C) = 0.08."
- State what is asked in symbols: "Required: P(C|+)."
- Write Bayes' rule in full with the expanded denominator.
- Substitute numbers: do not skip to the answer; the substitution line carries the marks.
- Interpret: "Only about 10% of women with a positive mammogram actually have cancer, because the disease is rare and the 8% false-positive rate applies to a much larger population. This is the base-rate fallacy."
That last interpretation sentence is what separates a 7 from a 10.
Bayesian belief networks
Definition: A Bayesian (belief) network is a directed acyclic graph in which each node is a random variable, each directed edge X → Y means "X is a direct cause of / directly influences Y", and each node carries a conditional probability table (CPT) giving P(node | its parents). It is a compact representation of the full joint distribution.
Burglary and Earthquake are root nodes with prior probabilities and are independent of each other. Both directly cause the Alarm, so Alarm has a CPT with 2² = 4 rows. John and Mary each hear only the alarm, so they are conditionally independent of Burglary and Earthquake given Alarm. John's 0.05 false-call rate models his confusing the telephone with the alarm; Mary's 0.70 detection rate models her missing the alarm when her music is loud.
Example computation: the probability that the alarm sounds, both call, and there is neither a burglary nor an earthquake:
Steps to construct a Bayesian network
- Identify the relevant random variables and their domains.
- Order the variables so that causes come before effects: a causal order gives the sparsest network.
- For each variable in order, choose the minimal set of already-placed variables that directly influence it; draw arrows from those parents.
- Write the CPT for each node, 2k rows for k boolean parents. Root nodes get priors.
- Check acyclicity, and check that the conditional independence assumptions the graph asserts are actually reasonable.
Inference in belief networks means computing P(query | evidence). Exact methods: inference by enumeration of the joint, and variable elimination (which reuses repeated sub-expressions). Because exact inference is NP-hard in general networks, approximate methods are used: direct sampling, rejection sampling, likelihood weighting and Markov chain Monte Carlo (Gibbs sampling).
Applications: medical diagnosis (Pathfinder), spam filtering, fault and network diagnosis, speech recognition, gene regulatory networks, risk analysis and insurance, image segmentation, troubleshooting wizards, information retrieval. Advantages: compact, encodes causal structure readably, handles missing data, combines expert knowledge with data, supports both diagnostic (effect → cause) and causal (cause → effect) reasoning. Limitations: exact inference is NP-hard; the network structure and CPTs are hard to elicit; it assumes a fixed, acyclic causal structure; poor at continuous variables without discretisation.
Knowledge engineering for uncertain reasoning
The process of building the probabilistic model: (1) decide what to talk about, (2) decide on the vocabulary of random variables, (3) encode general knowledge about dependences, the network topology, (4) encode a description of the specific problem instance as evidence, (5) pose queries and check the answers against expert intuition, (6) debug and refine the model. This mirrors ordinary knowledge engineering but with probabilities rather than hard rules.
Fuzzy logic
Definition: Fuzzy logic, introduced by Lotfi Zadeh in 1965, is a many-valued logic in which the truth value of a proposition is a real number in [0, 1] rather than just 0 or 1. It models vagueness: the fact that predicates like "tall", "hot" or "fast" have no sharp boundary, as opposed to probability, which models likelihood.
"There is a 0.7 probability that the bottle contains drinkable water" means it is either drinkable or not, and we are 70% sure. "The membership of this water in the fuzzy set drinkable is 0.7" means it is definitely somewhat drinkable, a matter of degree, not of chance.
A fuzzy set A over a universe X is defined by a membership function μA(x) → [0, 1]. Operations: union μA∪B = max(μA, μB); intersection μA∩B = min(μA, μB); complement μ¬A = 1 − μA. Common membership shapes: triangular, trapezoidal, Gaussian, sigmoid.
The fuzzy inference system: four blocks
- Fuzzification. Convert crisp inputs into degrees of membership in the linguistic sets (22°C → Cold 0.5, Warm 0.32).
- Knowledge base / rule base. IF-THEN rules written by an expert in linguistic terms: IF temperature is Hot AND humidity is High THEN fan speed is Fast.
- Inference engine. Evaluate each rule: take the min (AND) or max (OR) of the antecedent memberships to get the firing strength, clip or scale the consequent set accordingly, then aggregate all rule outputs by max. (Mamdani method; Sugeno uses a functional consequent.)
- Defuzzification. Convert the aggregated fuzzy output back to a crisp number. Methods: centroid / centre of gravity (most common), mean of maxima, weighted average, bisector.
Rules: R1 IF temp is Cold THEN fan is Slow. R2 IF temp is Warm THEN fan is Medium. R3 IF temp is Hot
THEN fan is Fast.
Input 22°C fuzzifies to Cold 0.5, Warm 0.32, Hot 0.
R1 fires at 0.5 clipping the Slow set; R2 fires at 0.32 clipping Medium; R3 does not fire.
Aggregate by max, then defuzzify by centroid: fan speed ≈ 47%.
A crisp controller would have jumped from Slow to Medium at a threshold; the fuzzy controller moves
smoothly, which is why fuzzy control is used in washing machines, rice cookers, camera autofocus,
anti-lock brakes and the Sendai subway.
Advantages: handles vague, linguistic and imprecise knowledge; rules are readable by domain experts; robust to noisy or missing inputs; no exact mathematical model of the plant is needed; smooth, continuous control; simple and cheap to implement in hardware. Limitations: membership functions and rules are chosen by hand with no formal method; not based on probability so it cannot learn from data by itself; validation is difficult; performance degrades as the number of variables (and hence rules) grows.
↑ contentsLearning
Learning models, inductive learning, decision trees, neural networks, backpropagation, reinforcement learning, knowledge in learning.
What learning means for an agent
Definition (Mitchell): A computer program is said to learn from experience E with respect to a class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E. In agent terms: learning is any modification of the agent's components that improves its future performance, driven by feedback from the critic.
Three things determine the design of any learning element: which component is being improved, what prior knowledge the agent already has, and what feedback is available. The third determines the type of learning.
Supervised, unsupervised and reinforcement learning
This comparison has appeared in nine of the twelve papers. Learn the table, the three examples, and the diagram.
| Basis | Supervised learning | Unsupervised learning | Reinforcement learning |
|---|---|---|---|
| Feedback | Labelled data: every input comes with the correct output | No labels at all | Delayed scalar reward or punishment after actions |
| Goal | Learn a mapping f: X → Y that generalises to unseen inputs | Discover hidden structure, groups or associations in the data | Learn a policy π: state → action that maximises cumulative reward |
| Data | (x, y) pairs | x only | Sequence of (state, action, reward, next state) |
| Sub-types | Classification (discrete label), Regression (continuous value) | Clustering, association rule mining, dimensionality reduction | Model-free (Q-learning, SARSA), model-based, policy gradient |
| Algorithms | Decision tree, naïve Bayes, KNN, SVM, linear/logistic regression, neural networks, random forest | K-means, hierarchical clustering, DBSCAN, PCA, Apriori | Q-learning, Deep Q-Network, actor-critic, temporal difference |
| Example | Spam / not-spam email filter trained on labelled mail; predicting house price from area | Segmenting bank customers into groups; market-basket analysis "bread ⟹ butter" | A robot learning to walk; AlphaGo; a game agent scoring points |
| Drawback | Labelling is expensive; needs lots of labelled data | No ground truth, so results are hard to validate | Needs many trials; reward design is difficult; slow convergence |
Classification vs regression vs clustering vs association
| Task | Output | Example |
|---|---|---|
| Classification | A discrete class label | Is this tumour malignant or benign? Which digit is this image? |
| Regression | A continuous number | Predict tomorrow's temperature, or a flat's rent from its area. |
| Clustering | Groups discovered without labels | Group 10,000 news articles into topics with K-means. |
| Association | if-then co-occurrence rules with support and confidence | Customers who buy nappies also buy beer (Apriori on transactions). |
Classification vs clustering in one line: classification is supervised and assigns data to predefined classes learned from labelled examples; clustering is unsupervised and discovers the groups itself from similarity, with no labels and no predefined classes.
Inductive learning and learning from observations
Inductive learning is the task of finding a hypothesis h that approximates an unknown target function f, given a training set of examples (x, f(x)). It is induction: reasoning from specific examples to a general rule, so the conclusion is never guaranteed, only supported.
- Hypothesis space H: the set of functions the learner is allowed to consider. If the true f ∈ H the problem is realisable.
- Ockham's razor: prefer the simplest hypothesis consistent with the data.
- Overfitting: the model memorises noise in the training data; training error is tiny but test error is large. Cured by more data, pruning, regularisation, early stopping, dropout, simpler models.
- Underfitting: the model is too simple to capture the pattern; both errors are high. Cured by a richer model or better features.
- Validation: split into training / validation / test sets (typically 60/20/20), or use k-fold cross-validation: divide into k folds, train on k−1 and test on the remaining one, rotate, and average. Model selection uses the validation set; the test set is touched only once, at the end.
Decision trees
Definition: A decision tree is a supervised learning model shaped like a flowchart, in which each internal node tests one attribute, each branch is an outcome of that test, and each leaf gives a class label (classification tree) or a value (regression tree). Classification is done by walking from the root to a leaf following the tests, which is exactly how the tree performs inference.
ID3 and information gain: the formulas you must write
ID3 (Iterative Dichotomiser 3, Quinlan 1986) builds the tree top-down, greedily choosing at each node the attribute with the highest information gain, and recursing on each branch until the examples at a node are pure or no attributes remain.
Handy logs for the exam: log₂(1/2) = −1, log₂(1/3) = −1.585, log₂(2/3) = −0.585, log₂(1/4) = −2, log₂(3/4) = −0.415, log₂(1/5) = −2.322, log₂(2/5) = −1.322, log₂(3/5) = −0.737, log₂(3/8) = −1.415, log₂(5/8) = −0.678.
- Compute the entropy H(S) of the current example set with respect to the target attribute.
- For every remaining attribute A, split S by A and compute the weighted entropy of the subsets.
- Compute Gain(S, A) = H(S) − weighted entropy, for each A.
- Choose the attribute with the maximum gain as the decision node.
- Recurse on each branch with the remaining attributes and the corresponding subset.
- Stop when a subset is pure (make a leaf with that class), or attributes run out (leaf = majority class), or the subset is empty (leaf = majority class of the parent).
Types of decision tree: classification trees (discrete label) and regression trees (continuous value); by algorithm: ID3 (information gain, categorical only), C4.5 (gain ratio, handles continuous attributes and missing values, prunes), CART (Gini index, binary splits, does both classification and regression), CHAID (chi-square).
Significance: easy to understand and to explain to a non-expert (white-box model); needs little data preparation: no normalisation or scaling; handles both numeric and categorical data; fast at prediction time; performs implicit feature selection; converts directly into rules. Limitations: unstable: a small change in data can change the whole tree (high variance); greedy so it does not guarantee the globally optimal tree; strongly prone to overfitting without pruning; biased towards attributes with many values; poor at capturing smooth or linear relations; can be biased if classes are imbalanced.
Pruning combats overfitting: pre-pruning (stop early on a depth, minimum-samples or significance criterion) and post-pruning (grow the full tree, then remove subtrees that do not improve validation accuracy, reduced-error pruning, cost-complexity pruning).
Decision tree vs random forest
| Basis | Decision tree | Random forest |
|---|---|---|
| Structure | One tree | An ensemble of many trees; prediction by majority vote (classification) or average (regression) |
| Training data | The whole dataset | Bagging: each tree is trained on a bootstrap sample, and at each split only a random subset of features is considered |
| Overfitting | High risk | Much lower: averaging independent trees cancels their individual variance |
| Accuracy | Lower, unstable | Higher and far more stable |
| Interpretability | Fully interpretable: you can read the rules | Black box; only feature-importance scores are readable |
| Speed / cost | Fast to train and predict | Slower, memory-heavy, but parallelisable |
| Use when | You must explain the decision (loan rejection, medical triage) | You need accuracy on noisy, high-dimensional data |
Example to close with: for credit approval a single tree gives the bank a reason it can quote to the customer; a random forest of 500 trees gives a few percent more accuracy but cannot be explained in a rejection letter.
Evaluating a classifier
Validation approaches: hold-out split, k-fold cross-validation, leave-one-out, stratified sampling (preserves class proportions), and bootstrap. The results go into a confusion matrix.
"Accuracy alone is misleading on imbalanced data, a model that calls every patient benign scores 95% accuracy on a dataset with 5% cancer. In cancer screening a false negative is far more costly than a false positive, so recall is the metric to optimise, even at the cost of precision."
Neural networks
An artificial neural network is a computing system of simple interconnected processing units (neurons) modelled on the brain, in which knowledge is stored in the weights of the connections and learned by adjusting those weights from data.
The perceptron
Definition: A perceptron (Rosenblatt, 1958) is the simplest neural unit, a single neuron that computes a weighted sum of its inputs plus a bias and passes it through an activation function to produce an output.
Activation functions
| Function | Formula | Range / use |
|---|---|---|
| Step (threshold) | 1 if x ≥ θ else 0 | {0,1}. Original perceptron; not differentiable so it cannot be used with backpropagation. |
| Linear / identity | f(x) = x | (−∞,∞). Output layer of a regression network. Stacking linear layers collapses to one linear layer. |
| Sigmoid (logistic) | 1 / (1 + e−x) | (0,1). Smooth, differentiable: f′ = f(1−f). Used for binary output; suffers from vanishing gradients. |
| Tanh | (ex−e−x)/(ex+e−x) | (−1,1). Zero-centred, so it converges faster than sigmoid. |
| ReLU | max(0, x) | [0,∞). Default in deep networks: cheap and avoids vanishing gradients; can "die" for negative inputs (fixed by Leaky ReLU). |
| Softmax | exᵢ / Σ exⱼ | Probabilities summing to 1. Output layer for multi-class classification. |
It introduces non-linearity. Without it, a network of any depth is just a composition of linear maps, which is itself linear, so the whole network collapses to a single-layer perceptron and can never learn a non-linear boundary such as XOR. It also bounds the output to a usable range and, being differentiable, makes gradient-based learning possible.
Why a perceptron is a linear classifier, and why XOR breaks it
The perceptron fires when w₁x₁ + w₂x₂ + b ≥ 0. That equation defines a straight line (a hyperplane in higher dimensions) that divides the input space into two half-planes. So a perceptron can only represent linearly separable functions. AND, OR and NOT are linearly separable and one perceptron learns each of them. XOR is not: its true points (0,1) and (1,0) lie on one diagonal and its false points (0,0) and (1,1) on the other, so no single straight line separates them.
The fix: a multilayer perceptron. XOR = (x₁ OR x₂) AND NOT(x₁ AND x₂), so two hidden neurons, one computing OR, one computing NAND, feeding an AND output neuron solve it. One concrete set of weights: hidden h₁ = step(x₁ + x₂ − 0.5) (OR), h₂ = step(−x₁ − x₂ + 1.5) (NAND), output y = step(h₁ + h₂ − 1.5) (AND). The hidden layer transforms the input space into one in which the classes are linearly separable: that is the whole purpose of hidden layers.
Multilayer perceptron (MLP)
Definition: A feed-forward network with an input layer, one or more hidden layers of non-linear units, and an output layer, fully connected between adjacent layers, with information flowing in one direction and no cycles. With one sufficiently large hidden layer and a non-linear activation, an MLP is a universal approximator: it can approximate any continuous function to arbitrary accuracy.
Backpropagation
Definition: Backpropagation is the supervised learning algorithm for multilayer networks. It repeatedly (i) propagates an input forward to produce an output, (ii) computes the error against the target, and (iii) propagates that error backwards, using the chain rule of calculus to find the gradient of the error with respect to every weight, then updates each weight by gradient descent.
- Initialise all weights and biases to small random values.
- Forward pass: for each layer compute net = Σwx + b and output = f(net), up to the output layer.
- Compute the error E = ½Σ(t − o)² at the output.
- Compute δ for each output unit.
- Backward pass: propagate δ to each hidden unit using the weights above it.
- Update every weight by w ← w + η·δ·input.
- Repeat for all training patterns (an epoch) until the error falls below a threshold or the epoch limit is reached.
Learning and validation in backpropagation: the dataset is split into training and validation sets. Weights are updated only on the training set; after each epoch the error on the validation set is measured. Training error falls monotonically, but validation error falls and then starts to rise, that turning point is the onset of overfitting, and training is stopped there (early stopping). Cross-validation, regularisation, dropout and momentum are the other standard controls.
When do we need backpropagation? Whenever a network has hidden layers: the perceptron rule only works when the target output of a unit is known, and for hidden units it is not. Backpropagation supplies that missing error signal by the chain rule. Limitations: slow convergence, local minima, vanishing gradients in deep sigmoid networks, sensitivity to the learning rate and initial weights, and the need for large labelled datasets.
Hebbian learning
The oldest learning rule (Donald Hebb, 1949), often summarised as "neurons that fire together, wire together": if two connected neurons are active simultaneously, the strength of the connection between them increases. It is unsupervised: no target output is used.
Example. Train a Hebbian unit on the AND function in bipolar form (inputs and targets in {−1, +1}), starting from w₁ = w₂ = b = 0 with η = 1:
Hebbian learning explains associative memory and conditioning (the bell and the food in Pavlov's experiment) and underlies Hopfield networks, but unmodified it grows weights without bound, so practical versions normalise (Oja's rule).
Reinforcement learning in a little more depth
The agent occupies a state s, takes an action a, receives a scalar reward r and moves to s′. It learns a policy π that maximises expected discounted return. The central trade-off is exploration versus exploitation: trying new actions to gather information versus taking the best-known action now (handled by ε-greedy or softmax action selection).
Example: a robot in a grid gets +10 for reaching the goal, −10 for a pit and −1 per step; after many episodes the Q-table encodes the shortest safe route. Applications: game playing (AlphaGo, Atari), robot control, self-driving, dynamic pricing, recommendation, traffic-signal control.
Other learning methods worth two marks each
| Method | One-line definition and use |
|---|---|
| Linear regression | Fits y = mx + c by minimising squared error; predicts a continuous value such as house price. Output range (−∞, ∞). |
| Logistic regression | Applies the sigmoid to a linear combination to output a probability in (0,1) and hence a class. Used for spam detection, disease prediction, credit default. Trained with cross-entropy loss, not squared error. |
| Naïve Bayes | Applies Bayes' rule assuming all features are conditionally independent given the class. Fast, works well for text and spam. |
| K-nearest neighbours | Lazy learner: classify a point by the majority vote of its k closest training points. No training phase; slow at prediction. |
| K-means clustering | Unsupervised: pick k centroids, assign each point to the nearest, recompute centroids, repeat until stable. |
| Support Vector Machine | Finds the hyperplane that maximises the margin between two classes; the closest points are the support vectors. The kernel trick (polynomial, RBF) maps data into a higher-dimensional space where it becomes linearly separable. Strong for high-dimensional data such as text and images; slow on very large datasets. |
| Deep learning | Neural networks with many hidden layers that learn a hierarchy of features automatically, removing the need for hand-crafted feature engineering. CNNs for images, RNN/LSTM for sequences, Transformers for language. Needs large data and GPUs, and is a black box. |
| Ensemble methods | Bagging (random forest), boosting (AdaBoost, XGBoost) and stacking combine weak learners into a strong one. |
Knowledge in learning
Pure inductive learning starts from a blank slate; in practice an agent already knows a great deal, and prior knowledge makes learning far faster and from far fewer examples. Explanation-based learning (EBL) generalises from a single example by explaining why it worked using background knowledge. Relevance-based learning (RBL) uses knowledge about which attributes matter to cut the hypothesis space. Knowledge-based inductive learning (KBIL) and inductive logic programming (ILP) find hypotheses that, together with background knowledge, explain the observations, allowing the learner to invent new predicates.
↑ contentsExpert Systems and Natural Language Processing
Architecture, components and development of expert systems; the stages of NLP, parse trees and ambiguity.
Expert systems
Definition: An expert system is a computer program that uses a knowledge base of human expertise and an inference engine to solve problems within a narrow domain at a level comparable to a human expert, and can explain its reasoning.
Characteristics: high performance in a narrow domain; use of heuristic and judgemental knowledge; separation of knowledge from the inference mechanism; ability to explain why a question is asked and how a conclusion was reached; ability to reason under uncertainty; symbolic rather than numerical reasoning.
Components: explain each with one line and an example
- Knowledge base. The domain knowledge: facts and heuristic IF-THEN production rules acquired from human experts. IF the patient has a fever AND a stiff neck THEN suspect meningitis (CF 0.7). This is what makes the system expert.
- Inference engine. The reasoning mechanism that matches rules against the working memory, resolves conflicts when several rules fire (by priority, specificity or recency), and applies forward or backward chaining to reach a conclusion.
- Working memory (database of facts). Holds the facts of the current case: this patient's symptoms and test results, and the intermediate conclusions derived so far.
- User interface. Lets a non-expert consult the system in near-natural language, asking questions and displaying conclusions.
- Explanation facility. Answers "why are you asking this?" and "how did you reach that diagnosis?" by replaying the chain of fired rules. This is essential for user trust and for medical or legal accountability.
- Knowledge acquisition subsystem. The tools by which the knowledge engineer adds, edits and validates rules obtained from the domain expert, the main bottleneck in building the system.
People involved: the domain expert (supplies knowledge), the knowledge engineer (elicits and encodes it), the end user (consults the system), and the system builder / tool vendor. Classic systems to name: DENDRAL (chemical structures, the first), MYCIN (bacterial infections, certainty factors, Stanford), XCON/R1 (configuring DEC computers), PROSPECTOR (mineral exploration), CADUCEUS (internal medicine).
Stages in developing an expert system
- Problem identification and feasibility. Is the domain narrow, is a human expert available, is the knowledge heuristic rather than algorithmic, is the payoff worth it?
- Knowledge acquisition. Interview the expert, observe cases, study manuals; the hardest and slowest stage.
- Knowledge representation. Choose rules, frames or logic and formalise the knowledge into that structure.
- Design and tool selection. Select a shell (CLIPS, JESS, Prolog) or build from scratch; design the inference strategy and the user interface.
- Prototype development. Build a small system covering a core subset of cases.
- Testing, verification and validation. Run historical cases; compare conclusions against the expert's; measure accuracy, sensitivity and specificity.
- Deployment and user training.
- Maintenance and refinement. Update rules as domain knowledge changes; the knowledge base is never finished.
(i) How components contribute to medical diagnosis: knowledge base holds diagnostic rules from senior doctors; working memory holds this patient's symptoms, history and test results; the inference engine chains rules (backward chaining to test a suspected disease, forward chaining as new test results arrive); the explanation facility justifies the diagnosis so the doctor can accept or override it; knowledge acquisition lets the hospital add new protocols.
(ii) How to evaluate accuracy and reliability: run the system on a large set of retrospective cases with confirmed diagnoses; build a confusion matrix and report accuracy, sensitivity (recall) and specificity; compare against a panel of doctors on the same blinded cases; measure inter-rater agreement (Cohen's kappa); run prospective trials; monitor error and near-miss rates after deployment; check that performance holds across age, sex and disease-prevalence subgroups.
(iii) Ethical and legal concerns: who is liable when the system is wrong, the hospital, the vendor or the doctor; patient data privacy and consent; algorithmic bias against groups under-represented in the training data; the need for explainability and informed consent; automation bias, where doctors defer to the machine; the requirement to keep a human in the loop for final decisions; regulatory approval as a medical device; and clear rules on data ownership and audit trails.
Advantages: preserves scarce expertise and makes it available anywhere, any time; consistent, unbiased and tireless; fast; useful for training juniors; explains its reasoning; can combine the knowledge of several experts. Disadvantages: no common sense or creativity; brittle at the edges of its domain, it fails badly rather than gracefully; expensive and slow to build because of the knowledge-acquisition bottleneck; cannot learn from experience by itself; needs constant maintenance; cannot handle novel situations its rules do not cover. Applications: medical diagnosis, geological prospecting, financial credit and fraud assessment, equipment fault diagnosis, process control, agricultural advice, legal reasoning, configuration and scheduling, helpdesks.
Natural Language Processing
Definition: NLP is the branch of AI concerned with enabling computers to read, understand, interpret and generate human language. It has two halves: natural language understanding (text or speech → meaning) and natural language generation (meaning → text or speech).
Why NLP is difficult: the problems of natural language understanding
- Ambiguity at every level (below): the central problem.
- Context dependence: the meaning of "it" or "there" depends on earlier sentences and on the physical situation.
- Need for world knowledge and common sense: "The trophy did not fit in the suitcase because it was too big", resolving "it" requires knowing about sizes and containers.
- Idioms, sarcasm, metaphor and humour that cannot be composed from word meanings.
- Ellipsis and anaphora: omitted words and pronoun references.
- Language variation: dialect, code-mixing (Nepali-English), spelling errors, new coinages, informal social-media text.
- Speech-specific problems: homophones, no clear word boundaries in continuous speech, accents, background noise.
- Resource scarcity for low-resource languages such as Nepali, few annotated corpora, no reliable parsers.
The stages of NLP
- Lexical / morphological analysis. Break the text into tokens, identify word structure, roots, prefixes, suffixes, and assign parts of speech. "unhappiness" → un + happy + ness.
- Syntactic analysis (parsing). Check the sentence against the grammar and build a parse tree showing how words group into phrases. "Colourless green ideas sleep furiously" is syntactically valid but semantically nonsense; "the boy the apple ate" is rejected here.
- Semantic analysis. Attach meaning to the structure, checking that it is meaningful in the domain. "Hot ice-cream" is rejected at this stage.
- Discourse integration. Interpret each sentence in the light of those around it, resolving pronouns and references. "Ram went home. He was tired."
- Pragmatic analysis. Interpret intended meaning in the real-world context. "Can you pass the salt?" is a request, not a question about ability.
How a parse tree helps
A parse tree makes the grammatical structure of a sentence explicit, showing which words modify which. This lets the system (i) verify grammaticality, (ii) identify subject, verb and object for meaning extraction, (iii) resolve structural ambiguity by generating one tree per reading, and (iv) feed a systematic, compositional semantic interpretation.
Ambiguity in NLP: one example each, and do not mix them up
| Type | What is ambiguous | Example |
|---|---|---|
| Lexical / morphological | A single word has more than one meaning or part of speech, or more than one morphological decomposition | "I saw a bat": animal or cricket bat? "Book the ticket": verb or noun? "unlockable": able to be unlocked, or unable to be locked? |
| Syntactic (structural) | The sentence has more than one valid parse tree | "I saw the man with a telescope", did I use the telescope, or does he have it? "Old men and women": are the women old? |
| Semantic | The structure is clear but the meaning still has multiple readings | "The car hit the pole while it was moving", which was moving? "Every man loves a woman": the same woman, or one each? |
| Pragmatic / discourse | The literal meaning is clear but the intended meaning or the reference depends on context | "Can you open the window?": request, not a question. "Ram told Shyam that he had passed": who passed? |
Applications of NLP: machine translation, chatbots and virtual assistants, sentiment analysis, spam filtering, speech recognition and synthesis, information retrieval and search, text summarisation, question answering, optical character recognition, grammar checking.
↑ contentsA* and search problems, solved
Every search numerical set by PU between 2018 and 2024, with the OPEN/CLOSED table the examiner wants to see.
1. Redraw the graph with edge costs. 2. Write the h-table. 3. Write f(n) = g(n) + h(n). 4. Make a step table with columns Step | Node expanded | OPEN (with f values) | CLOSED. 5. Trace parents back for the path. 6. Box the path and the cost. Never just state the answer.
Worked solution
Step 1: evaluation function. f(n) = g(n) + h(n), where g is the cost accumulated from S and h is the given straight-line estimate.
| Step | Expanded | Successors generated (g, h, f) | OPEN after step, ordered by f | CLOSED |
|---|---|---|---|---|
| 0 | : | S: g=0, h=15, f=15 | S(15) | : |
| 1 | S (f=15) | 1: 3+14 = 17 · 4: 4+12 = 16 | 4(16), 1(17) | S |
| 2 | 4 (f=16) | 5: (4+2)+10 = 16 | 5(16), 1(17) | S, 4 |
| 3 | 5 (f=16) | 6: (6+4)+10 = 20 · 2: (6+5)+10 = 21 · 1: (6+5)+14 = 25 → worse than 17, discard | 1(17), 6(20), 2(21) | S, 4, 5 |
| 4 | 1 (f=17) | 2: (3+1)+10 = 14 → better than the existing 21, so update g(2)=4 and set parent = 1 · 5 already closed with smaller g, discard | 2(14), 6(20) | S, 4, 5, 1 |
| 5 | 2 (f=14) | 3: (4+4)+8 = 16 · 5 discarded (closed, larger g) | 3(16), 6(20) | S, 4, 5, 1, 2 |
| 6 | 3 (f=16) | dead end: 3 has no successors except 2 | 6(20) | S, 4, 5, 1, 2, 3 |
| 7 | 6 (f=20) | 7: (10+3)+0 = 13 | 7(13) | S, 4, 5, 1, 2, 3, 6 |
| 8 | 7: goal test succeeds, stop | : | : | goal reached |
Step 2: trace the parents back. 7 ← 6 ← 5 ← 4 ← S.
Path: S → 4 → 5 → 6 → 7. Solution cost = 4 + 2 + 4 + 3 = 13.
Verification against the only alternative route: S → 1 → 2 → 5 → 6 → 7 = 3 + 1 + 5 + 4 + 3 = 16 > 13, so 13 is optimal.
Note that h(S) = 15 but the true cheapest cost from S to the goal is 13. Since h(S) > h*(S), this heuristic overestimates and is therefore not admissible. You can also see the inconsistency in the table: f falls from 16 at node 5 to 14 at node 2, whereas a consistent heuristic makes f non-decreasing along any path. A* still returned the optimal path here, but with an inadmissible heuristic that is luck, not a guarantee. Writing this shows the examiner you understand admissibility rather than just cranking the algorithm.
Worked solution
| Step | Expanded | Successors (g + h = f) | OPEN | CLOSED |
|---|---|---|---|---|
| 0 | : | S: 0 + 5 = 5 | S(5) | : |
| 1 | S | A: 1 + 3 = 4 · G: 12 + 0 = 12 | A(4), G(12) | S |
| 2 | A (f=4) | B: (1+3) + 6 = 10 · C: (1+1) + 2 = 4 | C(4), B(10), G(12) | S, A |
| 3 | C (f=4) | D: (2+1) + 3 = 6 · G: (2+2) + 0 = 4 → better than 12, update parent to C | G(4), D(6), B(10) | S, A, C |
| 4 | G (f=4) | goal test succeeds | : | done |
Path: S → A → C → G, cost = 1 + 1 + 2 = 4. The direct edge S→G costs 12, so its f value stays worst throughout and it is never expanded; D is generated but never expanded either.
Admissibility check (worth a mark): true remaining costs are h*(S) = 4, h*(A) = 3, h*(C) = 2, h*(D) = 3, h*(B) = 6, h*(G) = 0. Every given h equals h* except h(S) = 5, which exceeds h*(S) = 4. So the heuristic is admissible at every node but the start; since the start node is expanded first regardless, the optimal path is still returned.
Method (the edge labels are illegible in the scan, apply this to your printed copy)
The heuristic table is the useful part, and it tells you the shape of the answer before you start:
- h decreases along any sensible route towards M, so the promising corridor is A → C → F → K → M or A → C → I → M: the nodes with the smallest h (K = 32, J = 60, I = 100, L = 102, H = 111) are the ones near the goal.
- Build the same five-column step table as above. Start with A: f = 0 + 223 = 223.
- At each step add g (sum of the printed edge costs from A) to h from the table.
- Because h values here are large relative to typical edge costs, A* will behave almost greedily and drive straight down the corridor of falling h. Expect roughly four to six expansions.
- Report the path, then the cost as an explicit sum, then state whether the heuristic is admissible by comparing h(A) = 223 with the actual path cost you obtained.
State your assumption in the answer, "taking the A-B edge cost as 36 as printed", and continue. Examiners award method marks; a clearly stated assumption never costs you.
Worked solution
Depths: Start = 0, A = 1, B and C = 2, D = 3, E F G = 4, H I K = 5. So the goal depth d = 5, maximum depth m = 5, and the maximum branching factor b = 3 (at D).
BFS (FIFO queue, level by level):
DFS (LIFO stack, leftmost branch to the bottom first):
| BFS | DFS | |
|---|---|---|
| Time complexity | O(bd) = O(35) | O(bm) = O(35) |
| Space complexity | O(bd): the whole frontier is stored | O(b·m) = O(15): only the current path plus siblings |
| Complete? | Yes | Not in infinite/cyclic spaces (yes on this finite tree) |
| Optimal? | Yes for equal step costs: finds the shallowest goal | No: returns the first goal found, at any depth |
Conclusion to write: on this tree DFS happens to find K after fewer expansions and uses far less memory, but that is luck, the goal is on the leftmost deep branch. BFS is the safe choice when the goal is shallow or when optimality matters; DFS is the choice when memory is the binding constraint.
Crypt-arithmetic: all seven PU problems
One of these appears in every paper. Learn the reasoning pattern, not the answers, but knowing the answers lets you check your work in 30 seconds.
"This is a Constraint Satisfaction Problem. Variables = the distinct letters; Domain = {0,1,…,9} for each; Constraints = (i) Alldiff on the letters, (ii) no leading letter is zero, (iii) one column equation per column of the form digit + digit + carry-in = result digit + 10 × carry-out, with every carry in {0,1}." Then solve by constraint propagation and backtracking.
Worked solution
1. Fix A and P. The largest possible sum is 999 + 9999 = 10998, and the smallest 5-digit result is 10000. So APPLE lies between 10000 and 10998, which forces A = 1 and P = 0.
2. Rewrite algebraically with A = 1, P = 0:
3. Bound T. The left side is at most 1002T + 900 + 900 + 20. For it to reach 10000 we need 1002T ≥ 8180, so T ≥ 8.17, i.e. T ∈ {8, 9}. If T = 8: 100H + 99E = 1964 + 10L, but the maximum of 100H + 99E is 900 + 891 = 1791 < 1964. So T = 9.
4. Substitute T = 9: 9018 + 100H + 100E + 20 = 10000 + 10L + E, giving
5. Propagate. Test H from 8 downwards. The right-hand side lies between 962 and 1052, so 100H + 99E must fall in that band:
| H | Required 99E | E | Resulting L | Valid? |
|---|---|---|---|---|
| 8 | 162 + 10L | E = 2 → 198 | 10L = 36 | No, L not an integer |
| 7 | 262 + 10L | E = 3 → 297 | 10L = 35 | No |
| 6 | 362 + 10L | E = 4 → 396 | 10L = 34 | No |
| 5 | 462 + 10L | E = 5 → 495 | 10L = 33 | No |
| 4 | 562 + 10L | E = 6 → 594 | 10L = 32 | No |
| 3 | 662 + 10L | E = 7 → 693 | 10L = 31 | No |
| 2 | 762 + 10L | E = 8 → 792 | 10L = 30 → L = 3 | Yes |
A = 1, P = 0, T = 9, H = 2, E = 8, L = 3
Worked solution
Note first that ODD + ODD = 2 × ODD, so EVEN is even, the puzzle is self-describing.
1. A 3-digit number doubled is at most 1998, and EVEN has 4 digits, so E = 1.
2. Units: 2D = N + 10c₁. Tens: 2D + c₁ = E + 10c₂ = 1 + 10c₂. The left side must end in 1, which is odd, so c₁ must be odd, hence c₁ = 1 and 2D ≥ 10. Then 2D + 1 ≡ 1 (mod 10) ⟹ 2D ≡ 0 (mod 10) ⟹ D = 0 or 5; since 2D ≥ 10, D = 5.
3. With D = 5: units gives N = 10 − 10 = 0; tens gives 2(5) + 1 = 11, so the digit is 1 = E ✓ and c₂ = 1.
4. Hundreds: 2O + c₂ = V + 10c₃, and thousands: c₃ = E = 1. So 2O + 1 = V + 10, i.e. V = 2O − 9, requiring O ≥ 5.
| O | V = 2O − 9 | Check against E=1, D=5, N=0 |
|---|---|---|
| 5 | 1 | clashes with E = 1 ✗ |
| 6 | 3 | all distinct ✓ |
| 7 | 5 | clashes with D = 5 ✗ |
| 8 | 7 | all distinct ✓ |
| 9 | 9 | clashes with O ✗ |
Stating that the constraints do not force a unique solution, and giving both, scores higher than giving one and stopping.
Worked solution
1. Two 2-digit numbers sum to at most 198, and OUT has 3 digits, so the leading digit O = 1.
2. Units column: O + O = T + 10c₁ ⟹ 1 + 1 = 2, which is less than 10, so c₁ = 0 and T = 2.
3. Tens column: G + T + c₁ = U + 10c₂ ⟹ G + 2 = U + 10c₂. Since the hundreds digit of the answer is O = 1, we need c₂ = 1, so G + 2 = U + 10, i.e. G = U + 8.
4. U = 0 → G = 8 ✓. U = 1 → G = 9, but U would clash with O = 1 ✗. So U = 0, G = 8.
Worked solution
1. Two 4-digit numbers sum to at most 19998, so the leading digit A = 1.
2. Write the five column equations (c₁…c₄ are the carries out of each column, right to left):
3. Hundreds column: 2I + c₂ = 1 + 10c₃. The left side is even + c₂ and the right is odd, so c₂ = 1. Then 2I + 1 = 1 + 10c₃ ⟹ 2I = 10c₃. If c₃ = 1 then I = 5; if c₃ = 0 then I = 0.
4. Case c₃ = 1, I = 5: tens gives 2N + c₁ = 5 + 10 = 15, so c₁ = 1 and N = 7. Units then gives 1 + G = 7 + 10 = 17 ⟹ G = 16, impossible. Case rejected.
5. Case c₃ = 0, I = 0: tens gives 2N + c₁ = 0 + 10 = 10, so c₁ = 0 and N = 5. Units: 1 + G = 5 + 0 ⟹ G = 4. Thousands: N + S + c₃ = G + 10c₄ ⟹ 5 + S + 0 = 4 + 10 ⟹ S = 9.
Worked solution
The sum is 2 × LOGIC, so every column is a doubling with carry.
1. A 5-digit number doubled has at most 6 digits, so P = 1 and a₅ = 1.
2. The thousands column is the key: 2O + a₃ = O + 10a₄ ⟹ O + a₃ = 10a₄. Either a₄ = 1 with O = 10 − a₃ (so a₃ = 1, O = 9), or a₄ = 0 with O = 0 and a₃ = 0.
3. Branch A (O = 9, a₃ = 1, a₄ = 1): the tens column gives 2I + a₁ = 9 + 10a₂; a₂ = 0 forces I = 4, a₁ = 1; then units 2C = G + 10 and hundreds 2G = L + 10 give G = 2C − 10 and L = 4C − 30, so L ≥ 5 needs C ≥ 8.75, i.e. C = 9: but O = 9 already. Contradiction, branch rejected.
4. Branch B (O = 0, a₃ = 0, a₄ = 0):
Worked solution
1. Both numbers have 5 digits and so does the sum, so there is no carry out of the leftmost column: 2W + a₄ = R with R ≤ 9, hence W ≤ 4.
2. Try W = 1. Then R = 2 + a₄. Take a₄ = 0 so R = 2. The thousands column gives 2R + a₃ = I, i.e. I = 4 + a₃. Take a₃ = 1, so I = 5.
3. The hundreds column with a₃ = 1: 2O + a₂ = G + 10. Try a₂ = 0, O = 7 → G = 4. Check the units: 2G = 8 = T + 10a₁ ⟹ a₁ = 0, T = 8. Check the tens: 2N + a₁ = H + 10a₂ = H ⟹ H = 2N, and with N = 3 we get H = 6. All carries are consistent (a₁ = 0, a₂ = 0, a₃ = 1, a₄ = 0).
Say this in the exam: "This puzzle is under-constrained: eight letters, ten digits and only five column equations, so it has many valid solutions (21 in total). Any assignment satisfying all constraints is acceptable; the one above is verified by direct addition." Examiners accept a different valid answer, but only if you verified it.
Worked solution
1. The sum has one more digit than the addends, so G = 1 and c₄ = 1.
2. Add the units and tens equations to eliminate E and S:
3. With c₁ = 0 the units column gives E + 5 = S. The thousands column gives 2B + c₃ = A + 10, and the hundreds column 2A + 1 = M + 10c₃.
4. Try c₃ = 0: then M = 2A + 1 (so A ≤ 4) and 2B = A + 10. A = 4 → B = 7, M = 9. Remaining digits for E and S with S = E + 5 and E, S ∉ {1,4,5,7,9}: E = 3 → S = 8 ✓ (both free).
FOPL translation and resolution proofs
Eight knowledge bases, eight refutation proofs. The pattern never changes, so drill it once and it is 10 free marks.
Worked solution
Advantages of FOPL: see the Unit 3 list: expressiveness, conciseness, sound and complete inference, declarative and modular, basis of Prolog and expert systems.
- (a) must use → after ∀, never ∧.
- (c) the word only reverses the implication: selling implies the buyer is uninsured, not the other way round.
- (e) the order of quantifiers matters. ∀x ∃y loyalTo(x,y) = everyone is loyal to someone (possibly different people). ∃y ∀x loyalTo(x,y) = there is one person everyone is loyal to. Write the first, and say why.
Worked solution
The related 2024 knowledge base ("John likes all kinds of food …") in FOPL:
Worked solution
Step 1: symbols. S = the maid stole the jewellery; G = the butler was guilty; M = the maid milked the cows; C = the butler got his cream.
Step 2: convert to CNF.
Step 3: negate the goal and convert.
Step 4: resolve.
The empty clause is derived, so KB ∧ ¬goal is unsatisfiable. Hence KB ⊨ (G → C): if the butler was guilty then he got his cream. Draw the derivation as the tree in Fig 3.2.
Worked solution
Step 1: FOPL.
Step 2: CNF (clause form).
Step 3: resolution with unification.
Contradiction reached, so the negation of the goal is false and likes(Gita, Almond) is proved. Clauses C2 and C3 (mango, chapati) are never used, say so; recognising irrelevant premises is itself a mark.
Worked solution
Step 1: FOPL.
Step 2: CNF. Skolemise the ∃ in (1) with a new constant D (Ram's dog):
Step 3: resolution.
Sita killed the cat. The reasoning chain in words: Ram owns a dog, therefore Ram is an animal lover; animal lovers do not kill animals, and a cat is an animal, so Ram did not kill the cat; since one of the two did, it must be Sita.
Worked solution
Step 1: FOPL. Read "hard" as ¬easy. To be able to derive a liked course we use the reading "Shyam likes exactly the easy courses":
Step 2: CNF.
Step 3: resolution.
Shyam would like CS301. Add the note: "the sentence Shyam only likes easy courses strictly translates as likes(Shyam,x) → easy(x), which alone cannot derive a liked course; the intended knowledge base is the biconditional, so I use easy(x) → likes(Shyam,x) for the proof." That single sentence shows the examiner you understood the logic rather than copying a pattern.
Worked solution
Contradiction, therefore Krishna is angry is proved.
Worked solution
Step 1: convert each premise to CNF. Premise 1 needs care:
Step 2: negate the goal. ¬(¬C) = C.
Step 3: resolve.
The empty clause is derived, so ¬C is proved.
Worked solution
Proof by rules of inference (write the rule name beside every line):
Alternative by resolution (if the question says "using resolution"): clauses ¬P, Q, ¬R ∨ P, R ∨ S, ¬S ∨ T, plus the negated goal ¬T. Resolve ¬T with (¬S ∨ T) → ¬S; ¬S with (R ∨ S) → R; R with (¬R ∨ P) → P; P with ¬P → □.
Worked solution
Forward chaining (data-driven). Start from the facts and fire whatever matches:
Backward chaining (goal-driven). Start from the goal and work back:
"Forward chaining derived every intermediate fact whether or not it was needed; backward chaining touched only the rules relevant to D. On a small rule base the difference is invisible, but in a real flood-warning system with thousands of rules, backward chaining is far cheaper for answering a specific query, while forward chaining is the right choice when new sensor readings stream in continuously and all consequences must be updated."
CNF conversions, solved
PU has set the same two conversions in 2018, 2019, 2019 Spring and 2023. They are free marks.
Worked solution
Begin with the "why CNF" paragraph from Unit 3 and the eight steps, then:
Worked solution
Worked solution
CNF = (P ∨ R) ∧ (Q ∨ R) ∧ (¬P ∨ R) ∧ (¬S ∨ R).
This simplifies further. The antecedent contains both ¬P and P, so it is a tautology; an implication with a tautologous antecedent is equivalent to its consequent. Resolving (P ∨ R) with (¬P ∨ R) gives R directly, so the whole sentence reduces to R. Writing both the mechanical CNF and this simplification demonstrates real understanding.
Probability and Bayes numericals, solved
Five variants of the same question. Learn one method and all five fall.
Worked solution
P(cancer | positive mammogram) ≈ 0.102, about 10.2%.
Interpretation to write: out of 1000 women, 10 have cancer and 9 of them test positive; of the 990 without cancer, 79 still test positive. So 9 out of 88 positives are true, roughly 10%. Despite a 90% accurate test, a positive result means the woman probably does not have cancer, because the disease is rare. This is the base-rate fallacy, and it is why screening tests are followed by confirmatory biopsy.
Worked solution
P ≈ 0.0049, i.e. about 0.49%: roughly 1 in 203.
In a population of one million: 100 have the disease and 99 test positive; 999,900 are healthy and 19,998 of them test positive anyway. Almost every positive is a false alarm. Note also that the test's apparent accuracy (99% sensitivity, 98% specificity) is irrelevant next to the tiny prior, the lesson of the base-rate fallacy again.
Worked solution
P(spam | "refinance") ≈ 0.999, about 99.9%.
Contrast this with the cancer question and say so: here the prior is 50/50 and the likelihood ratio is 1000:1, so a single word is nearly conclusive. This is exactly how a naïve Bayes spam filter works: it multiplies such likelihood ratios over all the words in the email, assuming the words are conditionally independent given the class.
Worked solution
P(Blue | witness says Blue) ≈ 0.593, about 59.3%, so the cab was more likely Blue than Green, but far less certain than the witness's 85% reliability suggests, because Green cabs are more than twice as common. Note that the two figures given (85% correct, 25% false positive) do not sum to 100%, so they describe two separate conditional probabilities and must be used as given.
Worked solution
Reproduce Fig 4.1 exactly: the five nodes, the four arrows, and all four CPTs, then write the following four paragraphs beneath it.
- Variables. Five boolean variables: Burglary, Earthquake, Alarm, JohnCalls, MaryCalls.
- Topology and why. Burglary and Earthquake are root causes and are independent of one another, so they have no parents and carry prior probabilities. Both directly affect the Alarm, so both are parents of Alarm. John and Mary hear only the alarm itself, not the burglary, so Alarm is the sole parent of each, and JohnCalls and MaryCalls are conditionally independent given Alarm.
- CPTs. P(B) = 0.001, P(E) = 0.002; Alarm has four rows because it has two boolean parents; John's 0.05 false-alarm rate models the telephone confusion and Mary's 0.70 detection rate models her loud music.
- Use. The network answers diagnostic queries such as P(Burglary | JohnCalls ∧ MaryCalls) by summing the joint distribution P(b,e,a,j,m) = P(b)P(e)P(a|b,e)P(j|a)P(m|a) over the unobserved variables. It needs only 10 numbers instead of the 2⁵ − 1 = 31 of a full joint table.
ID3, evaluation metrics and the learning numericals
The two calculation-type learning questions PU has set, worked to the last decimal.
Worked solution
| # | Heavy | Smelly | Big | Growling | Bites |
|---|---|---|---|---|---|
| 1 | No | No | No | No | No |
| 2 | No | No | Yes | No | No |
| 3 | Yes | Yes | No | Yes | No |
| 4 | Yes | No | No | Yes | Yes |
| 5 | No | Yes | Yes | No | Yes |
| 6 | No | No | Yes | Yes | Yes |
| 7 | No | No | No | Yes | Yes |
| 8 | Yes | Yes | No | No | Yes |
(a) Entropy of the target. 5 examples Bite, 3 do not, out of 8.
(b) and (c) Information gain of each attribute. Split, compute each subset's entropy, take the weighted average, subtract from 0.9544.
| Attribute | Value = Yes | Value = No | Weighted entropy | Gain |
|---|---|---|---|---|
| Heavy | {3,4,8} → 2 bite, 1 not, H = 0.918 | {1,2,5,6,7} → 3 bite, 2 not, H = 0.971 | (3/8)(0.918) + (5/8)(0.971) = 0.951 | 0.003 |
| Smelly | {3,5,8} → 2 bite, 1 not, H = 0.918 | {1,2,4,6,7} → 3 bite, 2 not, H = 0.971 | 0.951 | 0.003 |
| Big | {2,5,6} → 2 bite, 1 not, H = 0.918 | {1,3,4,7,8} → 3 bite, 2 not, H = 0.971 | 0.951 | 0.003 |
| Growling | {3,4,6,7} → 3 bite, 1 not, H = 0.811 | {1,2,5,8} → 2 bite, 2 not, H = 1.000 | (4/8)(0.811) + (4/8)(1.000) = 0.906 | 0.049 |
ID3 chooses Growling as the root, because its information gain of 0.0488 bits is the largest (the other three tie at 0.0031).
(d) Build the rest of the tree.
Branch Growling = Yes, examples {3, 4, 6, 7} with H = 0.811:
Branch Growling = No, examples {1, 2, 5, 8} with H = 1.0:
Read the four leaves: the dog bites exactly when Growling and Smelly differ. The target function is Bites = Growling XOR Smelly. That is why every single attribute has a near-zero information gain at the root, an XOR target is invisible to a one-attribute-at-a-time greedy test, and ID3 only picks Growling because of a tiny accidental asymmetry in the sample. Write this: "the example demonstrates ID3's main weakness, the myopia of greedy attribute selection on interacting attributes."
Note: the Bites column for rows 1-3 is faint in the scanned paper; the reading above (No, No, No) is the one that makes the data consistent and produces the clean XOR structure.
Worked solution
Step 1: validation approaches (2 marks): hold-out split, k-fold cross-validation, stratified k-fold, leave-one-out, bootstrap; and the metrics derived from the confusion matrix.
Step 2: label the confusion matrix with Malignant as the positive class.
The model is right 85% of the time overall. Recall (90.9%) exceeds precision (83.3%), which is the right trade-off for a cancer screening tool: only 5 of 55 true malignancies are missed. Those 5 false negatives are still the most dangerous errors, since a missed melanoma goes untreated, whereas the 10 false positives merely trigger an unnecessary biopsy. If the system were to be deployed, the decision threshold should be lowered further to raise recall towards 100%, accepting lower precision, and the model should never be the final decision-maker, a dermatologist reviews every flagged case. Note also that accuracy alone would be a poor metric on a realistic dataset where malignant lesions are only 2-5% of cases.
What actually gets asked
Every question from fourteen PU and NCIT papers (2018 Spring to 2024 Fall), sorted by how often the topic appeared.
| Topic | Papers | Form the question takes |
|---|---|---|
| Crypt-arithmetic / CSP | 12 / 14 | "Solve stating all necessary conditions": EAT+THAT, ODD+ODD, GO+TO, NINA+SING, LOGIC+LOGIC, WRONG+WRONG, BASE+BALL |
| Search (A*, BFS/DFS, heuristics) | 12 / 14 | A* trace on a given graph; compare BFS/DFS/UCS/A*; define heuristics; informed vs uninformed |
| Neural networks & backpropagation | 11 / 14 | Define perceptron; XOR with a single neuron; MLP; explain backprop with example; activation functions |
| FOPL & resolution | 10 / 14 | Represent 5 sentences in FOPL; prove a goal by resolution on a small knowledge base |
| Agents / Turing test | 10 / 14 | Types of agent with diagrams; rational agent + task environments; Turing test, total and reverse; PEAS |
| Expert systems | 9 / 14 | Components + architecture diagram; development stages; advantages and applications |
| Supervised / unsupervised / RL | 8 / 14 | "Explain with examples"; classification vs clustering |
| Bayes numerical | 7 / 14 | Mammogram (×4), rare disease, spam filter, blue cab |
| Decision tree / ID3 | 7 / 14 | Entropy and information gain calculation; tree vs random forest; ID3 significance and limitations |
| Fuzzy logic | 7 / 14 | "How can uncertainty be represented using fuzzy logic? Explain with example" |
| Genetic algorithm | 6 / 14 | Steps with an example; use for optimisation |
| NLP | 5 / 14 | Steps of NLP; why it is difficult; ambiguity types; parse trees |
| Forward / backward chaining | 5 / 14 | Compare with examples; prove a goal both ways (flood system) |
| CNF conversion | 4 / 14 | Why CNF + steps + the same two formulas every time |
| Bayesian belief network | 4 / 14 | Burglar alarm network with CPTs; working principle; applications |
| Swarm intelligence (ACO / PSO) | 3 / 14 | Can search optimisation use swarm intelligence? describe the algorithm |
| Min-max & alpha-beta | 2 / 14 | Explain and give the advantage of pruning; chess case study |
| Semantic nets / frames | 2 / 14 | Discuss with examples; application in uncertain reasoning |
| Linear vs logistic regression | 2 / 14 | Compare with examples |
| Hill climbing · Hebbian learning · PEAS · SVM · deep learning | 1 each | Usually as a short note or one part of a two-part question |
The paper is not randomly sampled from the syllabus. It is a rotating set of about twenty question templates. Nine of the ten questions in your exam will come from the top twelve rows of this table. If you can do those twelve topics cold, you are looking at 85+, not 60.
The 24 questions to have ready
Write a full answer to each, to time. If you finish these you have covered roughly 95% of what can be asked.
Certain Do these first: one of each will be on the paper
- Solve a crypt-arithmetic problem stating all necessary conditions. Practise EAT+THAT and NINA+SING by hand until you can do either in 15 minutes. → solutions
- Trace A* on a given graph and report the solution cost. With the OPEN/CLOSED table and an admissibility comment. → solutions
- Represent a knowledge base in FOPL and prove a goal by resolution. → solutions
- A Bayes' rule numerical with interpretation. → solutions
- Components of an expert system + architecture diagram + development stages. → Unit 6
- Supervised vs unsupervised vs reinforcement learning with examples. → Unit 5
Very likely Second priority
- Explain backpropagation with an example; how learning and validation are done. → worked numerical
- What is a perceptron? Can a single perceptron design an XOR gate? Justify. → Fig 5.3
- Types of intelligent agent with diagrams and examples. → Unit 1
- How can uncertainty be represented using fuzzy logic? Explain with an example. → Unit 4
- Decision tree: types, significance, limitations; compare with random forest; ID3 with an example. → Unit 5, worked ID3
- Genetic algorithm: steps with an example; use for optimisation. → Unit 2
- Compare forward and backward chaining with examples. → Unit 3
- Why is CNF required? Steps, then convert P → ((Q ∧ ¬R) ↔ S). → solutions
- Compare BFS, DFS, UCS and A* with examples; informed vs uninformed search. → Unit 2 table
- Turing test, total Turing test, reverse Turing test / CAPTCHA, with a justified stand. → Unit 1
- Bayesian belief network: draw the burglar alarm network with CPTs; working principle; applications. → Fig 4.1
- Steps of NLP; why NLP is difficult; types of ambiguity with examples. → Unit 6
Worth an hour each The rest of the surface area
- Rational agent and the seven task-environment properties; PEAS for a part-picking robot and an automated car.
- Heuristics: definition, significance, types and challenges in informed search.
- Min-max search and the advantages of alpha-beta pruning.
- Hill climbing: algorithm, its three problems and their solutions.
- Semantic nets and frames with examples; propositional vs predicate logic.
- Swarm intelligence: ant colony optimisation and particle swarm optimisation algorithms; short notes on SVM, deep learning, machine learning, reinforcement learning.
A predicted paper for your exam
Built by taking the rotation pattern of the last seven years and picking what is due. Sit this under timed conditions one week before the exam.
Topics that appeared in 2023 and 2024 but not in consecutive years are due to rotate back; the six "certain" topics appear regardless. Two questions below (5 and 9) are variants that have not been set before but sit squarely inside the syllabus, those are the ones to think about rather than memorise.
Answer plan
Rational agent definition + the four things rationality depends on → the five agent types, one diagram each (Figs 1.3-1.5) → PEAS table for the taxi → conclude that the taxi needs a utility-based learning agent because the environment is partially observable, stochastic and multi-agent, and goals conflict (speed vs safety vs comfort).
Answer plan
f = g + h, the seven algorithm steps, the OPEN/CLOSED table, the path in a box, the admissibility check (compare h(start) with the actual cost), then the memory drawback and IDA*/SMA*/RBFS. → worked examples
Answer plan and the SEND+MORE solution
CSP definition (X, D, C) → the seven necessary conditions → column equations → propagate.
Note that SEND+MORE has not yet been set at PU but is the single most famous instance, so it is a live candidate. The method is identical to the seven solved problems.
Answer plan
Answer plan
Types of knowledge → the five representation schemes table → semantic net diagram (Fig 3.1) with is-a and has-a links → the same knowledge as a frame → inheritance walk ("Sparrow is-a Bird is-a Animal, therefore Sparrow breathes") → properties of a good representation → strengths and weaknesses of each.
Worked answer
Prior P(B) = 0.40 rises to posterior P(B|D) = 0.53 once the defect is observed, evidence shifts belief towards the less reliable machine. Any Bayes variant is this same five-line template.
Answer plan
Definition + the product formula → Fig 4.1 reproduced with all four CPTs → the four explanatory paragraphs → one joint-probability calculation → applications and limitations. → worked version
Answer plan
MLP definition + Fig 5.4 → the seven backprop steps → the delta formulas → the full 2-2-1 numerical from Unit 5 → training vs validation curves and early stopping → limitations (local minima, vanishing gradients, learning-rate sensitivity).
Answer plan
Entropy and gain formulas → a table of gains → the tree diagram → decision tree vs random forest comparison table → pruning as the answer to overfitting. Practise the arithmetic on the dog-bite dataset and on the classic play-tennis table.
Answer plan
Fig 6.1 + the six components → the eight development stages → then the five NLP levels, the parse tree of Fig 6.3 with the grammar rules, and how the tree resolves the "I saw the man with a telescope" ambiguity by producing two trees.
The night-before sheet
Everything that must be in your head when you walk in. Read only this on the last night, nothing else.
Formulas
Numbers to remember
- log₂: 1/2 = −1 · 1/3 = −1.585 · 2/3 = −0.585 · 1/4 = −2 · 3/4 = −0.415 · 3/8 = −1.415 · 5/8 = −0.678 · 1/5 = −2.322 · 2/5 = −1.322 · 3/5 = −0.737
- Burglary CPT: P(B) = 0.001, P(E) = 0.002, P(A|b,e) = 0.95 / 0.94 / 0.29 / 0.001, P(J|a) = 0.90 / 0.05, P(M|a) = 0.70 / 0.01
- Crypt answers: EAT+THAT = 819 + 9219 = 10038 · ODD+ODD = 655 + 655 = 1310 · GO+TO = 81 + 21 = 102 · NINA+SING = 5051 + 9054 = 14105 · LOGIC×2 = 90452 → 180904 · WRONG×2 = 12734 → 25468 · BASE+BALL = 7483 + 7455 = 14938 · SEND+MORE = 9567 + 1085 = 10652
- Mammogram answer 10.2% · rare disease 0.49% · spam 99.9% · blue cab 59.3%
Lists you will be asked to produce
Agent types (5)
Simple reflex · model-based reflex · goal-based · utility-based · learning
Learning agent parts (4)
Performance element · critic · learning element · problem generator
Task environments (7)
Observable · agents · deterministic · episodic · static · discrete · known
Problem formulation (5)
Initial state · actions · transition model · goal test · path cost
CNF steps (8)
↔ out · → out · ¬ inwards · standardise · Skolemise · drop ∀ · distribute · flatten
Resolution steps (5)
FOPL · CNF · negate goal · resolve · derive □
GA steps (8)
Encode · initialise · fitness · select · crossover · mutate · replace · terminate
Backprop steps (7)
Init · forward · error · output δ · hidden δ · update · repeat
Expert system parts (6)
Knowledge base · inference engine · working memory · user interface · explanation · knowledge acquisition
NLP levels (5)
Lexical · syntactic · semantic · discourse · pragmatic
Fuzzy system blocks (4)
Fuzzifier · rule base · inference engine · defuzzifier
Hill climbing problems (3)
Local maximum · plateau · ridge
Ten one-line answers that carry marks
- Rationality maximises expected performance, not actual; it is not omniscience.
- BFS is optimal only when all step costs are equal; UCS fixes that.
- DFS is the only classical strategy with linear O(bm) memory.
- A*'s drawback is memory, not time, it keeps every generated node.
- ∀ pairs with →, ∃ pairs with ∧.
- KB ⊨ α iff (KB ∧ ¬α) is unsatisfiable, the basis of refutation.
- Fuzzy logic models degree of truth; probability models degree of belief.
- Without a non-linear activation, any depth of network collapses to a single linear layer.
- A single perceptron can only separate linearly separable classes, so XOR needs a hidden layer.
- Accuracy is a misleading metric on imbalanced data; quote recall for screening problems.
Draw a diagram in every answer. Number your steps. Box every final answer. Never leave a question blank: a definition plus a labelled figure is worth four marks on a topic you barely know. Keep the crypt-arithmetic for last.
Built from the COM 713.3 syllabus and fourteen past papers, 2018-2024. Where a scanned figure was unreadable, the method is given so you can apply it to your own printed copy. Good luck: the six certain topics are worth 60 marks, and you have time to own all of them.
↑ contents