AI questions split into three kinds: definitions and classifications (agents, AI types, learning types), algorithm traces (BFS/DFS on a graph, A* with a heuristic, minimax with pruning, resolution proofs), and design answers (knowledge representation choice, expert-system architecture). For traces, always show the open list, the closed list, and the evaluation function values — markers credit the trace, not just the final path.
Units 2 and 3 carry the most teaching hours and the most marks. Budget your revision accordingly.
The six-unit breakdown and teaching hours follow the archived 2018 CACS410 outline mapped to BCA302; the 2025 TU syllabus publishes no verified numbered unit outline, and this guide's unit structure is not official 2025 TU wording.
Contents
- Unit 1: Introduction
- Unit 2: Problem Solving Methods
- Unit 3: Knowledge Representation and Reasoning
- Unit 4: Learning
- Unit 5: Neural Networks and Natural Language Processing
- Unit 6: Expert System and Machine Vision
Unit 1: Introduction
Teaching hours: 6
Topics in outline order
- Intelligence, intelligent behaviour, artificial intelligence
- Understanding AI based on thought process and behaviour
- Hard vs strong AI; soft vs weak AI
- Foundations of AI
- Applications of AI
- Intelligent agents: introduction, structure, properties, PEAS description
- Types of agents: simple reflex, model-based, goal-based, utility-based, learning
- Environment types: deterministic, stochastic, static, dynamic, observable, semi-observable, single-agent, multi-agent
Explanation
1.1 Intelligence, intelligent behaviour, artificial intelligence
Intelligence is the capacity to acquire and apply knowledge, to reason, to learn, and to adapt to new situations. Intelligent behaviour is behaviour that would be called intelligent in a human — perceiving, reasoning, acting, learning. Artificial intelligence is the branch of computing that builds systems performing tasks that currently require human intelligence: perception, language, reasoning, planning, and learning.
Strong (hard) AI claims a machine can possess genuine understanding and consciousness — the "mind is a machine" position, associated with the Chinese Room debate. Weak (soft) AI claims only that machines can simulate intelligent behaviour without consciousness; it is the position almost all working systems take. Note the common alternative pairing: strong AI = general intelligence, weak AI = narrow, task-specific systems. State which pairing you are using in an answer.
1.2 Foundations of AI
The field is conventionally organised on two axes: thinking vs acting, and humanly vs rationally. Thinking humanly models cognition (cognitive science); acting humanly is judged by the Turing Test; thinking rationally uses laws of thought and logic; acting rationally builds the rational agent, which is the modern mainstream because rationality is mathematically definable and does not require matching human mistakes.
Philosophy (logic, mind, knowledge), mathematics (logic, probability, computability, NP-completeness), economics (decision theory, utility, game theory), neuroscience (neurons, brain organisation), psychology (behaviourism, cognitive models), computer engineering (fast hardware), control theory and cybernetics (feedback, stability), and linguistics (language structure, semantics).
1.3 Applications of AI
Game playing, speech recognition, machine translation, computer vision, robotics, expert systems, fraud detection, medical diagnosis, recommendation, autonomous vehicles, and generative assistants. For each, name the core technique — search, learning, reasoning, or optimisation — because that is the part the syllabus tests.
1.4 Intelligent agents
An agent perceives its environment through sensors and acts through actuators. Its structure is architecture plus program: the architecture runs the program, and the program maps percept sequences to actions. Properties: autonomy, reactivity, pro-activeness, and social ability. PEAS specifies the task environment: Performance measure, Environment, Actuators, Sensors — e.g. for a medical diagnosis system: accuracy and cost (P), patient and hospital (E), displays and questions (A), symptoms and lab results (S).
Simple reflex: condition-action rules on the current percept, fails in partially observable worlds. Model-based reflex: keeps internal state to track the unobserved world. Goal-based: chooses actions that reach a goal, using search and planning. Utility-based: compares outcomes by a utility function, handling conflicting goals and trade-offs. Learning: a performance element plus critic, learning element, and problem generator, which improves over time.
Deterministic vs stochastic (is the next state fully determined by the current state and action?), static vs dynamic (does the world change while the agent decides?), fully vs partially observable, discrete vs continuous, episodic vs sequential, single-agent vs multi-agent (competitive or cooperative). These properties decide which algorithm is appropriate: a stochastic, partially observable, dynamic environment rules out simple table-driven agents.
Key terms
Turing Test · rational agent · PEAS · percept sequence · autonomy · utility function · Chinese Room · NP-completeness
Revision points
- The rational-agent view dominates because it is general and testable; the Turing Test measures behaviour, not understanding.
- PEAS answers are marked on all four elements being specific to the stated system.
- Environment classification drives agent design — always connect the two in a long answer.
Practice questions
- Define artificial intelligence under the "acting rationally" view and explain one advantage of that view.
- Give the PEAS description for an automated railway gate controller.
- Classify a self-driving car's environment on all dimensions and justify each.
Answer notes: (1) AI is the study and construction of agents that act so as to maximise expected performance given their percepts and knowledge. Advantage: it is precisely definable via utility and probability, covers environments with uncertainty, and does not depend on reproducing human cognition. (2) Performance: safety, throughput, no collisions. Environment: track, trains, road users, signals. Actuators: gate motor, warning lights, siren. Sensors: track circuits, axle counters, cameras, manual override. (3) Partially observable (occlusion, weather), stochastic (other drivers, pedestrians), dynamic (world changes while planning), continuous (position, speed), sequential (decisions affect later states), multi-agent (other drivers, pedestrians).
Worked example: PEAS description for a smart traffic light controller
Problem: Write a PEAS description for an autonomous traffic light controller at a busy intersection.
Solution:
| PEAS Element | Description |
|---|---|
| Performance measure (P) | Average waiting time per vehicle, number of pedestrian crossings completed per green phase, and fuel consumption reduction compared to fixed-time signals. |
| Environment (E) | A road intersection with vehicles and pedestrians. The environment is partially observable (the controller cannot see every vehicle approaching from side streets), stochastic (arrival rates vary), dynamic (traffic patterns change throughout the day), and multi-agent (other intersections, emergency vehicles). |
| Actuators (A) | The traffic light controller can change the signal state (red, yellow, green) for the main road and the cross-street, and can trigger pedestrian walk/don't-walk signals. |
| Sensors (S) | Sensors include inductive loop detectors in the road (detect vehicle presence and count), cameras (visual detection of vehicles and pedestrians), and pedestrian push-buttons. |
Interpretation: The performance measure quantifies "good" behaviour (shorter waits, better flow). The environment properties dictate that a simple reflex agent would fail (partially observable, stochastic), so a model-based or goal-based agent is needed. The actuators are discrete (signal changes), and the sensors provide both quantitative (loop counts) and qualitative (camera images) data.
Use case: AI in Nepali language processing
A research team in Nepal is building a chatbot that can answer questions in Nepali about government services. The project uses a knowledge-based approach (rule-based expert system) for domain-specific queries and a statistical model (sequence-to-sequence with attention) for generating natural-language responses. The system uses a dictionary of Nepali verbs and prefixes to handle morphology. This illustrates how AI techniques can be combined: symbolic AI for reliability in the domain, and statistical AI for natural-language generation.
Mermaid diagram: PEAS framework
graph TB
A[Performance Measure] -->|Defines success| B[Environment]
A -->|Drives agent design| C[Actuators]
A -->|Guides evaluation| D[Sensors]
Explanation: The PEAS framework consists of four elements that completely specify a task environment. Performance measure defines what constitutes successful behaviour. Environment describes the task context. Actuators are what the agent can do. Sensors are how the agent perceives the environment. All four must be specified for a well-defined agent design problem.
Common mistakes, limitations, and security concerns
- Mistake 1: Confusing "strong AI" (machines with consciousness) with "general AI" (machines that can perform any intellectual task). They are related but distinct; be clear which you mean in an answer.
- Mistake 2: Saying "the Turing Test proves a machine is intelligent". The Turing Test only proves that a machine can imitate human responses well enough to fool interrogators; it does not measure understanding or consciousness.
- Mistake 3: Thinking "all AI uses neural networks". AI includes many approaches: search, logic, knowledge representation, probabilistic modelling, reinforcement learning, and more. Neural networks are just one subfield.
- Limitation: Current AI systems are narrow; they excel at the specific tasks they were trained for but cannot transfer learning to unrelated domains without significant retraining.
- Security concern: AI systems that process user data must comply with privacy regulations (e.g., GDPR). Facial recognition and surveillance AI raise ethical concerns about mass surveillance and bias.
Exam-ready answer points
Short answer (1–2 marks):
- Define "rational agent" and list its four properties.
- What does PEAS stand for? (Performance measure, Environment, Actuators, Sensors)
- Differentiate strong AI from weak AI with one sentence.
- Name the four basic agent types (simple reflex, model-based reflex, goal-based, utility-based).
Long answer (5–10 marks):
- Describe the four views of AI (thinking humanly, acting humanly, thinking rationally, acting rationally) and explain why the rational-agent view is dominant.
- Compare the six environment dimensions (deterministic/stochastic, static/dynamic, fully/partially observable, discrete/continuous, episodic/sequential, single/multi-agent) and how they affect agent design.
- Explain the PEAS framework with a detailed example of your choice.
Diagram question:
- Draw the PEAS framework showing all four elements and how they connect to agent design.
- Draw a two-by-two matrix classifying agents by percept horizon (current vs internal state) and decision time (episodic vs sequential).
Self-check questions (with answers)
-
Question: What is the difference between "acting humanly" and "acting rationally" in AI? Answer: "Acting humanly" means the machine's behaviour is judged by the Turing Test — imitating human responses. "Acting rationally" means the machine acts to maximise its performance measure, regardless of whether its behaviour looks human. The rational view is dominant because it is mathematically precise and does not require matching human cognition.
-
Question: List the six dimensions of environment classification and give one example of each. Answer: Deterministic (next state fully determined by current state and action — e.g., chess), stochastic (next state has probability distributions — e.g., dice games), static (environment does not change while the agent decides — e.g., single-player puzzle), dynamic (environment changes during decision — e.g., real-time strategy), fully observable (complete state information — e.g., checkers), partially observable (some state information hidden — e.g., poker), discrete (finite states/actions — e.g., grid world), continuous (infinite states/actions — e.g., robot arm control), episodic (each episode is independent — e.g., image classification), sequential (decisions affect future — e.g., game playing), single-agent (one agent — e.g., solitaire), multi-agent (multiple agents — e.g., traffic control).
-
Question: What is the "frame problem" in AI, and why is it challenging? Answer: The frame problem is the challenge of representing what does not change when an action is taken. It is difficult because the world has countless unchanged facts, and explicitly representing all of them is infeasible. Default logic and frame axioms help, but the problem remains a foundational issue in knowledge representation.
-
Question: Differentiate a simple reflex agent from a model-based reflex agent. Answer: A simple reflex agent uses condition-action rules on the current percept only, failing when the percept is insufficient. A model-based reflex agent maintains an internal state that tracks the unobserved part of the world, allowing it to handle partially observable environments.
-
Question: What is the Chinese Room argument, and what does it target? Answer: The Chinese Room, proposed by John Searle, argues that a system can manipulate symbols according to rules without understanding them. It targets the claim that strong AI (machines with genuine understanding) is achievable by symbol manipulation alone.
-
Question: When would you choose a utility-based agent over a goal-based agent? Answer: Choose utility-based when the agent has conflicting goals and needs to trade off between them (e.g., a self-driving car balancing travel time vs. fuel consumption vs. safety). Goal-based agents focus on reaching a single goal state without handling trade-offs.
-
Question: What are the two common pairings of "strong/soft AI"? Answer: Strong AI = general intelligence / consciousness. Weak AI = narrow, task-specific systems / simulated behaviour.
-
Question: Why is a partially observable environment more challenging for an agent, and what type of agent typically handles it? Answer: In a partially observable environment, the agent cannot determine the full state from a single percept, so it must maintain an internal state. A model-based reflex agent typically handles this by keeping track of what it believes the state to be.
Unit 2: Problem Solving Methods
Teaching hours: 12
Topics in outline order
- Definition of a problem; problem as state space; problem formulation; well-defined problems
- Constraint satisfaction problems
- Water jug, n-queens, cryptarithmetic, graph colouring problems
- Problem solving by searching; types of searching; measuring performance; general state space search
- Uninformed search: BFS, DFS, depth-limited, iterative deepening, bidirectional
- Informed search: greedy best-first, A*, optimality of A*, local search (hill climbing, simulated annealing)
- Game playing: optimal decisions, minimax, alpha-beta pruning, tic-tac-toe, stochastic games
Explanation
2.1 Definition of a problem, problem as state space, well-defined problems, CSPs, classic problems
A problem is defined by an initial state, a set of actions, a transition model (successor function), a goal test, and a path cost. The state space is the set of all states reachable from the initial state; a solution is a path from initial to goal, and an optimal solution has minimum path cost. A well-defined problem specifies all five components precisely so that solutions can be verified. Formulation is the modelling step: choosing which details to keep (e.g. only jug contents, not water temperature) determines the size of the space you must search.
A constraint satisfaction problem (CSP) has variables, domains, and constraints; a solution assigns every variable a value satisfying all constraints. Standard techniques: backtracking search, forward checking, constraint propagation (arc consistency), variable and value ordering (minimum remaining values, least constraining value), and local search (min-conflicts). CSPs matter because the structure allows pruning far beyond blind search.
Classic problems: Water jug: states are the amounts in each jug; actions pour until source empty or target full. N-queens: place n queens so none attack; incremental formulation places one queen per column. Cryptarithmetic: assign digits to letters so the arithmetic holds, with leading-zero and all-different constraints — a CSP with carry variables. Graph colouring: assign colours to vertices so adjacent vertices differ; it is NP-complete and demonstrates constraint propagation well.
2.2 Problem solving by searching, types of searching, measuring performance, general state space search
Search explores the state space by expanding nodes from the frontier. Performance is measured by completeness (does it find a solution if one exists?), optimality, time complexity (nodes generated), and space complexity (nodes stored). Complexity is expressed with b (branching factor), d (depth of the shallowest goal), and m (maximum depth). General state-space search keeps a frontier and an explored set, and detects repeated states to avoid loops.
2.3 Uninformed search: BFS, DFS, depth-limited, iterative deepening, bidirectional
BFS expands the shallowest node: complete, optimal for unit step costs, time and space O(b^d) — memory is the killer. DFS expands the deepest node: space O(bm), not optimal, may not terminate in infinite spaces. Depth-limited adds a limit l, removing infinite descent but introducing incompleteness if the goal is deeper. Iterative deepening repeats depth-limited search with increasing limits: combines BFS's optimality with DFS's linear memory, at the cost of re-generating upper levels. Bidirectional searches forward from the start and backward from the goal and meets in the middle, reducing time to O(b^(d/2)) but requiring reversible actions and efficient goal-set membership.
2.4 Informed search: greedy best-first, A*, optimality of A*, local search
An evaluation function f(n) guides the search. Greedy best-first uses f = h(n), the estimated cost to the goal: fast but not optimal and can be misled by a bad heuristic. A uses f = g(n) + h(n), actual cost so far plus estimate. A* is complete, and optimal if h is admissible (never overestimates) and, for graph search, consistent (h(n) ≤ c(n,n′) + h(n′)). With an admissible but inconsistent heuristic, graph search needs re-opening of nodes; with a consistent heuristic, each node is expanded once. Local search keeps one state and moves to a neighbour: hill climbing (steepest ascent) can stick at local maxima, plateaus, and ridges; simulated annealing accepts worse moves with probability e^(−ΔE/T), lowering T over time to escape local optima.
2.5 Game playing: optimal decisions, minimax, alpha-beta pruning, tic-tac-toe, stochastic games
In a two-player zero-sum deterministic game, minimax computes the value of a state as MAX's best move assuming MIN plays optimally; values back up from terminal utilities. Alpha-beta pruning prunes branches that cannot affect the result, giving the same answer as minimax with up to O(b^(d/2)) nodes in the best case. Tic-tac-toe is small enough for full minimax with pruning. Stochastic games (expectiminimax) add chance nodes with probabilities, so values become expected utilities; this is the model for dice and card games.
Key terms
Frontier · successor function · admissibility · consistency (monotonicity) · heuristic · local maximum · plateau · evaluation function · ply · chance node
Revision points
- Memorise complexities: BFS O(b^d) time and space; DFS O(bm) space; IDDFS O(b^d) time, O(bd) space; A* exponential worst case but guided.
- A* optimality requires admissibility; graph-search optimality requires consistency. Distinguish the two.
- Alpha-beta does not change the answer, only the work — that sentence is worth marks.
Practice questions
- Formulate the water jug problem (4-litre and 3-litre jugs, goal 2 litres in the 4-litre jug) as a state space and give a solution path.
- Trace A* on a small graph and explain why an inadmissible heuristic can return a suboptimal path.
- Apply alpha-beta pruning to a game tree and state how many leaves are evaluated versus plain minimax.
Answer notes: (1) States (x, y) with 0 ≤ x ≤ 4, 0 ≤ y ≤ 3; actions fill, empty, pour; start (0,0); goal x = 2. Path: (0,0) → (0,3) → (3,0) → (3,3) → (4,2) → (0,2) → (2,0). (2) f = g + h; if h overestimates the remaining cost on a cheap branch, that branch's f looks large and it is expanded later, so the first goal popped may not be cheapest. (3) Alpha-beta evaluates only leaves that survive pruning; in the best case about 2b^(d/2) instead of b^d, and the root value is identical.
Worked example: Water jug problem state space and solution
Problem: Solve the water jug problem with a 4-litre jug and a 3-litre jug, aiming to get exactly 2 litres in the 4-litre jug.
Solution:
-
State: (x, y) where x = amount in 4-litre jug, y = amount in 3-litre jug. Both x and y are integers.
-
Initial state: (0, 0) — both jugs empty.
-
Goal: x = 2 (exactly 2 litres in the 4-litre jug).
-
Actions (all operations are deterministic):
- Fill 4-litre jug: (x, y) → (4, y)
- Fill 3-litre jug: (x, y) → (x, 3)
- Empty 4-litre jug: (x, y) → (0, y)
- Empty 3-litre jug: (x, y) → (x, 0)
- Pour from 4-litre to 3-litre: (x, y) → (x − min(x, 3−y), y + min(x, 3−y)) i.e. pour until the 4-litre jug is empty or the 3-litre jug is full.
- Pour from 3-litre to 4-litre: (x, y) → (x + min(y, 4−x), y − min(y, 4−x))
- (Optional) Empty/Full from/to source — same as 3 and 2.
-
Transition model: All actions are deterministic and invertible.
-
Solution path (one possible path, 7 steps):
- Start: (0, 0)
- Fill 3-litre jug: (0, 0) → (0, 3)
- Pour 3-litre to 4-litre: (0, 3) → (3, 0)
- Fill 3-litre jug: (3, 0) → (3, 3)
- Pour 3-litre to 4-litre: (3, 3) → (4, 2) — the 4-litre jug has room for 1 litre, so 1 litre is poured; 2 litres remain in the 3-litre jug
- Empty 4-litre jug: (4, 2) → (0, 2)
- Pour 3-litre to 4-litre: (0, 2) → (2, 0) — all 2 litres fit in the empty 4-litre jug
- Result: (2, 0) — 4-litre jug now has exactly 2 litres. Goal reached!
Intermediate state table:
| Step | Action | State (x, y) |
|---|---|---|
| 0 | Start | (0, 0) |
| 1 | Fill 3-litre | (0, 3) |
| 2 | Pour 3→4 | (3, 0) |
| 3 | Fill 3-litre | (3, 3) |
| 4 | Pour 3→4 | (4, 2) |
| 5 | Empty 4-litre | (0, 2) |
| 6 | Pour 3→4 | (2, 0) |
| 7 | Goal: x = 2 ✓ |
Verification: At step 7, x = 2, so the 4-litre jug contains exactly 2 litres, which is the goal. The path is 7 actions from the start state.
Use case: Route planning in GPS navigation
A GPS navigation system finds the shortest route from Kathmandu to Pokhara. The state space consists of (current_city, remaining_distance). The initial state is (Kathmandu, total_distance). The goal is (Pokhara, 0). The successor function generates neighbouring cities reachable from the current city. The path cost is the road distance. The system uses A* with a heuristic (straight-line distance to Pokhara) to efficiently find the route, exploring fewer nodes than BFS or DFS would require. This is a real-time application of uninformed and informed search.
Mermaid diagram: BFS vs DFS frontier expansion
graph TD
A[Start: S] --> B[BFS: expand shallowest]
A --> C[DFS: expand deepest]
B --> D[Level 1: A, B]
D --> E[Level 2: C, D, E, F]
C --> F[Goes deep: S→A→G→H→...]
Explanation: The diagram compares BFS and DFS state-space expansion. BFS expands all nodes at the current depth before moving to the next level (shallowest first), guaranteeing finding the shallowest goal. DFS follows a single path deep into the tree before backtracking, using less memory but potentially missing shallow goals or infinite looping in infinite trees. The branching factor and depth determine the efficiency of each approach.
Common mistakes, limitations, and security concerns
- Mistake 1: Confusing "optimal" with "complete". A complete algorithm finds a solution if one exists; an optimal algorithm finds the best solution (minimum cost). BFS is both complete and optimal (for unit costs); DFS is neither complete nor optimal in infinite spaces.
- Mistake 2: Forgetting that A* optimality requires admissibility (h never overestimates). An inadmissible heuristic can make A* return a suboptimal path, even if it finds a solution faster.
- Mistake 3: Thinking "alpha-beta changes the minimax answer". Alpha-beta pruning does not change the computed minimax value; it only removes branches that make the same decision, reducing the number of nodes evaluated.
- Limitation: Hill climbing local search can get stuck at local maxima; it has no memory of where it has been. Simulated annealing escapes local optima but requires careful cooling schedules and many evaluations.
- Security concern: Pathfinding algorithms in autonomous vehicles must handle adversarial inputs (e.g., fake road signs) that could mislead the planning system. Robustness testing and validation are essential.
Exam-ready answer points
Short answer (1–2 marks):
- What does "branching factor" mean? (the average number of successors per state)
- What is the time/space complexity of BFS? (O(b^d))
- What is the difference between a "well-defined problem" and a general problem? (a well-defined problem has five specified components: initial state, actions, transition model, goal test, path cost)
- What does "admissible" mean for a heuristic? (never overestimates the true cost to the goal)
Long answer (5–10 marks):
- Formulate the 8-puzzle as a state-space search problem: initial state, actions, transition model, goal test, path cost.
- Compare BFS, DFS, and IDDFS on time complexity, space complexity, and completeness.
- Explain the A* algorithm and the conditions for its optimality (admissibility and consistency).
- Describe the minimax algorithm for two-player games and how alpha-beta pruning improves efficiency.
Diagram question:
- Draw the state space for the water jug problem and trace the solution path.
- Draw a game tree with alpha-beta pruning, showing which branches are pruned and which are kept.
Self-check questions (with answers)
-
Question: What is the state space for the water jug problem with a 4-litre and a 3-litre jug? Answer: States (x, y) with 0 ≤ x ≤ 4, 0 ≤ y ≤ 3, giving 5 × 4 = 20 possible states.
-
Question: Compare the time complexity of BFS and DFS in terms of b (branching factor) and d (goal depth). Answer: BFS time: O(b^d). DFS time: O(b^m) where m is the maximum depth (may be infinite). BFS space: O(b^d). DFS space: O(bm).
-
Question: What is the key difference between greedy best-first and A* search? Answer: Greedy best-first uses f(n) = h(n) (estimated cost to goal), which is fast but not optimal and can be misled by a bad heuristic. A* uses f(n) = g(n) + h(n) (actual cost so far + estimated cost), which is optimal if h is admissible and consistent.
-
Question: Explain why alpha-beta pruning does not change the minimax result. Answer: Alpha-beta pruning removes branches that cannot affect the final minimax value, because the value of a min node is the minimum of its successors and a max node is the maximum. If a branch is pruned, it is because we have already found a better (or worse) value at an ancestor, so the pruned branch's value cannot change the outcome.
-
Question: What is the difference between "state space" and "search tree"? Answer: The state space is the set of all reachable states (nodes may be reached via multiple paths). The search tree is the tree of states generated starting from the initial state, where nodes are typically expanded without checking for duplicates (unless using graph search).
-
Question: When would you use local search (hill climbing) instead of graph search (BFS/A*)? Answer: Local search uses minimal memory (one current state) and is suitable for large state spaces where finding the global optimum is less important than finding a good solution quickly. It is commonly used for optimisation problems (e.g., Travelling Salesperson Problem) rather than finding the shortest path from A to B.
-
Question: What is the "explored set" in search, and why is it important? Answer: The explored set (or closed set) keeps track of all states that have already been visited, preventing the search from revisiting them and avoiding infinite loops, especially in state spaces with cycles.
-
Question: What is the expectiminimax algorithm, and when is it used? Answer: Expectiminimax extends minimax to handle chance nodes (stochastic games). Each chance node has a probability, and the expected value is computed as the weighted average of the successor values. It is used for games with dice, cards, or other sources of randomness.
Unit 3: Knowledge Representation and Reasoning
Teaching hours: 15
Topics in outline order
- Definition and importance of knowledge; issues in knowledge representation; knowledge representation systems; properties; types of knowledge; the role of knowledge
- Knowledge representation techniques: rule based, semantic nets, frames, logic based
- Propositional logic: syntax and semantics, proof by resolution, CNF, resolution algorithm, limitations, forward and backward chaining
- Predicate logic: FOPL syntax, semantics, quantification, Horn clauses, inference by conversion to PL, rules of inference, unification and lifting, CNF for FOPL, resolution, resolution refutation system
- Handling uncertain knowledge, random variables, prior and posterior probability, inference using full joint distribution, Bayes' rule, Bayesian networks and reasoning in them
Explanation
3.1 Definition and importance of knowledge; issues in knowledge representation; properties; types of knowledge; role of knowledge
Knowledge is information about the world that supports reasoning and action, as opposed to raw data. It is important because intelligent behaviour requires inferring new facts, not just storing them. A knowledge representation (KR) is a formal scheme for encoding beliefs so a machine can reason with them. Issues: the knowledge-acquisition bottleneck, choosing the right level of abstraction, handling incomplete and uncertain knowledge, and keeping inference tractable. Properties of a good KR: representational adequacy, inferential adequacy, inferential efficiency, and acquisitional efficiency. Types: declarative (facts), procedural (how to do things), explicit vs tacit, and commonsense vs expert. Role: KR supports inference, explanation, and knowledge sharing; it is the substrate of expert systems.
3.2 Knowledge representation techniques: rule based, semantic nets, frames, logic based
Rule-based: IF–THEN production rules with a working memory and an inference engine (forward chaining for data-driven reasoning, backward for goal-driven). Semantic nets: nodes for concepts and labelled arcs for relations (is-a, has-a), supporting inheritance but weak on precise semantics. Frames: structured records with slots and fillers, default values, and inheritance; natural for stereotyped concepts. Logic-based: declarative statements with formal semantics, allowing sound inference — the most rigorous option and the one the rest of the unit builds.
3.3 Propositional logic: syntax and semantics, proof by resolution, CNF, resolution algorithm, limitations, forward and backward chaining
Syntax: atoms (P, Q), connectives ¬, ∧, ∨, →, ↔. Semantics: truth tables assign truth values; a sentence is valid if true in every model, satisfiable if true in some. CNF: conjunction of clauses, each a disjunction of literals; conversion uses elimination of ↔ and →, De Morgan, distribution, and clause normalisation. Resolution: from (A ∨ P) and (B ∬ P) derive (A ∨ B); refutation proves KB ⊨ α by showing KB ∧ ¬α is unsatisfiable. Limitations: no quantifiers or relations, so it cannot express "all students..." compactly, and the propositional language grows exponentially with the number of objects. Chaining: forward chaining derives all consequences from facts with Horn clauses (data-driven), backward chaining works from the query to supporting facts (goal-driven, used in Prolog).
3.4 Predicate logic: FOPL syntax, semantics, quantification, Horn clauses, inference by conversion to PL, rules of inference, unification and lifting, CNF for FOPL, resolution, resolution refutation system
Adds terms, variables, predicates, functions, and quantifiers ∀ (universal) and ∃ (existential). Semantics: an interpretation maps constants, functions, and predicates onto a domain; a sentence is true in a model accordingly. Quantification: ∀x P(x) means P holds for every object; ∃x P(x) means at least one; ¬∀x P(x) ≡ ∃x ¬P(x) and vice versa — the quantifier negation equivalences are heavily examined. Horn clause: a clause with at most one positive literal, written as a rule P₁ ∧ … ∧ Pₙ → Q, which supports efficient chaining. Inference to PL: universal instantiation substitutes a ground term; existential instantiation introduces a Skolem constant. Rules of inference: modus ponens, modus tollens, and-introduction/elimination, or-introduction, universal generalisation. Unification finds a substitution making two atomic sentences identical; lifting turns propositional inference rules into FOPL rules by unifying first. CNF for FOPL: eliminate implications, move negations inward, standardise variables apart, Skolemise existentials, drop universals, distribute, and split into clauses. Resolution refutation: negate the goal, convert to clause form, resolve until the empty clause appears.
3.5 Handling uncertain knowledge, random variables, prior and posterior probability, inference using full joint distribution, Bayes' rule, Bayesian networks and reasoning in them
Real knowledge is often uncertain, so logic alone is insufficient; probability supplies degrees of belief. Random variable: a variable with a domain of values (Boolean, discrete, continuous). Prior P(A) is belief before evidence; posterior P(A|B) after. Full joint distribution: a table over all variables from which any probability can be computed by summing out irrelevant variables (inference by enumeration); it is complete but exponential in size. Bayes' rule: P(A|B) = P(B|A)·P(A)/P(B), used for diagnosis from causal knowledge and as the update rule in Bayesian reasoning. Bayesian network: a directed acyclic graph with one node per variable, each with a conditional probability table given its parents, encoding conditional independences; inference is exact by variable elimination or approximate by sampling (likelihood weighting, MCMC), and the topology typically encodes causal structure.
Key terms
Validity vs satisfiability · clause · literal · Skolem constant · most general unifier · Horn clause · conditional independence · DAG · inference by enumeration
Revision points
- Resolution is refutation-based: to prove α, show KB ∧ ¬α leads to the empty clause.
- Universal instantiation is sound; existential instantiation needs a fresh Skolem constant.
- A Bayesian network's size is exponential in the maximum number of parents, not in the number of variables — that is its main advantage over a joint table.
Practice questions
- Convert
(P → Q) ∧ (Q → R)to CNF and proveP → Rby resolution. - Explain unification and give the most general unifier for
Knows(John, x)andKnows(y, Mary). - State Bayes' rule and use it for a disease test with 1% prevalence, 99% sensitivity, and 5% false-positive rate.
Answer notes: (1) CNF: (¬P ∨ Q), (¬Q ∨ R). Negate the goal: P and ¬R. Resolve P with (¬P ∨ Q) → Q; Q with (¬Q ∨ R) → R; R with ¬R → empty clause. (2) Unification finds a substitution making two atoms identical: {y/John, x/Mary}. (3) P(D|+) = P(+|D)P(D) / [P(+|D)P(D) + P(+|¬D)P(¬D)] = 0.99×0.01 / (0.0099 + 0.05×0.99) = 0.0099/0.0594 ≈ 0.167, i.e. about 17% — the base-rate point.
Worked example: Converting to CNF and resolution proof
Problem: Convert the expression (P → Q) ∧ (Q → R) to CNF and use resolution to prove P → R (i.e., derive R from P and the given clauses).
Solution:
-
Convert to CNF. Start with
(P → Q) ∧ (Q → R).- Eliminate implications:
P → Qis equivalent to¬P ∨ Q, andQ → Ris equivalent to¬Q ∨ R. - The expression becomes
(¬P ∨ Q) ∧ (¬Q ∨ R). - This is already in CNF: two clauses conjoined, each a disjunction of literals.
- Clause 1:
¬P ∨ Q - Clause 2:
¬Q ∨ R
- Eliminate implications:
-
Prove P → R by resolution. To prove that
P → Rlogical follows from the KB, we show that KB ∧ ¬R leads to contradiction (empty clause).- KB =
(¬P ∨ Q) ∧ (¬Q ∨ R) - Negated goal:
¬(P → R)≡P ∧ ¬R - So we add
Pand¬Rto the KB.
- Start with clauses: C1 = (¬P ∨ Q), C2 = (¬Q ∨ R), and the negated goal ¬(P → R) = P ∧ ¬R.
- Add P and ¬R as unit clauses.
- Resolve P with (¬P ∨ Q) → Q (parent clauses P and C1).
- Resolve Q with (¬Q ∨ R) → R (parent clauses Q and C2).
- Resolve R with ¬R → empty clause (parent clauses R and ¬R).
Since the empty clause is derived, the original goal P → R is proven.
Resolution tableau:
Clause Literals Parents (resolution step) C1 ¬P, Q — C2 ¬Q, R — Unit P — (added) Unit ¬R — (added) R1 Q Resolve(P, C1) — eliminate P R2 R Resolve(Q, C2) — eliminate Q Empty — Resolve(R2, ¬R) — eliminate R Since the empty clause is derived, the resolution proof is complete, and P → R is logically entailed.
- KB =
Intermediate result: The CNF of (P → Q) ∧ (Q → R) is (¬P ∨ Q) ∧ (¬Q ∨ R). The resolution proof derives the empty clause from these clauses plus the negated goal, thereby proving P → R.
Use case: Knowledge representation for a Nepali medical diagnosis system
A clinic in Nepal wants an AI system to help diagnose common diseases based on symptoms. The knowledge base uses a rule-based representation:
- Rule 1: IF fever AND cough THEN likely influenza.
- Rule 2: IF fever AND breathing_difficulty THEN likely pneumonia.
- Rule 3: IF rash AND recent_travel THEN consider dengue.
The inference engine uses forward chaining: it starts with observed symptoms (e.g., the patient has fever and rash) and derives conclusions (likely influenza or dengue). This illustrates how a simple KR formalism can support practical decision-support in a resource-constrained setting like a Nepali clinic.
Mermaid diagram: Resolution refutation steps
graph TD
A[Start: KB ∧ ¬Goal] --> B[Convert to CNF]
B --> C[Add Negated Goal as Clauses]
C --> D[Resolve: Select Two Clauses]
D --> E[Compute Resolvent]
E --> F{Empty Clause?}
F -->|Yes| G[Proof Complete]
F -->|No| D
Explanation: The diagram shows the core resolution refutation procedure: start with the knowledge base plus the negated goal, convert both to clausal form (CNF), then repeatedly select two clauses, compute their resolvent (eliminating complementary literals), and continue until the empty clause is derived. The empty clause indicates a contradiction, proving the original goal.
Common mistakes, limitations, and security concerns
- Mistake 1: Confusing "valid" and "satisfiable". A formula is valid if it is true in every interpretation; it is satisfiable if it is true in some interpretation. Valid formulas are always satisfiable, but the converse is not true.
- Mistake 2: Forgetting that resolution is refutation-only: to prove α, you show KB ∧ ¬α is unsatisfiable, not that you derive α directly.
- Mistake 3: Misapplying unification by not standardising variables apart before resolution. Two clauses with the same variable name may produce incorrect resolvents if the variables are not renamed.
- Limitation: Propositional logic cannot express statements about "all" or "some" (quantification). For "All humans are mortal", you need predicate logic with the ∀ quantifier.
- Security concern: In automated reasoning systems, malformed input can cause excessive computation (e.g., non-terminating resolution). Timeouts and clause limits are necessary for production deployments.
Exam-ready answer points
Short answer (1–2 marks):
- What is the difference between valid and satisfiable?
- What is CNF, and what operations are needed to convert a formula to CNF?
- What is unification, and what is it used for?
- Name the two main inference directions in propositional logic: forward chaining and backward chaining.
Long answer (5–10 marks):
- Convert a given first-order logic formula to CNF and show the conversion steps.
- Explain resolution: the inference rule, the refutation-based proof strategy, and the condition for success (empty clause).
- Describe the properties of a good knowledge representation: representational adequacy, inferential adequacy, inferential efficiency, and acquisitional efficiency.
- Explain Bayes' rule with the disease-test example, including the base-rate fallacy.
Diagram question:
- Draw the resolution refutation procedure: start with KB ∧ ¬α, convert to CNF, resolve until empty clause.
- Draw a truth table for propositional logic, showing validity and satisfiability.
- Draw a Bayesian network structure with conditional probability tables.
Self-check questions (with answers)
-
Question: What are the four properties of a good knowledge representation? Answer: Representational adequacy, inferential adequacy, inferential efficiency, and acquisitional efficiency.
-
Question: What is the key difference between propositional logic and predicate logic? Answer: Propositional logic deals with whole propositions without internal structure (atoms P, Q, etc.). Predicate logic adds terms, variables, predicates, functions, and quantifiers (∀, ∃), allowing statements about "all" and "some".
-
Question: Explain the difference between universal instantiation and existential instantiation in FOPL. Answer: Universal instantiation substitutes a ground term for a universally quantified variable (∀x P(x) → P(c)). Existential instantiation introduces a Skolem constant for an existentially quantified variable (∃x P(x) → P(c), where c is a fresh constant not previously used).
-
Question: What is the base-rate fallacy, and how does it appears in the disease-test example? Answer: The base-rate fallacy is ignoring the prior probability (prevalence) when judging the posterior probability. In the example, even with 99% sensitivity and 5% false-positive rate, if prevalence is 1%, the probability of having the disease given a positive test is only about 17%, not 95% as one might intuitively expect.
-
Question: What is a Horn clause, and why is it important in logic programming? Answer: A Horn clause is a clause with at most one positive literal, written as a rule
P₁ ∧ … ∧ Pₙ → Q. It is important because it supports efficient logic programming (Prolog) and linear-time forward chaining. -
Question: How does a Bayesian network encode conditional independence? Answer: A Bayesian network is a DAG where each node is conditionally independent of its non-descendants given its parents. This encodes a compact factorisation of the joint distribution using conditional probability tables, making inference more tractable than using a full joint table.
-
Question: What is the difference between forward chaining and backward chaining in propositional logic? Answer: Forward chaining starts from the known facts and derives new conclusions (data-driven), stopping when no new facts can be derived or the query is supported. Backward chaining starts from the query and works backward to find supporting facts (goal-driven), commonly used in Prolog.
-
Question: What is the "frame problem", and how does it relate to knowledge representation? Answer: The frame problem is the challenge of representing what does not change when an action is taken. In KR, it relates to the difficulty of explicitly stating all unaffected properties, requiring default logic or circumscription to handle implicitly.
Unit 4: Learning
Teaching hours: 4
Topics in outline order
- Concepts of machine learning
- Rote learning
- Learning by analogy
- Inductive learning
- Explanation-based learning
- Supervised and unsupervised learning
- Learning by evolution (genetic algorithm)
Explanation
4.1 Concepts of machine learning
Learning is any change in a system that improves its performance on future tasks. A learning system has a performance element (acts), a critic (evaluates outcomes), a learning element (updates the model), and a problem generator (explores). Learning is needed where rules cannot be hand-coded: perception, prediction, personalisation, and control.
4.2 Rote learning, learning by analogy, inductive learning, explanation-based learning, supervised and unsupervised learning, learning by evolution (genetic algorithm)
Rote learning: store the input and its result, then look it up. It requires no generalisation and cannot handle unseen inputs; caching and memoisation are practical forms. It is the baseline against which smarter methods are measured.
Learning by analogy: transform a known solution from a similar past case to fit the new problem — case-based reasoning. It needs a similarity metric, a retrieval mechanism, and an adaptation rule; it works well in domains with recurring structured cases (help desks, legal precedent) but inherits the weaknesses of its similarity measure.
Inductive learning: from examples, infer a general hypothesis that fits the data — the dominant paradigm. The classic algorithm is decision-tree induction (ID3/C4.5): choose the attribute with highest information gain, split, recurse, and prune. It trades bias (preference for simple trees, Occam's razor) against variance (overfitting noise).
Explanation-based learning: given one example plus a complete domain theory, generalise by explaining why the example is a goal instance and extracting the logically necessary conditions as a new rule. It is "one-shot" and does not need many examples, but needs an accurate theory and is sensitive to an incomplete one.
Supervised vs unsupervised: Supervised uses labelled examples to learn a mapping input → output; tasks are classification and regression; evaluation by held-out accuracy, precision/recall, or error. Unsupervised uses no labels to discover structure — clustering (k-means, hierarchical), dimensionality reduction (PCA), and association rules. Semi-supervised and reinforcement learning sit between, using partial labels or reward signals.
Learning by evolution (genetic algorithm): a population of candidate solutions encoded as chromosomes is evolved by selection (fitness-proportionate or tournament), crossover (recombination), and mutation, over generations. They suit large, rugged, non-differentiable search spaces; the cost is many evaluations and no optimality guarantee. Schema theory explains why building blocks survive.
Key terms
Hypothesis · bias-variance · overfitting · information gain · fitness function · elitism · clustering · reinforcement learning
Revision points
- Rote vs inductive vs explanation-based is a favourite three-way comparison: memory, many examples, one example plus theory.
- Supervised needs labels; unsupervised does not. State the task type that follows from that.
- GA components in order: encoding, fitness, selection, crossover, mutation, replacement.
Practice questions
- Distinguish supervised, unsupervised, and reinforcement learning with one task each.
- Why can explanation-based learning work from a single example, and what does it require?
- Describe the main steps of a genetic algorithm for maximising f(x) = x² on integers 0–31.
Answer notes: (1) Supervised: labelled data, e.g. spam classification. Unsupervised: unlabelled, e.g. customer segmentation by k-means. Reinforcement: reward from interaction, e.g. learning a game policy. (2) Because the domain theory lets the system prove that the example satisfies the goal and then generalise over the proof's sufficient conditions, rather than over many observations; it requires a correct and complete background theory and a well-defined goal concept. (3) Encode x as a 5-bit chromosome; initialise a random population; evaluate fitness x²; select by fitness; apply single-point crossover; mutate bits at a low rate; replace and repeat until convergence or a generation limit; return the best individual.
Worked example: Genetic algorithm for f(x) = x²
Problem: maximise f(x) = x² for x ∈ {0, 1, 2, ..., 31} using a genetic algorithm with 5-bit binary encoding.
Solution:
-
Encoding: Each candidate solution x is encoded as a 5-bit binary string (since 2^5 = 32 covers 0–31). A population of, say, 4 individuals is used.
-
Initial population (randomly generated):
- Individual 1: 01101 = 13, f(13) = 169
- Individual 2: 11000 = 24, f(24) = 576
- Individual 3: 00110 = 6, f(6) = 36
- Individual 4: 11111 = 31, f(31) = 961
-
Selection (fitness-proportionate, roulette wheel):
- Total fitness = 169 + 576 + 36 + 961 = 1742
- Probabilities: P(1) = 169/1742 ≈ 0.097, P(2) = 576/1742 ≈ 0.331, P(3) = 36/1742 ≈ 0.021, P(4) = 961/1742 ≈ 0.552
- Suppose selection yields: Individual 4 (31), Individual 2 (24), Individual 4 (31), Individual 2 (24) — the fitter individuals are more likely to be chosen.
-
Crossover (single-point, probability 0.8):
- Parent 1: 11111 (31)
- Parent 2: 11000 (24)
- Crossover point after bit 3:
- Offspring 1: 111|00 = 11100 = 28, f(28) = 784
- Offspring 2: 110|11 = 11011 = 27, f(27) = 729
-
Mutation (bit-flip probability 0.1 per bit):
- Offspring 1: 11100 → mutate bit 2 → 11000 = 24
- Offspring 2: 11011 → no mutation (all bits stay the same with probability 0.9^5 ≈ 0.59)
-
Replacement: Elitism carries Individual 4 (x = 31, f = 961) into the next generation unchanged; the remaining slots are filled by offspring such as x = 28 (f = 784) and x = 27 (f = 729) from the crossover above. The best-so-far remains x = 31 (f = 961). Without elitism, full replacement would discard x = 31 and the new generation's best could drop to x = 28 (f = 784) — worse than the starting best, which is why elitism is standard practice.
-
Repeat: Steps 3–6 are repeated for multiple generations. Over time, the population converges toward x = 31.
Intermediate result: After one generation, the offspring include x = 28 (f = 784) and x = 27 (f = 729), but with elitism the best-so-far remains x = 31 (f = 961). Without elitism, the new generation's best could be x = 28 (f = 784), which is worse than the initial best — showing why elitism prevents losing the best solution. With more generations, the GA would likely find x = 31 or very close to it.
Use case: Traffic pattern optimisation in Kathmandu
A city government in Kathmandu uses a genetic algorithm to optimise traffic light timing across a grid of intersections. The chromosome encodes the green-light duration for each approach at each intersection. The fitness function evaluates the total average waiting time across all vehicles in a simulated rush hour. Selection, crossover, and mutation evolve the timing parameters over hundreds of generations. The result is a near-optimal signal timing plan that reduces average waiting by 15% compared with the previous fixed-time plan. This illustrates how GAs can optimise real-world systems with many interacting parameters.
Mermaid diagram: Genetic algorithm flow
graph TD
A[Initialise Population] --> B[Evaluate Fitness]
B --> C{Convergence?}
C -->|No| D[Selection]
D --> E[Crossover]
E --> F[Mutation]
F --> B
C -->|Yes| G[Return Best Solution]
Explanation: The diagram shows the core GA loop: initialise a population of candidate solutions, evaluate each's fitness, check for convergence (e.g., fitness threshold or generation limit), and if not converged, perform selection (choose parents), crossover (combine parents), and mutation (introduce variation), then loop back to fitness evaluation. The best solution found is returned when convergence is achieved.
Common mistakes, limitations, and security concerns
- Mistake 1: Thinking "genetic algorithms always find the global optimum". GAs are heuristic; they often find good solutions but provide no guarantee of optimality. The result depends on parameter settings (population size, mutation rate, crossover rate) and the landscape of the fitness function.
- Mistake 2: Confusing "genetic algorithms" with "genetic programming". GAs optimise a population of values (usually binary-encoded); genetic programming evolves computer programs (tree structures) to solve a task.
- Mistake 3: Setting the mutation rate too high (e.g., 0.75), which turns the search into random walk and prevents convergence. Typical rates are 0.001–0.1 per bit.
- Limitation: GAs require many fitness evaluations, which can be expensive if the function is slow to compute. For such cases, surrogate models or Bayesian optimisation may be better.
- Security concern: In adversarial settings, a GA-based optimisation can be misled by a fitness function that is gamed or manipulated by an attacker. Validate the fitness function and consider robustness testing.
Exam-ready answer points
Short answer (1–2 marks):
- What are the three main types of machine learning: supervised, unsupervised, reinforcement?
- What is the difference between inductive learning and rote learning?
- What are the six components of a genetic algorithm (in order)?
- Name one difference between decision-tree induction and neural networks.
Long answer (5–10 marks):
- Compare supervised, unsupervised, and reinforcement learning with examples of each.
- Explain the bias-variance trade-off in inductive learning (decision trees): how pruning controls overfitting.
- Describe the main steps of a genetic algorithm and the role of each: encoding, fitness, selection, crossover, mutation, replacement.
- Explain explanation-based learning with an example, and contrast it with inductive learning (many examples vs. one example plus theory).
Diagram question:
- Draw the genetic algorithm loop: initialisation → evaluation → selection → crossover → mutation → check convergence.
- Draw a decision tree with the ID3 information-gain splitting criterion at each node.
Self-check questions (with answers)
-
Question: What is the difference between inductive learning and rote learning? Answer: Inductive learning infers a general hypothesis from many examples, allowing prediction on unseen inputs. Rote learning stores input–output pairs and only handles exact matches; it cannot generalise.
-
Question: List the six components of a genetic algorithm in the order they operate. Answer: Encoding, fitness evaluation, selection, crossover, mutation, replacement.
-
Question: What is the bias-variance trade-off? Answer: Bias is the error from overly simple models (underfitting); variance is the error from models that are too complex and fit noise (overfitting). A good model balances both. In decision trees, pruning reduces variance at the cost of increasing bias.
-
Question: Why does explanation-based learning need a "complete domain theory"? Answer: EBG generalises from a single example by extracting the logically necessary conditions that make the example a goal instance. If the domain theory is incomplete, the generalisation may be too specific or incorrect, covering cases it should not.
-
Question: Compare k-means clustering and hierarchical clustering. Answer: k-means partitions k clusters by minimising within-cluster sum of squares; it requires specifying k and works well for spherical clusters. Hierarchical clustering builds a tree of clusters (dendrogram) without requiring k, and can be agglomerative (bottom-up) or divisive (top-down).
-
Question: What is "elitism" in a genetic algorithm? Answer: Elitism is the practice of carrying the best individual(s) from one generation directly into the next, ensuring that the best fitness is not lost between generations.
-
Question: What is the function of the "problem generator" in a learning system? Answer: The problem generator explores new variations or modifies the learning scheme to discover more effective ways of improving performance, preventing the system from getting stuck in a local configuration.
-
Question: Why is reinforcement learning distinct from supervised learning? Answer: Reinforcement learning uses reward signals from interaction with an environment, without labelled input–output pairs. The agent must discover which actions lead to high reward through trial and error, whereas supervised learning has explicit correct answers for each example.
Unit 5: Neural Networks and Natural Language Processing
Teaching hours: 7
Topics in outline order
- Introduction to artificial neural networks
- Mathematical model of a neuron; types of networks: feed-forward, feed-back
- Gate realisation using neural networks
- Learning in neural networks: backpropagation
- Hopfield network; Boltzmann machines
- Natural language understanding and generation
- Steps in NLP: syntax analysis, semantic analysis, pragmatic analysis
Explanation
5.1 Introduction to artificial neural network, mathematical model, types of networks, gate realisation, backpropagation, Hopfield network, Boltzmann machines
A network of simple units inspired by neurons; each unit computes a weighted sum of inputs plus a bias, passes it through an activation function, and sends the result on. Networks learn by adjusting weights, giving them tolerance to noise and the ability to approximate non-linear functions. Drawbacks: opaque models, large data and compute needs, and risk of overfitting.
A neuron computes y = f(Σ wᵢxᵢ + b) where f may be a step, sigmoid, tanh, or ReLU. Feed-forward networks pass information one way (input → hidden → output) and are used for classification and regression. Feed-back (recurrent) networks have cycles, so their state depends on history — used for sequences and associative memory.
With a step activation, a perceptron realises AND (weights 1,1, bias −1.5) and OR (1,1, −0.5), and NOT (weight −1, bias 0.5). XOR is not linearly separable, which is the historical reason for hidden layers: two perceptrons in a hidden layer plus an output unit compute it.
Forward pass computes the output and loss; backward pass computes the gradient of the loss with respect to each weight by the chain rule, propagating error from output to input; weights are updated by gradient descent w ← w − η ∂L/∂w. Issues: local minima, slow convergence, and sensitivity to learning rate; remedies include momentum, adaptive learning rates (Adam), and better initialisation.
A Hopfield network is a fully connected recurrent network with symmetric weights and binary units, an energy function that decreases with each update, and associative memory behaviour: it stores patterns as energy minima and recalls a stored pattern from a noisy cue; capacity is about 0.14n patterns for n units. A Boltzmann machine is a stochastic recurrent network with visible and hidden units, where units are updated probabilistically according to their energy, so it can escape local minima and learn distributions; restricted Boltzmann machines (no visible-visible or hidden-hidden links) are the practical variant.
5.2 Concepts of natural language understanding and generation, steps in NLP: syntax analysis, semantic analysis, pragmatic analysis
Natural language understanding maps text or speech to meaning: intent, entities, and relations. Natural language generation maps meaning to text: content selection, sentence planning, and surface realisation. The pair is the two halves of any dialogue or translation system.
Lexical and morphological analysis (tokens, stems), syntactic analysis (parse tree, grammar, part of speech), semantic analysis (word sense, roles, truth conditions), pragmatic analysis (intent, context, implicature), and discourse analysis across sentences. Classic pipeline tools: POS taggers, chunkers, parsers, named-entity recognisers.
Key terms
Perceptron · activation function · hidden layer · gradient descent · energy function · attractor · corpus · parse tree · word sense disambiguation
Revision points
- Be ready to write the perceptron update rule and the XOR argument.
- Hopfield = associative memory, energy minimisation; Boltzmann = stochastic, distribution learning.
- Distinguish syntax (structure), semantics (meaning), pragmatics (intended meaning in context) with one example each.
Practice questions
- Show that a single perceptron cannot compute XOR, and give a two-layer network that can.
- Outline backpropagation for one hidden layer, naming what is computed in each pass.
- Differentiate syntax, semantics, and pragmatics with the sentence "Can you open the window?"
Answer notes: (1) XOR's positive and negative examples are not separable by one line, so no single threshold works. Hidden units h1 = OR(x1,x2), h2 = NAND(x1,x2), output = AND(h1,h2) gives XOR. (2) Forward: compute activations layer by layer and the output error. Backward: compute output deltas, propagate deltas to the hidden layer via the transposed weights, accumulate weight gradients, and update with the learning rate. Repeat over epochs. (3) Syntax: interrogative structure with modal + subject + verb + object. Semantics: a question about the listener's ability to open the window. Pragmatics: in most contexts it is a request to open the window, not a question about ability.
Worked example: Perceptron cannot compute XOR
Problem: Prove that a single-layer perceptron (single neuron with step activation) cannot compute the XOR function, and describe a two-layer network that can.
Solution:
-
Single perceptron limitation. A single perceptron computes
y = step(w₁x₁ + w₂x₂ + b), where step outputs 1 if the weighted sum exceeds threshold t, and 0 otherwise. The decision boundary is a straight line (in 2D) — a linear separator. XOR outputs 1 when exactly one input is 1: XOR(0,0) = 0, XOR(0,1) = 1, XOR(1,0) = 1, XOR(1,1) = 0. The four points (0,0), (0,1), (1,0), (1,1) cannot be separated by a single straight line into the two classes {0} and {1}. Therefore, a single perceptron cannot compute XOR. -
Two-layer network for XOR. A network with two hidden units and one output unit can compute XOR:
- Hidden unit h1: OR unit with weights (1, 1) and bias −0.5 → outputs 1 if x1 = 1 or x2 = 1 (or both).
- Hidden unit h2: NAND unit with weights (−1, −1) and bias 1.5 → outputs 1 unless both x1 = 1 and x2 = 1.
- Output unit: AND of h1 and h2 → outputs 1 only when h1 = 1 and h2 = 1.
Truth table verification:
x1 x2 h1 = OR(x1,x2) h2 = NAND(x1,x2) output = AND(h1,h2) = XOR(x1,x2) 0 0 0 1 0 0 1 1 1 1 1 0 1 1 1 1 1 1 0 0 Swipe to see all columns
The two-layer network correctly computes XOR in all four cases.
Intermediate result: A single-layer perceptron is limited to linear decision boundaries and cannot compute XOR. A two-layer network with OR and NAND hidden units plus an AND output unit correctly implements XOR.
Use case: Speech recognition for Nepali language
A team is building a speech-to-text system for the Nepali language. The front-end extracts Mel-frequency cepstral coefficients (MFCCs) from audio frames. A feed-forward neural network (or a CNN) classifies phonemes. A recurrent neural network (LSTM) models the sequence of phonemes to handle co-articulation. The system is trained on a corpus of recorded Nepali sentences with transcriptions. This illustrates how neural networks (feed-forward, recurrent) are used for NLU (speech-to-text) in a low-resource language context.
Mermaid diagram: Perceptron XOR argument
graph TB
A[Single Perceptron] --> B[Decision Boundary: straight line]
B --> C{XOR points: (0,0), (0,1), (1,0), (1,1)}
C -->|Cannot be separated| D[Not linearly separable]
C -->|One straight line| E[Impossible]
D -->|Two-layer network| F[Hidden h1: OR]
D -->|Hidden h2: NAND|
F --> G[Output: AND(h1, h2)]
G --> H[XOR computed correctly]
Explanation: The diagram illustrates why a single perceptron cannot compute XOR: the four XOR input-output pairs are not linearly separable (no single straight line can separate the 0-output points from the 1-output points). A two-layer network with OR and NAND hidden units plus an AND output unit overcomes this by creating a non-linear decision boundary.
Common mistakes, limitations, and security concerns
- Mistake 1: Saying "neural networks always learn the right function". Neural networks can overfit the training data, get stuck in local minima, or fail to converge if the learning rate is poorly chosen. Regularisation, cross-validation, and sufficient data are essential.
- Mistake 2: Thinking "more hidden layers always mean better performance". Deep networks are harder to train (vanishing/exploding gradients) and may overfit. Residual connections, batch normalisation, and proper architecture design are needed.
- Mistake 3: Confusing "syntax" and "semantics" in NLP. Syntax is about sentence structure (grammar); semantics is about meaning (word sense, truth conditions). They are related but distinct.
- Limitation: NLP systems struggle with ambiguity, sarcasm, and low-resource languages without large annotated corpora.
- Security concern: NLP models that process user-generated text can be vulnerable to adversarial attacks (e.g., subtle character changes that flip the model's classification). Input validation and model robustness testing are important.
Exam-ready answer points
Short answer (1–2 marks):
- What is the perceptron update rule? (w ← w + η(t − y)x, where t is the target, y is the output, x is the input, and η is the learning rate)
- What is the XOR problem, and why does it motivate hidden layers?
- Distinguish syntax, semantics, and pragmatics with one example each.
- What activation functions are commonly used in neural networks? (step, sigmoid, tanh, ReLU)
Long answer (5–10 marks):
- Explain the backpropagation algorithm: forward pass (compute activations and loss), backward pass (compute gradients via chain rule), weight update (gradient descent).
- Describe the Perceptron learning rule and its convergence property (converges if the data is linearly separable).
- Compare feed-forward and recurrent networks: feed-forward processes input once; recurrent networks have cycles and maintain state.
- Differentiate syntax, semantics, and pragmatics with a detailed example.
Diagram question:
- Draw the perceptron model: weighted inputs, bias, activation function, output.
- Draw the two-layer XOR network with hidden OR and NAND units and AND output.
- Draw the backpropagation flowchart: forward pass → compute loss → backward pass → compute gradients → update weights.
Self-check questions (with answers)
-
Question: What is the perceptron learning rule? Answer: w ← w + η(t − y)x, where w is the weight vector, η is the learning rate, t is the target output, y is the actual output, and x is the input vector. The weights are adjusted in the direction that reduces the error.
-
Question: Why can't a single perceptron compute XOR? Answer: XOR's four input-output pairs are not linearly separable; no single straight line can divide the (0,0) point from the (0,1), (1,0), and (1,1) points. A single perceptron's decision boundary is a straight line.
-
Question: Differentiate syntax, semantics, and pragmatics with the sentence "What time is it?". Answer: Syntax: the grammatical structure (interrogative with modal + subject + verb). Semantics: the question asks for the current time. Pragmatics: in most contexts, it is a polite request, not a genuine question about the time.
-
Question: What is the role of the activation function in a neural network? Answer: The activation function introduces non-linearity into the neuron's output, allowing the network to approximate non-linear functions. Without activation functions, a multi-layer network would be equivalent to a single-layer network.
-
Question: Compare the Hopfield network and the Boltzmann machine. Answer: Hopfield is deterministic, fully connected with symmetric weights, and uses energy minimisation for associative memory. Boltzmann is stochastic, uses probabilistic unit updates, and can learn probability distributions over data. Restricted Boltzmann machines (RBMs) remove visible-visible and hidden-hidden connections for practical learning.
-
Question: What is the backpropagation algorithm, and what are its two main passes? Answer: Backpropagation is the standard algorithm for training neural networks. The forward pass computes the output and the loss; the backward pass computes the gradient of the loss with respect to each weight by the chain rule, propagating error from the output layer back to the input layer.
-
Question: What is the difference between a feed-forward network and a recurrent network? Answer: A feed-forward network processes information in one direction (input → output) without cycles. A recurrent network has cycles, so its output depends on previous inputs (memory/state), making it suitable for sequences and time series.
-
Question: What is the role of the learning rate in gradient descent? Answer: The learning rate (η) controls the step size of each weight update. Too large a learning rate may overshoot the minimum and fail to converge; too small a learning rate may take too many iterations to converge.
Unit 6: Expert System and Machine Vision
Teaching hours: 4
Topics in outline order
- Expert system: concept, architecture, stages of development
- Concept of machine vision; steps of machine vision; applications
- Knowledge acquisition and the bottleneck
Explanation
6.1 Expert system: concept, architecture, stages of development, knowledge acquisition and the bottleneck
A program that reproduces the decision-making of a human expert in a narrow domain, using encoded domain knowledge and an inference engine, and able to explain its reasoning. It suits domains with well-defined rules and scarce expertise (medical diagnosis, equipment fault diagnosis, tax advisory, credit approval).
Knowledge base (facts and rules), inference engine (forward or backward chaining), working memory (current facts), user interface, explanation facility (why/how), and knowledge acquisition module (the interface to the expert that builds and maintains the base). Some descriptions add a case base or a learning module.
Problem identification and feasibility → knowledge acquisition from experts and documents → knowledge representation (rules, frames, logic) → prototype construction → testing and validation against expert cases → refinement and maintenance → deployment and training. The dominant risks are knowledge-acquisition bottlenecks, brittleness outside the covered domain, and maintenance as rules accumulate.
The knowledge-acquisition bottleneck is the fact that eliciting, encoding, and validating expert knowledge typically takes 60–80% of project time and cost. It occurs because expert knowledge is often tacit, experience-based, and difficult to articulate in formal rules.
6.2 Concept of machine vision; steps of machine vision; applications
Machine vision gives a system the ability to acquire, process, and interpret images to make decisions. It differs from image processing by ending in a decision, and from computer vision mainly by its industrial-engineering emphasis on speed, repeatability, and integration with control.
Image acquisition (camera, lighting, optics) → pre-processing (denoising, filtering, contrast) → segmentation (thresholding, edge detection, region growing) → feature extraction (shape, texture, colour, position) → classification or measurement → decision and actuation (accept/reject, robot guidance).
Quality inspection on production lines, defect detection, dimension measurement, robotic pick-and-place, optical character recognition, barcode reading, agricultural sorting, medical imaging support, and traffic monitoring. Limitations: lighting sensitivity, calibration and maintenance cost, and difficulty with variable or deformable objects.
Key terms
Knowledge base · inference engine · explanation facility · forward vs backward chaining · brittleness · segmentation · feature vector · illumination
Revision points
- Draw the expert-system block diagram from memory; arrows matter (user → interface → inference engine ↔ knowledge base, plus explanation).
- Forward chaining is data-driven, backward is goal-driven — link this to diagnosis vs design tasks.
- Machine vision always ends in a decision; that is the distinction to state first.
Practice questions
- Draw and explain the architecture of an expert system, and state where the explanation facility gets its information.
- Why is knowledge acquisition called the bottleneck of expert-system development?
- List the steps of a machine-vision system for detecting surface defects on metal sheets.
Answer notes: (1) Knowledge base and working memory feed an inference engine that the user reaches through the interface; the explanation facility records the rule chain fired, so it can answer "why" (which rule is being considered) and "how" (which rules derived a conclusion). (2) Domain expertise is tacit, expensive to elicit, hard to validate, and changes over time; encoding it into rules takes most of the project effort and is the main cause of cost overrun and failure. (3) Controlled illumination and camera acquisition → filtering and contrast enhancement → segmentation of defect regions → feature extraction (area, shape, texture) → classifier with a threshold → accept/reject signal to the line.
Worked example: Expert system for crop disease diagnosis
Problem: Design a simple expert system to diagnose a few common crop diseases based on symptoms, and identify where the knowledge acquisition bottleneck would occur.
Solution:
-
Domain: Crop diseases in wheat (common in Nepal): leaf rust, powdery mildew, and bacterial leaf blight.
-
Knowledge base (encoded as IF-THEN rules):
- Rule 1: IF leaves have reddish-brown pustules THEN leaf rust.
- Rule 2: IF leaves have white powdery spots THEN powdery mildew.
- Rule 3: IF leaves have yellowish-water-soaked lesions WITH a wet atmosphere THEN bacterial leaf blight.
-
Inference engine: Uses forward chaining. Given observed symptoms (e.g., "leaves have reddish-brown pustules"), the engine fires Rule 1 and concludes "leaf rust".
-
User interface: Presents the question "Do the leaves have reddish-brown pustules? (yes/no)" and shows the diagnosis.
-
Explanation facility: When "leaf rust" is diagnosed, the facility reports "Rule 1 was fired because the symptom 'leaves have reddish-brown pustules' was provided."
-
Knowledge acquisition bottleneck: Eliciting the rules from wheat farmers and agricultural officers is difficult because (a) disease symptoms can look similar to the untrained eye, (b) the knowledge is tacit and experienced-based, (c) symptoms vary with weather and growth stage, and (d) the expert may not articulate the rules explicitly. Most project effort (60–80%) goes into encoding the knowledge, and maintaining the system as new diseases emerge is an ongoing cost.
Use case: Optical character recognition for Nepali script
A project to digitise ancient Nepali manuscripts uses a machine vision system. The steps are:
- Image acquisition: High-resolution grayscale scans of the manuscript pages.
- Pre-processing: Despeckling, contrast adjustment, and binarisation (Otsu's method).
- Segmentation: Connected-component analysis to isolate individual characters; line and word detection.
- Feature extraction: Shape features (stroke count, curvature, loop presence) for each character.
- Classification: A k-NN classifier trained on labelled Nepali script characters.
- Decision: The recognised character string is output, and the text is searched or indexed.
The system achieves 85% character accuracy, which is limited by ink fading, varying handwriting styles, and paper degradation. This illustrates how machine vision steps are applied in a real-world low-resource context.
Mermaid diagram: Expert system architecture
graph TB
A[User Interface] --> B[Inference Engine]
B <--> C[Knowledge Base]
B --> D[Explanation Facility]
C --> D
Explanation: The diagram shows the core expert system architecture. The user interface interacts with the inference engine, which reasons over the knowledge base. The explanation facility gets its information from both the inference engine (which rule chain is active) and the knowledge base (what rules and facts are stored). The knowledge base and inference engine are bidirectional: the engine both reads from and adds to the knowledge base (during explanation or maintenance).
Common mistakes, limitations, and security concerns
- Mistake 1: Thinking "any domain can be captured in an expert system". Domains with vague boundaries, contradictory expert opinions, or rapidly changing knowledge are poor candidates. Expert systems work best in well-defined, stable domains.
- Mistake 2: Underestimating the knowledge-acquisition bottleneck. Eliciting, encoding, and validating expert knowledge typically takes 60–80% of project time and cost. Skipping this step leads to a brittle, unreliable system.
- Mistake 3: Confusing "machine vision" with "computer vision". Machine vision is engineering-focused: it ends in a decision (accept/reject) and emphasises speed, repeatability, and integration. Computer vision is research-focused: it aims to interpret images at a human or super-human level.
- Limitation: Expert systems are brittle outside their covered domain. A single exception or out-of-scope case can cause the system to produce incorrect or meaningless output.
- Security concern: In critical domains (medical diagnosis, financial advisory), incorrect outputs can cause harm. The system should always include a human-in-the-loop, and the knowledge base should be regularly validated against real-world cases.
Exam-ready answer points
Short answer (1–2 marks):
- What are the six components of an expert system architecture?
- What is the difference between forward chaining and backward chaining?
- What distinguishes machine vision from computer vision?
- Name three applications of machine vision.
Long answer (5–10 marks):
- Describe the expert system development life cycle: from problem identification to deployment and maintenance.
- Explain the expert system architecture with the knowledge base, inference engine, working memory, user interface, and explanation facility.
- Explain why knowledge acquisition is the bottleneck and what makes a domain suitable (or unsuitable) for an expert system.
- Describe the machine vision pipeline: from image acquisition to decision and actuation.
Diagram question:
- Draw the expert system block diagram from memory.
- Draw the machine vision pipeline with all six steps labeled.
Self-check questions (with answers)
-
Question: What are the six main components of an expert system? Answer: Knowledge base, inference engine, working memory, user interface, explanation facility, and knowledge acquisition module.
-
Question: Differentiate forward chaining and backward chaining. Answer: Forward chaining starts from the given facts and derives new conclusions (data-driven), stopping when no new facts can be derived or the query is supported. Backward chaining starts from the query and works backward to find supporting facts (goal-driven), commonly used in Prolog.
-
Question: What is the "knowledge acquisition bottleneck" and why does it occur? Answer: The knowledge acquisition bottleneck is the fact that eliciting, encoding, and validating expert knowledge typically takes 60–80% of project time and cost. It occurs because expert knowledge is often tacit, experience-based, and difficult to articulate in formal rules.
-
Question: List the machine vision pipeline steps in order. Answer: Image acquisition → pre-processing → segmentation → feature extraction → classification → decision and actuation.
-
Question: What is the difference between "image processing" and "machine vision"? Answer: Image processing transforms an image (e.g., filtering, enhancement) without necessarily making a decision. Machine vision acquires, processes, and interprets images to make a decision or take an action, emphasising speed, repeatability, and integration with control systems.
-
Question: Why should an expert system include a human-in-the-loop in critical domains? Answer: Expert systems can be brittle outside their covered domain and may produce incorrect output. A human-in-the-loop ensures that the system's recommendations are validated, especially in domains like medical diagnosis or financial advisory where errors cause harm.
-
Question: What is the explanation facility in an expert system, and how does it generate explanations? Answer: The explanation facility records the rule chain fired during inference and can answer "why" (which rule is being considered) and "how" (which rules derived the conclusion). It provides transparency and helps the user understand the system's reasoning.
-
Question: What are the limitations of machine vision in real-world deployments? Answer: Machine vision is sensitive to lighting changes, requires careful calibration, has high maintenance costs (camera cleaning, lens replacement), and struggles with variable or deformable objects (e.g., parts that differ slightly between units).
Exam Strategy
- Draw the state-space graph before tracing any search; label g, h, and f values in a table.
- For resolution proofs, list clauses in numbered form and cite the parents of each resolvent.
- Attempt the numerical probability question (Bayes, joint distribution) — it is usually the most predictable full-mark question in Unit 3.
- Keep definitions short and spend the space on the trace or the diagram.
References
- TU document: https://portal.tu.edu.np/downloads/BCA_Syllabus-compressed_compre_2024_01_30_18_33_22.pdf
- Location: PDF p. 128-131
- SHA-256: sha256:d126d513c1051b176b03e56e067608546786d279b596b7b431ecff4d944496cb
This guide is derived from an earlier TU syllabus outline (CACS410) for BCA302 Artificial Intelligence. The available compilation contains sections printed in different years. The 2025 TU curriculum lists this course in the semester 5 structure but does not publish a detailed unit outline. This guide follows the archived outline and is not a statement of official 2025 TU wording.