AI_ML Notes ALL_MODULE RVS
AI_ML Notes ALL_MODULE RVS
FOLLOW THIS SYLLABUS AND THE NOTES FOR YOUR JUT UNIVERSITY EXAM.
UNIT I: Introduction to AI, Intelligent Agents and Search
A commonly used definition, given by Elaine Rich, is: 'Artificial Intelligence is the study of how to make computers
do things which, at the moment, people do better.' AI systems are generally judged along two dimensions —
thinking vs acting, and humanly vs rationally — which gives us four categories of definitions:
1.1 History of AI
The history of AI can be understood as a series of waves of optimism and 'AI winters' (periods of reduced funding
and interest):
• 1943 — McCulloch and Pitts proposed the first mathematical model of an artificial neuron, laying the
foundation of neural networks.
• 1950 — Alan Turing published 'Computing Machinery and Intelligence' and proposed the Turing Test to
judge machine intelligence.
• 1956 — The Dartmouth Conference, organised by John McCarthy, Marvin Minsky, Claude Shannon and
others, is regarded as the official birth of AI as a field; the term 'Artificial Intelligence' was coined here.
• 1956–1974 — The 'golden years': early programs like the Logic Theorist and General Problem Solver were
developed; expectations were very high.
• 1974–1980 — First AI Winter: progress slowed because of limited computing power and unrealistic
promises, so funding was cut.
• 1980–1987 — Rise of Expert Systems (e.g., MYCIN, DENDRAL) that used rule-based knowledge to solve
domain-specific problems; commercial interest returned.
• 1987–1993 — Second AI Winter caused by the collapse of the specialised Lisp-machine market and the
limitations of expert systems.
• 1993–2011 — AI became more mathematical, with strong growth in machine learning, probabilistic
reasoning (Bayesian networks), and intelligent agents.
• 2011–present — The Deep Learning era: with the availability of big data, GPUs, and better algorithms, AI
achieved breakthroughs in image recognition, speech recognition, game playing (AlphaGo), and natural
language processing (large language models).
Exam Tip: Questions on 'History of AI' are commonly asked for 2–3 marks. Remember the Dartmouth Conference
(1956) as the official birth year, and the two AI winters.
2. Agents
An agent is anything that can be viewed as perceiving its environment through sensors and acting upon that
environment through actuators. This is one of the most fundamental concepts in AI because almost every AI
system (a robot, a chatbot, a game-playing program, a thermostat) can be modelled as an agent.
Fig 2.1: The Agent interacts with its Environment through sensors (percepts) and actuators (actions).
For example, a human agent has eyes, ears, and other organs as sensors, and hands, legs, and vocal tract as
actuators. A robotic agent might have cameras and infrared range finders as sensors, and motors as actuators. A
software agent receives file contents, keystrokes, or network packets as percepts, and acts by displaying output
on the screen, writing files, or sending network packets.
Note that rationality is not the same as omniscience or perfection — a rational agent can still make mistakes if the
outcome is genuinely unpredictable, but it must act reasonably given the information available to it.
Example: A thermostat is a simple reflex agent — if the temperature falls below the set point, turn the heater ON;
if it rises above the set point, turn it OFF. It does not remember past temperatures; it only reacts to the present
percept.
3.2 Model-Based Reflex Agents
A model-based reflex agent keeps track of the part of the world it cannot currently see by maintaining an internal
state. This internal state is updated over time using knowledge of how the world evolves (a 'transition model') and
how the agent's own actions affect the world. This allows the agent to handle partial observability, which a simple
reflex agent cannot.
Example: A self-driving car uses a model-based reflex agent approach — even when a pedestrian momentarily
passes behind another vehicle (occluded from the camera), the internal model keeps track of where the
pedestrian is likely to be.
Example: A GPS navigation system is goal-based — given the goal 'reach the destination', it searches through
possible routes and selects the sequence of turns that achieves the goal, and it can easily be given a new goal (a
different destination).
Example: A ride-sharing app's route-planning algorithm is utility-based — it does not just find 'a' route to the
destination (the goal) but the one that best balances time, fuel cost, and tolls (utility).
Example: A spam-email filter is a learning agent — the performance element classifies emails as spam or not spam,
and the learning element updates its rules whenever the user marks a wrongly-classified email, so the filter's
accuracy keeps improving.
4. Environments
The environment is everything that surrounds the agent and with which the agent interacts. Before designing an
agent, it is essential to understand the properties of its task environment (often abbreviated as the PEAS
description: Performance measure, Environment, Actuators, Sensors). Environments can be classified along
several dimensions:
• Fully Observable vs Partially Observable: In a fully observable environment, the agent's sensors give it
access to the complete state of the environment at each point in time (e.g., chess). In a partially observable
environment, sensors give only noisy or incomplete information (e.g., a self-driving car cannot see around
a blind corner).
• Deterministic vs Stochastic: In a deterministic environment, the next state is completely determined by the
current state and the agent's action (e.g., a puzzle like the 8-puzzle). In a stochastic environment, there is
randomness / uncertainty in outcomes (e.g., dice games, taxi driving with unpredictable traffic).
• Episodic vs Sequential: In an episodic environment, the agent's experience is divided into atomic 'episodes'
where the choice of action in each episode depends only on the episode itself (e.g., defect-detection on an
assembly line). In a sequential environment, the current decision can affect all future decisions (e.g., chess,
where every move affects the rest of the game).
• Static vs Dynamic: A static environment does not change while the agent is deliberating (e.g., crossword
puzzles). A dynamic environment can change during the agent's decision-making (e.g., driving a car, where
other vehicles keep moving).
• Discrete vs Continuous: A discrete environment has a finite/countable number of distinct states and actions
(e.g., chess board positions). A continuous environment has states and actions that vary smoothly (e.g.,
robot arm angles, taxi driving speed).
• Single-Agent vs Multi-Agent: A single-agent environment has only one agent acting (e.g., solving a
crossword alone). A multi-agent environment has multiple agents that may cooperate or compete (e.g.,
chess is a two-agent, competitive environment).
• Known vs Unknown: This refers to the agent's (or designer's) state of knowledge about the 'rules' of the
environment, not the state of the environment itself.
Example (PEAS for a self-driving taxi): Performance measure — safety, speed, legal driving, comfort, profit;
Environment — roads, traffic, pedestrians, weather; Actuators — steering, accelerator, brake, horn, display;
Sensors — cameras, GPS, speedometer, sonar, engine sensors. The taxi environment is partially observable,
stochastic, sequential, dynamic, continuous, and multi-agent.
1. Goal Formulation: based on the current situation, the agent decides what it wants to achieve.
2. Problem Formulation: the agent decides what actions and states to consider given the goal (abstracting
away irrelevant detail).
3. Search: the agent simulates sequences of actions in its model to find a path from the initial state to the goal
— this produces a solution.
4. Execution: the agent carries out the actions recommended by the solution, one at a time.
Example: Consider a tourist in Chandigarh who wants to reach Delhi. Goal formulation: 'Be in Delhi.' Problem
formulation: states are cities, actions are drives between adjacent cities. Search: the agent examines route options
(via a map) to find a sequence of cities forming a path to Delhi. Execution: the tourist actually drives the chosen
route.
6. Formulating Problems
Formally, a search problem can be defined using five components:
Example — The 8-puzzle: States describe the arrangement of 8 numbered tiles and a blank on a 3x3 board; Initial
state is the given (scrambled) arrangement; Actions move the blank Left/Right/Up/Down; Transition model gives
the resulting arrangement; Goal test checks whether the arrangement matches the target configuration; Path cost
is usually the number of moves (each move costs 1).
7. Search Strategies
A search strategy is defined by picking the order in which nodes are expanded. Search strategies are broadly
divided into two categories:
• Uninformed (Blind) Search: has no additional information about states beyond that provided in the problem
definition. These strategies can only generate successors and distinguish a goal state from a non-goal state.
Examples: BFS, Uniform Cost Search, DFS, Depth-Limited Search, Iterative Deepening, Bidirectional Search.
• Informed (Heuristic) Search: uses problem-specific extra knowledge (a heuristic function) beyond the
problem definition, which helps find solutions more efficiently. Examples: Best-First Search, A*, SMA*, Hill
Climbing, Simulated Annealing.
The performance of a search strategy is evaluated on four criteria, which is exactly the 'Measure of Performance
and Analysis of Search Algorithms' topic covered later in this unit: Completeness, Optimality, Time Complexity,
and Space Complexity.
Fig 7.1: BFS visits nodes level by level (left) while DFS dives deep along one branch first (right).
Properties: BFS is complete (it will find a solution if one exists, provided the branching factor is finite) and it is
optimal if all step costs are equal, because it always finds the shallowest goal node first. However, its time and
space complexity are both O(b^d), where b is the branching factor and d is the depth of the shallowest solution
— this exponential space requirement is BFS's biggest drawback, as the frontier can become extremely large.
Example: Finding the minimum number of moves to solve a puzzle, or finding the shortest friend-chain between
two people in a social network (all edges have equal 'cost'), is naturally solved with BFS.
UCS is complete and optimal, provided step costs are all greater than or equal to some small positive constant. Its
time and space complexity is O(b^(1+floor(C*/ε))), where C* is the cost of the optimal solution and ε is the
minimum step cost — which can be much worse than b^d if there are many small steps.
Example: Finding the cheapest flight route between two cities, where each flight leg has a different ticket price, is
solved with UCS rather than plain BFS.
DFS has modest memory requirements — it only needs to store the path from the root to the current node, plus
the unexpanded sibling nodes, giving a space complexity of O(bm), where m is the maximum depth of the tree —
much better than BFS's O(b^d). However, DFS is not complete in infinite state spaces (it can get stuck going down
an infinitely deep or looping path), and it is not optimal, because it may find a longer / costlier solution before a
shorter one. Its worst-case time complexity is O(b^m).
Example: Finding the shortest route between two cities on a large road map is often done bidirectionally —
searching outward from both the source city and the destination city simultaneously.
A heuristic is called admissible if it never overestimates the true cost to reach the goal — i.e., h(n) <= h*(n), where
h*(n) is the actual optimal cost from n to the goal. A heuristic is called consistent (or monotonic) if, for every node
n and every successor n' generated by action a, h(n) <= c(n,a,n') + h(n'), i.e., the estimated cost does not decrease
by more than the actual step cost. Every consistent heuristic is also admissible.
• Greedy Best-First Search: uses f(n) = h(n) only, always expanding the node that appears closest to the goal.
It is fast, but not complete (can get stuck in loops) and not optimal, because it ignores the cost already spent
to reach n.
• A* Search: uses f(n) = g(n) + h(n), where g(n) is the actual cost so far to reach n, and h(n) is the estimated
cost from n to the goal. This is the most widely used informed search algorithm.
8.3 A* Search
A* Search evaluates nodes using f(n) = g(n) + h(n): g(n) is the exact cost from the start to node n, and h(n) is the
heuristic estimate of the cost from n to the nearest goal. Because f(n) estimates the total cost of the cheapest
solution through n, A* expands the node that is likely to be on the cheapest overall path.
Key result: A* using Tree-Search is optimal if h(n) is admissible; A* using Graph-Search is optimal if h(n) is
consistent. Because f-values are non-decreasing along any path (when h is consistent), A* is guaranteed to find
the optimal solution. However, A*'s memory usage is still exponential in the worst case, since it keeps all
generated nodes in memory.
Example: A* is used in GPS navigation software and video-game pathfinding, where straight-line distance to the
destination serves as h(n), guiding the search efficiently while still finding the shortest actual route.
• Iterative-Deepening A* (IDA*): performs iterative deepening using f(n) = g(n)+h(n) as the cutoff instead of
depth, keeping memory usage linear.
• Recursive Best-First Search (RBFS): mimics best-first search using only linear space, by keeping track of the
f-value of the best alternative path available from any ancestor of the current node.
• Simplified Memory-Bounded A* (SMA*): SMA* behaves like A* until memory is full. When memory runs
out, it drops the leaf node with the highest f-value (the worst node) from the frontier to free up space, and
'backs up' the forgotten value into its parent, so that the parent remembers the best value of its forgotten
children. This lets SMA* make full use of whatever memory is available, and it is complete if there is enough
memory to store the shallowest solution path, and optimal if enough memory is available to store the best
solution path.
Exam Tip: SMA* is a favourite viva/theory question: remember it 'forgets the worst node and remembers its value
at the parent' when memory is full — this is the key differentiator from plain A*.
Fig 9.1: Hill Climbing can get trapped in a local maximum instead of reaching the global maximum.
• Local Maxima: a peak that is higher than all its neighbours but lower than the global maximum — once
here, hill climbing cannot escape because all neighbouring moves make things worse.
• Plateaus: a flat area of the state-space landscape where all neighbouring states have the same value, so the
algorithm has no direction to move in and effectively gets stuck wandering.
• Ridges: a sequence of local maxima that is very difficult to navigate because the orientation of the ridge
compared to the available moves makes progress slow, even though the overall trend leads upward.
Variants used to mitigate these problems include Stochastic Hill Climbing (chooses randomly among better
neighbours, weighted by improvement), First-Choice Hill Climbing (generates neighbours randomly until one is
found that is better than the current state), and Random-Restart Hill Climbing (runs hill climbing multiple times
from randomly generated initial states and keeps the best result).
Example: In the 8-queens problem, hill climbing starts with a random arrangement of 8 queens on the board and
repeatedly moves one queen to the position within its column that most reduces the number of attacking pairs,
until no single move can reduce it further.
At high temperature, the algorithm behaves almost like a random walk (lots of exploration, escaping local maxima
easily); as T decreases towards zero, the algorithm behaves more and more like hill climbing (mostly exploiting
good moves). It can be proven that if T is lowered slowly enough, simulated annealing will find the global optimum
with probability approaching 1. This is why simulated annealing is widely used for large combinatorial optimisation
problems such as VLSI layout, scheduling and the travelling-salesman problem.
Note: b = branching factor, d = depth of shallowest solution, m = maximum depth of the state space, l = depth
limit, C* = cost of the optimal solution, ε = smallest step cost.
Exam Tip: This comparison table is an excellent quick-revision tool and is often directly asked as a university
question — memorise the complexity column carefully.
UNIT II: Game Playing and Knowledge Representation using Logic
1. Game Playing
Games have historically been an important application area for AI because they provide a well-defined,
competitive environment that is easy to formalise, yet extremely hard to solve completely — for example, chess
has roughly 10^40 legal positions. Games are typically modelled as a search problem involving two players (usually
called MAX and MIN) who move alternately, and where each player tries to maximise their own outcome while
minimising the opponent's.
A game can be formally defined using the following components: the Initial State (board setup and whose turn it
is), a function TO-MOVE(state) that indicates which player moves, ACTIONS(state) giving the legal moves,
RESULT(state, move) the transition model, IS-TERMINAL(state) that checks whether the game has ended, and
UTILITY(state, player) which gives a numeric value for the outcome of a terminal state (for example, +1 for a win,
-1 for a loss, 0 for a draw in chess).
Additional practical techniques include Quiescence Search (extending the search at 'unstable' positions, such as
right after a capture, so the evaluation is not misleading) and Forward Pruning (discarding moves that appear
clearly bad without fully evaluating them, to save time).
Fig 1.1: Alpha-Beta Pruning avoids evaluating branches (dashed) that cannot affect the final MAX decision.
In the best case (when moves happen to be ordered so that the best move is examined first), alpha-beta pruning
reduces the time complexity from O(b^m) to O(b^(m/2)) — effectively doubling the depth that can be searched
in the same amount of time compared to plain minimax. This is why alpha-beta pruning, rather than plain minimax,
is used in essentially every practical game-playing program.
Worked example: In Figure 1.1, the MAX node has three MIN children. The first MIN child evaluates its two leaves
(3 and 5) and returns 3. The second MIN child evaluates its first leaf (6); since MAX already has a guaranteed 3,
and this branch already offers 6 (>=3, so it could still help) — after seeing the second leaf (9) the branch returns
6. The third MIN child evaluates its first leaf (1); since MAX already has a value of 6 from the second branch, and
this branch already can only give at most 1 so far (which is worse for MAX than the guaranteed 6), the second leaf
under this branch can be pruned — there is no need to evaluate it because it cannot change MAX's final decision
of 6.
Exam Tip: Alpha-beta pruning always gives the same answer as minimax; only the amount of computation changes
— this line ('same result, less work') is a favourite exam distinction.
2. Knowledge-Based Agents
A knowledge-based agent is one whose central component is a Knowledge Base (KB) — a set of sentences
expressed in some formal representation language (typically a form of logic) that represents facts about the world
that the agent believes to be true. The agent operates using two main functions: TELL, which adds new sentences
(percepts, facts) into the KB, and ASK, which queries the KB to determine what action to take, and the agent
decides on actions by performing logical inference over its KB — deriving new sentences from old ones using rules
of logic.
At an abstract level, a knowledge-based agent can be described in three steps for every time step: (1) it TELLs the
KB what it has perceived, (2) it ASKs the KB what action it should perform (using logical reasoning combined with
the goal), and (3) it TELLs the KB which action was chosen, and then performs it. This design lets the agent be built
by simply adding sentences to the KB, at what is called the 'knowledge level' — describing what the agent knows,
independent of how it is implemented.
The advantages of the knowledge-based approach include: the agent can be told new facts directly (learning does
not require reprogramming), the agent can combine facts to reach new conclusions it was never explicitly told,
and the agent's behaviour is transparent and can be explained by showing the chain of logical deductions.
Fig 3.1: A sample Wumpus World — percepts like 'Breeze' and 'Stench' warn the agent about nearby pits and the Wumpus.
• Performance measure: +1000 for climbing out of the cave with the gold, -1000 for being eaten by the
Wumpus or falling into a pit, -1 for each action taken, and -10 for using the single available arrow.
• Environment: a 4x4 grid of rooms; the agent starts in the room at bottom-left [1,1], facing east; the locations
of the Wumpus, pits, and gold are randomly assigned to other squares.
• Actuators: the agent can Move Forward, Turn Left/Turn Right by 90°, Grab (an object in the current room),
Shoot (the single arrow in the direction it is facing), and Climb (out of the cave when at [1,1]).
• Sensors: the agent has five percepts, given as a 5-tuple — Stench (in the room and rooms directly adjacent
to the Wumpus), Breeze (in rooms directly adjacent to a pit), Glitter (in the room containing gold), Bump
(when the agent walks into a wall), and Scream (heard everywhere when the Wumpus is killed by the
arrow).
This environment has the following properties: it is discrete, static, single-agent, and partially observable (the
agent can only sense its current square — it cannot see pits or the Wumpus directly unless right next to it). It is
essentially deterministic, except that the initial locations of the Wumpus, pits and gold are chosen randomly at
the start.
Example of reasoning: If the agent perceives a Breeze in square [1,2], it can logically infer that there must be a pit
in one of the adjacent squares ([1,3] or [2,2]), even though it cannot see the pit directly. If it later also perceives
no Breeze in a room adjacent to [2,2], it can logically deduce that the pit must be in [1,3], not [2,2] — this kind of
deduction from percepts to conclusions about hidden aspects of the world is exactly what propositional and first-
order logic (discussed next) allow the agent to do formally.
4. Propositional Logic
Propositional Logic (also called Boolean logic) is the simplest logic that illustrates the basic concepts of logical
representation and reasoning. It deals with propositions — declarative statements that are either true or false —
combined using logical connectives.
Example (Wumpus World in propositional logic): Let B1,1 mean 'there is a breeze in square [1,1]', and P1,2, P2,1
mean 'there is a pit in [1,2] / [2,1]' respectively. The rule of the game can be written as: B1,1 ⇔ (P1,2 ∨ P2,1). If
the agent perceives B1,1 to be true, it can combine this sentence with logical inference rules to conclude facts
about where pits might be.
This approach demonstrates the power of the knowledge-based agent design: by encoding just the rules of
adjacency (Breeze ⇔ neighbouring Pit, Stench ⇔ neighbouring Wumpus) and combining them with actual
observed percepts, the agent can safely navigate the cave, find the gold, and return, using pure logical deduction
rather than guessing — even though it never directly perceives the pits or the Wumpus except through its
percepts.
• Equality (=): allows stating that two terms refer to the same object, e.g., FatherOf(John) = Richard.
• Higher-order logic: allows quantification over predicates and functions themselves, not just over objects
(e.g., 'there exists a property that both John and Mary share').
• Modal / Temporal logics: extend FOL with operators for necessity/possibility or for time (e.g., 'it is always
true that...', 'eventually...'), useful for reasoning about belief, knowledge, and time-varying facts.
• Fuzzy logic / Probabilistic extensions: allow degrees of truth or probabilities instead of strict true/false,
useful for reasoning under uncertainty.
• Situation Calculus: every predicate/function that can change over time is given an extra argument
representing the 'situation' (a snapshot of the world at a point in time), e.g., At(Agent, [1,1], S0) means the
agent is at [1,1] in situation S0. Actions transform one situation into another via a function Result(action,
situation), allowing the KB to reason about how the world changes as actions are performed.
• Fluents: predicates or functions whose value can change over time are called fluents (as opposed to eternal,
unchanging facts, which are simply predicates without a situation argument). For example, Alive(Wumpus,
s) is a fluent since the Wumpus may be alive in one situation and dead in a later one.
Example: In the Wumpus World, using situation calculus we might write: Holding(Gold, s) ⇒ Holding(Gold,
Result(TurnRight, s)) — turning right does not cause the agent to drop the gold, i.e., the Holding fluent persists
across that particular action. Such rules (called 'frame axioms') are needed to specify what does not change when
an action is performed, in addition to rules (called 'effect axioms') specifying what does change.
This connects Unit I (agents, search) with Unit II (logic): search provides the mechanism to explore possible action
sequences, while logic (propositional or first-order) provides the mechanism to represent what is known about
the world and to soundly infer new facts — together, they allow a goal-based, knowledge-based agent to operate
intelligently and safely in a partially observable environment such as the Wumpus World.
UNIT III: Knowledge Representation and Inference
1. Knowledge Base
A Knowledge Base (KB) is the central component of any knowledge-based system — it is an organised collection
of facts, rules, and relationships about a particular domain, represented in a form that a computer program can
store, retrieve, and reason over. The KB is populated using domain knowledge supplied by human experts or
extracted from data, and it is used by an Inference Engine to derive new conclusions or answer queries.
A good knowledge base should satisfy several important properties: Representational Adequacy (the ability to
represent all the kinds of knowledge needed for the domain), Inferential Adequacy (the ability to derive new
knowledge from existing knowledge), Inferential Efficiency (the ability to direct inference in productive directions
using control information), and Acquisitional Efficiency (the ability to acquire new knowledge easily, whether
through automated learning or human input).
Example: An expert system for medical diagnosis, such as MYCIN, has a knowledge base containing facts like 'the
organism is gram-positive' and rules like 'IF the infection is primary-bacteremia AND the site of culture is one of
the sterile sites AND the suspected portal of entry is the gastrointestinal tract, THEN there is suggestive evidence
that the identity of the organism is bacteroides.' The inference engine combines such rules with patient-specific
facts to suggest a diagnosis.
Broadly, knowledge can be classified into several types, each of which may need a different kind of representation:
• Declarative Knowledge: simple statements of facts about the world (e.g., 'the sky is blue'), typically
represented using logic or semantic networks.
• Procedural Knowledge: knowledge about how to do something, i.e., a sequence of actions or a method
(e.g., how to solve a quadratic equation), typically represented using production rules or algorithms.
• Meta-Knowledge: knowledge about knowledge itself (e.g., which rules are more reliable, or in what order
to try different reasoning strategies).
• Heuristic Knowledge: rule-of-thumb knowledge based on experience that is useful but not guaranteed to
be correct (e.g., 'if traffic is heavy on the highway, take the service road').
• Structural Knowledge: knowledge about how concepts relate to and are structured with respect to one
another (e.g., a car has an engine, wheels, and a chassis).
Common knowledge representation schemes used in AI include Logic (propositional and first-order, covered in
Unit II), Semantic Networks (graphs where nodes represent objects/concepts and labelled edges represent
relationships, e.g., 'IS-A', 'HAS-A'), Production (Rule-Based) Systems, and Frame-Based Systems — the latter two
are discussed in detail below.
• A Global Database (Working Memory): holds the current facts or state of the problem-solving process,
which is continuously read from and written to.
• A Set of Production Rules (the Rule Base): each rule is expressed as a condition-action (IF-THEN) pair — IF a
specified pattern of conditions is satisfied by the current contents of the global database, THEN the
corresponding action is performed (which usually updates the global database in some way).
• A Control Strategy (Inference / Recognise-Act Cycle): decides which applicable rule to fire when several
rules' conditions are satisfied simultaneously (this is called conflict resolution), and manages the overall
cycle of matching rules against the database and executing them.
Fig 3.1: Architecture of a Production System — the control/inference engine repeatedly matches rules against the working memory
and fires applicable ones.
The basic operation of a production system follows a repeated 'Match–Select–Act' (recognise-act) cycle: (1) Match
— compare the rules' IF-parts (conditions) against the current contents of the global database to find the set of
rules whose conditions are satisfied (called the conflict set); (2) Select (Conflict Resolution) — choose one rule
from the conflict set to fire, using a strategy such as rule priority, specificity (most specific rule wins), or recency
(rule matching the most recently added fact wins); (3) Act — execute the THEN-part of the selected rule, which
typically adds, deletes, or modifies facts in the global database. This cycle repeats until no more rules match, or a
goal condition is reached.
Example: A simple production system for animal identification might contain rules such as: 'IF the animal has fur
AND gives milk THEN it is a mammal'; 'IF the animal is a mammal AND has stripes THEN it is a tiger.' Given the facts
'has fur' and 'gives milk' in the global database, the first rule fires, adding 'is a mammal' to the database; this newly
added fact then allows the second rule (if 'has stripes' is also known) to fire, concluding 'is a tiger'.
Advantages of production systems include modularity (each rule is an independent chunk of knowledge that can
be added or removed without directly editing other rules) and a natural mapping to human expert reasoning ('if
situation X, then do Y'), which makes them easy to build and understand. Their main disadvantages are that, as
the rule base grows large, it becomes hard to guarantee there are no conflicting or redundant rules, and the
matching process can become computationally expensive.
4. Frame-Based System
A Frame is a data structure used to represent a stereotyped situation, object, or concept, along with all the
knowledge associated with it, in one organised unit — similar in spirit to a 'record' or 'object' in programming, but
specifically designed for AI knowledge representation. Frame-based representation was proposed by Marvin
Minsky as a way to capture structured, real-world knowledge more naturally than flat logical sentences.
A frame consists of a collection of Slots, and each slot holds a Value (which can itself be another frame, a number,
a string, a default value, a procedure to compute the value when needed — called a 'procedural attachment' or
'demon' — or a pointer/link to a related frame). For example, a frame representing the concept 'Car' might have
slots such as: Number-of-Wheels (default value 4), Fuel-Type, Manufacturer, Owner (a link to a 'Person' frame),
and so on.
Frames are usually organised into a hierarchy using IS-A links, which allows Inheritance — a powerful feature
where a specific frame automatically 'inherits' the slots and default values of its more general parent frame, unless
it explicitly overrides them with its own value. This closely mirrors object-oriented programming concepts such as
classes, instances, and inheritance.
Example: Consider a frame hierarchy: 'Vehicle' (a general frame, with slot Number-of-Wheels = unknown) → 'Car'
(IS-A Vehicle, overrides Number-of-Wheels = 4) → 'MyHondaCity' (IS-A Car, an instance with Owner = 'Ramesh',
Colour = 'White'). The instance 'MyHondaCity' automatically inherits Number-of-Wheels = 4 from the Car frame
without it needing to be stated explicitly, and it can further specialise with its own specific slot values such as
Colour.
Frames are particularly effective for representing structured, real-world knowledge with natural defaults and
exceptions (e.g., 'birds typically fly, but a penguin frame can override the Flies slot to False'), and they group all
related knowledge about a concept together, making retrieval efficient. Their main limitation is that reasoning
with frames (especially with inheritance exceptions and procedural attachments) can be less formally rigorous
than logic-based systems, and complex frame hierarchies can become difficult to maintain.
5. Inference
Inference is the process by which new facts or conclusions are logically derived from existing facts and rules stored
in the knowledge base. It is the mechanism that allows a knowledge-based system to go beyond what it was
explicitly told, and answer questions or make decisions that require combining multiple pieces of knowledge.
6. Forward Chaining
Forward Chaining is a data-driven inference strategy — reasoning starts from the known facts in the working
memory and applies rules whose IF-conditions are satisfied, deriving new facts, which are then added to the
working memory; this process repeats, generating more and more new facts, continuing until the goal is reached
(i.e., the desired fact appears in the database) or no more rules can fire.
Fig 6.1: Forward Chaining reasons from facts toward the goal (left); Backward Chaining reasons from the goal back to facts (right).
The forward chaining algorithm can be summarised as: (1) collect all facts currently known; (2) find all rules whose
IF-part is completely satisfied by these facts; (3) fire those rules, adding their conclusions as new facts (if not
already present); (4) repeat steps 2–3 using the enlarged fact set, until either the goal fact appears, or no new
facts can be derived.
Example: Given facts 'X is a bird' and rules 'IF X is a bird THEN X can fly' and 'IF X can fly THEN X is not a fish',
forward chaining would first apply the rule to derive 'X can fly', and then use this new fact to further derive 'X is
not a fish' — arriving step by step at conclusions without initially knowing exactly which conclusion is the goal.
Forward chaining is most suitable when there are many possible conclusions but the number of known initial facts
is relatively small, or when the system needs to derive all the consequences of the current situation (e.g.,
monitoring and alarm systems, where all known sensor readings should be used to generate every relevant alert).
Its main drawback is that it may generate many irrelevant facts that have nothing to do with the actual goal,
wasting computation.
7. Backward Chaining
Backward Chaining is a goal-driven inference strategy — reasoning starts from the goal (the hypothesis to be
proved or the question to be answered) and works backward, looking for rules whose THEN-part (conclusion)
matches the goal. For each such rule, its IF-part (conditions) become new sub-goals, which must themselves be
proved (either because they are already known facts, or by recursively finding further rules that conclude them).
This continues until all sub-goals are reduced to facts that are already known to be true (or the search fails,
meaning the goal cannot be proved).
The backward chaining algorithm can be summarised as: (1) start with the goal to be proved; (2) find a rule whose
conclusion (THEN-part) matches the current goal; (3) treat each condition in that rule's IF-part as a new sub-goal;
(4) recursively try to prove each sub-goal, either by matching it directly against known facts, or by finding another
rule that concludes it; (5) if all sub-goals of some applicable rule succeed, the original goal is proved.
Example: To check the goal 'X is not a fish', backward chaining looks for a rule concluding this — 'IF X can fly THEN
X is not a fish' — and sets 'X can fly' as a new sub-goal. It then looks for a rule concluding 'X can fly' — 'IF X is a bird
THEN X can fly' — setting 'X is a bird' as the next sub-goal. If 'X is a bird' is already a known fact, the chain of sub-
goals succeeds, proving that 'X is not a fish', without ever needing to derive unrelated facts.
Backward chaining is most suitable when there is a single, specific goal to be verified (e.g., diagnostic / expert
systems such as MYCIN, where the goal is to confirm 'does the patient have disease D?'), because it only explores
rules and facts that are actually relevant to that particular goal, avoiding the wasted effort forward chaining may
incur.
Starts from Known facts in working memory The goal / hypothesis to prove
Best suited for Many possible conclusions; A single specific goal; diagnostic/expert
monitoring/planning systems systems
Efficiency Can generate many irrelevant facts Explores only goal-relevant rules
Exam Tip: A very frequent exam question is 'Differentiate between Forward and Backward Chaining' — the table
above covers all key points needed for full marks.
UNIT IV — Machine Learning Foundations
This unit introduces the concept of learning in intelligent agents and builds up the foundational algorithms of
Machine Learning that form the backbone of modern Artificial Intelligence systems. We move from the general
idea of an agent that improves its own performance through experience, to concrete algorithms such as Decision
Trees, Support Vector Machines, Artificial Neural Networks and Bayesian Belief Networks. Each topic is explained
conceptually, mathematically (where required) and with a worked example so that it can be directly used for
examination writing.
Definition: A learning agent is an intelligent agent that is capable of improving its behaviour and performance
over time through experience, rather than relying only on a fixed, pre-programmed set of rules.
In classical AI, an agent's behaviour is fixed at design time by the programmer — every possible situation and its
correct response must be anticipated in advance. This works only for very simple, fully known environments. Real-
world environments, however, are large, dynamic and only partially known in advance. It is impossible for a
designer to foresee every situation the agent will encounter. The solution is to build agents that can learn: agents
that start with some basic knowledge and then adapt and improve their decision-making as they gather more
experience from the environment. Learning allows an agent to operate successfully in environments that were
not fully known at design time, and it allows the agent's performance to improve automatically over its lifetime.
1. Performance Element: This is what was previously considered the entire agent — it takes in percepts from
the sensors and decides on external actions to be performed by the effectors. It is responsible for selecting
actions based on the current knowledge it has.
2. Critic: The critic tells the learning element how well the agent is performing with respect to a fixed
performance standard. The critic uses an external standard because the percepts themselves do not directly
indicate the agent's own success — for example, a chess program may need an external standard to know
that checkmating the opponent is good, since the percept sequence alone does not say so.
3. Learning Element: This component is responsible for making improvements to the performance element. It
takes knowledge about how the agent has been doing, and determines how the performance element
should be modified to do better in the future.
4. Problem Generator: This component is responsible for suggesting actions that will lead to new and
informative experiences, even if these actions are not optimal in the short run. This is important because if
the agent only ever acts to maximise its immediate performance, it may never discover better long-term
strategies — this is often called the exploration vs. exploitation trade-off.
Example
Consider a self-driving taxi agent. The performance element decides steering, acceleration and braking actions.
The critic observes outcomes such as sudden braking, passenger complaints, or safe/late arrivals and reports this
to the learning element. The learning element then modifies the driving rules (e.g., 'brake earlier when it is
raining'). The problem generator may occasionally suggest trying a new, unexplored route purely to learn whether
it is faster — even though the agent is not certain it will save time.
2. Inductive Learning
Definition: Inductive learning (also called learning from examples) is a form of learning in which an agent tries
to figure out a general function or rule from a given set of input-output example pairs (the training set).
The task is: given a training set of examples of the form (x, f(x)), where x is an input and f(x) is the correct output
produced by an unknown target function f, the learner must find (or approximate) a hypothesis function h such
that h behaves the same as, or as close as possible to, f — not only on the training examples already seen, but also
on new, unseen examples. This ability to correctly handle new inputs is called generalisation.
Key Terminology
• Training Set: The set of example input-output pairs used to construct the hypothesis.
• Hypothesis (h): A candidate function that the learning algorithm proposes as an approximation of the true
target function f.
• Hypothesis Space: The set of all hypotheses that the learning algorithm is allowed to consider (e.g., all
straight lines, all decision trees of a certain depth).
• Consistent Hypothesis: A hypothesis h is said to be consistent with the training data if it agrees with the
value of f for every example in the training set.
• Generalisation / Test Set: The ability of the learned hypothesis to correctly predict outputs for inputs that
were not part of the training set; measured using a separate test set.
Example
Suppose we are given the following example pairs of a function: f(1) = 2, f(2) = 4, f(3) = 6, f(4) = 8. A learner using
inductive learning may propose the hypothesis h(x) = 2x. This hypothesis is consistent with all the given examples,
and because it is a simple linear rule, by Ockham's Razor it would be preferred over a more complicated hypothesis
(such as a high-degree polynomial) that also happens to fit the same four points exactly.
A very common way to visualise inductive learning for two-class data is as finding a curve or boundary that best
separates the plotted example points, such that it can correctly classify new points that fall on either side of that
boundary.
The agent learns a mapping from inputs to outputs Spam email detection;
Supervised Learning using a training set of correctly labelled input-output predicting house
pairs. prices
Unit IV of this course primarily focuses on Supervised Learning techniques (Decision Trees, SVM, Neural Networks,
Bayesian Networks), while Unit V focuses on Unsupervised Learning (Clustering methods).
4. Supervised Learning
Definition: Supervised learning is a type of machine learning in which the algorithm is trained on a labelled
dataset — that is, a dataset in which every training example is paired with the correct output (label). The goal
is to learn a mapping function from inputs to outputs so that the model can predict the output for new,
unseen inputs.
The word 'supervised' comes from the idea that a 'teacher' (the labelled dataset) supervises the learning process
by providing the correct answer for every training example, and the algorithm's job is to adjust itself so that its
predicted output matches the correct output as closely as possible, minimising the prediction error.
Example
Suppose we want to build a system that predicts whether a student will pass or fail an exam based on the number
of hours studied. We collect past data of (hours studied, pass/fail) pairs and train a supervised learning model on
this labelled data. Once trained, the model can predict pass/fail for a new student given only their study hours.
This is a classification problem, since the output ('pass' or 'fail') is a discrete category.
Definition: A Decision Tree is a supervised learning model represented as a tree structure, where each
internal node tests the value of a particular attribute, each branch represents an outcome of that test, and
each leaf node represents a final decision or class label.
Decision tree learning is one of the most widely used and easy-to-interpret methods of inductive learning. Given
a set of labelled training examples, the algorithm builds a tree that can be used to classify new, unseen examples
by starting at the root node, testing the attribute at that node, following the branch corresponding to the
example's value for that attribute, and repeating this process until a leaf node (a decision) is reached.
Entropy
Entropy is a measure, borrowed from information theory, of the amount of uncertainty or impurity/disorder
present in a set of examples. If a set S contains only examples of a single class, its entropy is 0 (no uncertainty at
all). If a set S is evenly split between two classes, its entropy is at its maximum, 1 (highest uncertainty). For a set S
with a Boolean (two-class) classification, where p⊕ is the proportion of positive examples and p⊖ is the
proportion of negative examples:
Information Gain
Information Gain measures the expected reduction in entropy that results from splitting (partitioning) the training
examples according to a particular attribute A. The attribute with the highest information gain is chosen as the
decision node, because it does the best job of separating the training examples according to the target
classification.
where Sᵥ is the subset of S for which attribute A has value v, and the summation is taken over every possible value
v of attribute A.
Step 1: Out of 8 examples, 4 are 'Yes' and 4 are 'No'. So the initial Entropy(S) = −(4/8)log₂(4/8) − (4/8)log₂(4/8) = 1
(maximum uncertainty, since the classes are evenly split).
Step 2: We calculate the Information Gain for each candidate attribute (Outlook, Humidity, Wind) by computing
the weighted entropy of the subsets formed after splitting on that attribute, and subtracting it from 1. In this
example, splitting on 'Outlook' produces the purest subsets — all 'Overcast' examples are 'Yes', which gives
Outlook the highest information gain.
Step 3: Since Outlook gives the highest information gain, it becomes the root node. The examples are partitioned
into three branches: Sunny, Overcast and Rain. The 'Overcast' branch becomes a pure leaf ('Yes') immediately,
since all overcast examples say 'Yes'. For the 'Sunny' and 'Rain' branches, which still contain a mix of Yes/No, the
algorithm recursively repeats the same process (choosing the next best attribute — Humidity for Sunny, Wind for
Rain) until every branch ends in a pure leaf node.
Fig 5.1 — Resulting decision tree for the 'Play Tennis' example
This resulting tree can now be used to classify a brand-new day: to predict whether tennis will be played, we
simply start at the root, check the actual Outlook value for that day, and follow the tree down to a leaf to get the
prediction.
Definition: A Support Vector Machine is a supervised learning algorithm that classifies data by finding the
optimal hyperplane that best separates the data points of different classes, such that the margin (distance)
between the hyperplane and the nearest data points of each class is maximised.
Support Vector Machines are considered one of the most powerful 'out-of-the-box' classifiers in machine learning,
particularly effective for classification problems with a clear margin of separation between classes and for high-
dimensional data.
Key Concepts
• Hyperplane: A decision boundary that separates different classes of data. In a 2-dimensional space this is
simply a line; in 3 dimensions it is a plane; in higher dimensions it is called a hyperplane.
• Margin: The distance between the hyperplane and the nearest data point from either class. SVM tries to find
the hyperplane that has the maximum possible margin — this is why it is also called the Maximum Margin
Classifier.
• Support Vectors: The data points that lie closest to the hyperplane. These points are the most critical
elements of the dataset because they are the ones that actually determine the position and orientation of
the hyperplane — removing any non-support-vector point would not change the hyperplane at all, but
moving a support vector would.
• Kernel Trick: When data cannot be separated by a straight line/hyperplane in its original space (i.e., it is not
linearly separable), SVM uses a mathematical function called a kernel to transform/project the data into a
higher-dimensional space in which it does become linearly separable. Common kernels include Linear,
Polynomial and Radial Basis Function (RBF).
Fig 6.1 — Maximum margin hyperplane separating two classes, with support vectors circled
Example
Suppose we want to classify emails as spam or not-spam, using two features: the number of times the word 'free'
appears, and the number of exclamation marks used. If we plot each email as a point on a 2-D graph using these
two feature values, spam emails tend to cluster in one region (high 'free' count, many exclamation marks) while
genuine emails cluster elsewhere. SVM finds the straight line (hyperplane) that best divides these two clusters
with the widest possible gap, and any new email is classified as spam or not-spam depending on which side of that
line it falls.
Advantages of SVM
• Effective in high-dimensional spaces, even when the number of features exceeds the number of samples.
• Memory efficient, since it uses only a subset of training points (the support vectors) in the decision function.
• Versatile — different kernel functions can be applied for different types of decision boundaries.
Disadvantages of SVM
• Not very efficient on very large datasets, since training time can be high.
• Performance depends heavily on the correct choice of kernel and its parameters.
• Does not directly provide probability estimates for class membership.
The term Belief Network generally refers to Bayesian Belief Networks, which represent a different, probabilistic
approach to knowledge and learning (covered in detail in Topic 10 below), as opposed to Neural Networks, which
learn numeric weights through training examples. Both are important sub-areas used for learning and reasoning
under uncertainty.
8. The Perceptron
Definition: A Perceptron is the simplest form of an artificial neural network — a single artificial neuron that
takes several binary or real-valued inputs, computes a weighted sum of these inputs, and produces a single
binary output based on whether this sum exceeds a certain threshold.
The perceptron was proposed by Frank Rosenblatt in 1958 and is historically the earliest trainable neural network
model. It is primarily used for binary classification problems where the data is linearly separable — that is, the two
classes can be separated by drawing a single straight line (in 2-D) or a hyperplane (in higher dimensions).
Working of a Perceptron
Each input xᵢ is multiplied by its corresponding weight wᵢ, and all these weighted inputs are summed together,
along with an extra term called the bias (b), which allows the decision boundary to be shifted away from the origin.
This weighted sum is then passed through an activation function — in the original perceptron, this is a simple step
function that outputs 1 if the sum is above a threshold, and 0 (or −1) otherwise.
Output: y = 1 if z ≥ 0, y = 0 if z < 0
wᵢ(new) = wᵢ(old) + η × (t − ŷ) × xᵢ
This rule has a simple intuition: if the perceptron predicted 0 but the correct answer was 1 (t − ŷ = 1), the weights
are increased in the direction of the inputs that were 'on', making the perceptron more likely to output 1 next
time for a similar input. If it predicted 1 but the correct answer was 0, the weights are decreased. This process is
repeated over all training examples, for many passes (epochs), until the perceptron classifies all training examples
correctly (or a maximum number of iterations is reached).
Definition: A Multi-Layer Feed Forward Network (also called a Multi-Layer Perceptron, MLP) is a neural
network consisting of more than one layer of neurons — an input layer, one or more hidden layers, and an
output layer — in which information flows strictly in one direction, from input to output, with no cycles or
loops.
By stacking multiple layers of neurons, with non-linear activation functions at each neuron, a multi-layer network
is able to represent much more complex, non-linear decision boundaries than a single perceptron — including
problems like XOR that a single perceptron cannot solve.
Fig 9.1 — A multi-layer feed forward neural network with one hidden layer
Layers of an MLP
• Input Layer: Receives the raw feature values of the example; performs no computation, simply passes values
forward.
• Hidden Layer(s): One or more intermediate layers where the actual non-linear computation happens. Each
hidden neuron computes a weighted sum of its inputs and passes it through a non-linear activation function
(e.g., Sigmoid, Tanh, ReLU).
• Output Layer: Produces the final prediction of the network (e.g., a class label or a numeric value).
10. Forward Pass: The input is passed forward through the network layer by layer, using the current weights, to
produce a predicted output.
11. Backward Pass: The error (difference between predicted output and the true target) is calculated at the
output layer, and then propagated backward through the network, layer by layer, using the chain rule of
calculus, to compute how much each individual weight contributed to the error.
12. Weight Update: Every weight in the network is then adjusted slightly, in the direction that reduces the overall
error, using an optimisation method such as Gradient Descent.
This process is repeated for many epochs until the network's overall error on the training set becomes acceptably
small, or stops improving further.
Example
Consider handwritten digit recognition. The input layer receives the pixel intensity values of a digit image. The
hidden layers progressively learn to detect useful intermediate features — for instance, early hidden neurons
might learn to detect edges and curves, while later hidden neurons combine these into shapes resembling parts
of digits. The output layer finally has 10 neurons (one for each digit 0–9), and the neuron with the highest output
value is taken as the network's predicted digit.
10. Bayesian Belief Networks
Definition: A Bayesian Belief Network (BBN), also called a Bayesian Network or a Belief Network, is a graphical
model that represents a set of random variables and their conditional dependencies using a Directed Acyclic
Graph (DAG), together with a Conditional Probability Table (CPT) attached to every node.
Bayesian Networks provide a way to represent uncertain knowledge compactly and to perform reasoning under
uncertainty. Instead of storing the full joint probability distribution over all variables (which grows exponentially
with the number of variables and quickly becomes infeasible to store or compute), a Bayesian Network exploits
the fact that most variables directly depend on only a few other variables, and represents only these local
dependencies explicitly.
This scenario can be represented using five random variables — Burglary, Earthquake, Alarm, JohnCalls and
MaryCalls — connected as shown below:
Fig 10.1 — Bayesian Belief Network for the burglary example
Here, Burglary and Earthquake are root nodes (no parents), each with its own prior probability of occurring. Alarm
depends on both Burglary and Earthquake (it can be triggered by either or both), so its CPT specifies P(Alarm |
Burglary, Earthquake) for all four combinations of the two parent values. Finally, JohnCalls and MaryCalls each
depend only on Alarm (not directly on Burglary or Earthquake), reflecting the fact that John and Mary only react
to hearing the alarm, not to the burglary or earthquake directly.
Table 10.1 — Sample Conditional Probability Table for the Alarm node
This means we never need to store the entire joint distribution table (which, for 5 Boolean variables, would need
2⁵ = 32 entries); instead we only need the much smaller set of local CPTs, and the full joint probability of any
specific combination of events can be calculated on demand by simply multiplying together the relevant
conditional probabilities from the network.
Applications of Bayesian Belief Networks
• Medical diagnosis — reasoning about diseases and their symptoms under uncertainty.
• Spam filtering and document classification.
• Risk analysis and decision support systems.
• Fault diagnosis in industrial and mechanical systems.
Advantages
• Compactly represents uncertain knowledge, avoiding the need to store a huge joint probability table.
• Explicitly shows the causal/dependency structure between variables, making the model easy to interpret.
• Supports both forward (predictive) reasoning and backward (diagnostic) reasoning.
UNIT V — Unsupervised Learning
While Unit IV dealt with supervised learning, where the training data comes with correct labels/answers, this unit
deals with Unsupervised Learning, where the algorithm is given only raw, unlabelled data and must discover
hidden structure, patterns or natural groupings within it on its own. The main focus of this unit is Clustering — the
task of grouping similar data points together — covering K-Means Clustering, Hierarchical Clustering
(Agglomerative and Divisive) and Fuzzy Clustering.
1. Unsupervised Learning
Definition: Unsupervised learning is a type of machine learning in which the algorithm is given a dataset that
has no labelled outputs, and it must find natural patterns, groupings or structure within the data purely based
on the similarities and differences among the data points themselves.
Unlike supervised learning, where a 'teacher' provides the correct answer for every training example,
unsupervised learning has no such teacher — the algorithm must explore the data and organise it in a meaningful
way based only on the inherent structure present in the features. This is very useful in real-world situations where
labelling data is expensive, time-consuming, or simply not possible.
Training data Labelled (input-output pairs given) Unlabelled (only inputs given)
Example
A retail company has data about the purchasing behaviour of thousands of customers, but no predefined labels
about which 'type' of customer each one is. Using unsupervised learning (clustering), the company can
automatically group customers into segments such as 'bargain hunters', 'brand loyal customers' and 'occasional
buyers', purely based on similarities in their purchase patterns, without ever having been told in advance what
these groups should be.
2. K-Means Clustering
Definition: K-Means is a partition-based unsupervised clustering algorithm that divides a given dataset into
a pre-specified number, K, of non-overlapping clusters, such that each data point belongs to the cluster with
the nearest mean (centroid).
K-Means is one of the simplest and most widely used clustering algorithms because of its speed and simplicity. It
works iteratively, alternating between assigning points to the nearest cluster centre and then recalculating the
cluster centres, until the assignments stop changing.
Fig 2.1 — Data points partitioned into K = 3 clusters, with centroids marked ✕
Worked Example
Suppose we have six students' marks in two subjects and we want to group them into K = 2 clusters ('weak
performers' and 'strong performers'). We first randomly choose two students' mark-pairs as the initial centroids.
In the assignment step, every student is assigned to whichever of the two centroids their marks are closest to. In
the update step, we recompute each cluster's centroid as the average marks of the students currently in that
cluster. We repeat this assignment-and-update cycle; after a few iterations the centroids stabilise, and the six
students end up divided into two clear groups — one cluster containing students with generally lower marks and
the other containing students with generally higher marks.
Advantages
• Simple to understand and computationally fast, even for fairly large datasets.
• Guaranteed to converge (though not always to the global optimum).
Disadvantages
• The number of clusters K must be specified in advance.
• Sensitive to the initial random placement of centroids — poor initialisation can lead to poor clustering.
• Works best only when clusters are roughly spherical/globular in shape and of similar size; performs poorly
on irregularly shaped clusters.
• Sensitive to outliers, since they can significantly distort the mean of a cluster.
3. Hierarchical Clustering
Definition: Hierarchical Clustering is an unsupervised clustering method that builds a hierarchy (a tree-like
structure) of nested clusters, rather than producing a single fixed set of K clusters, by progressively merging
or splitting clusters based on their similarity.
Unlike K-Means, hierarchical clustering does not require the number of clusters to be specified in advance.
Instead, it produces a complete tree of clusters, called a Dendrogram, and the user can 'cut' this tree at any desired
level to obtain any number of clusters after the algorithm has already run.
The Dendrogram
A dendrogram is a tree-like diagram that records the sequence of merges (or splits) made during hierarchical
clustering, along with the distance (dissimilarity) at which each merge/split happened. The height at which two
clusters are joined in the dendrogram represents how dissimilar those two clusters were. To obtain a specific
number of clusters, we simply draw a horizontal line across the dendrogram at a chosen height — the number of
vertical lines this horizontal cut crosses gives the number of clusters.
Hierarchical clustering can be performed using two fundamentally opposite strategies: Agglomerative (bottom-
up) and Divisive (top-down), explained in detail below.
Definition: Agglomerative clustering is a 'bottom-up' hierarchical clustering approach that starts by treating
every single data point as its own individual cluster, and then repeatedly merges the two closest (most similar)
clusters together, one pair at a time, until only a single cluster containing all the data points remains.
Definition: Divisive clustering is a 'top-down' hierarchical clustering approach that starts with all data points
in a single large cluster, and then repeatedly splits the most heterogeneous (least similar/most spread out)
cluster into two smaller clusters, continuing until every data point is in its own individual cluster.
Divisive clustering is essentially the exact reverse process of agglomerative clustering. It is conceptually simple but
computationally more expensive in practice, since deciding the best way to split a cluster into two requires
considering a very large number of possible splits (there are 2^(n−1) − 1 ways to split a cluster of n points into two
non-empty groups), which is why agglomerative clustering is used far more commonly in practice.
Starting point Each point is its own cluster All points in one single cluster
Computational cost Less expensive; more commonly used More expensive; less commonly used
• Single Linkage: The distance between two clusters is taken as the minimum distance between any single
point in the first cluster and any single point in the second cluster.
• Complete Linkage: The distance between two clusters is taken as the maximum distance between any point
in the first cluster and any point in the second cluster.
• Average Linkage: The distance between two clusters is taken as the average of the distances between every
pair of points, one from each cluster.
• Centroid Linkage: The distance between two clusters is taken as the distance between the centroids (mean
points) of the two clusters.
Example
Suppose we have five cities and we want to group them hierarchically based on the road distance between them.
Agglomerative clustering would start by treating each city as its own cluster, then merge the two closest cities
into a group, then find the next closest pair of clusters (which could be a city and the group, or two other cities)
and merge them, and so on, until all five cities are combined into a single cluster — with every merge step recorded
in a dendrogram that can then be 'cut' at any distance threshold to get the desired number of city groups.
5. Fuzzy Clustering
Definition: Fuzzy Clustering is a clustering technique in which each data point can belong to more than one
cluster simultaneously, with a degree of membership (a value between 0 and 1) indicating how strongly it
belongs to each cluster, rather than being forced to belong to exactly one cluster as in K-Means and
hierarchical clustering.
Both K-Means and Hierarchical Clustering are examples of 'hard' or 'crisp' clustering, where every data point is
assigned to exactly one cluster, with full (100%) membership in that cluster and 0% membership in every other
cluster. In many real-world situations, however, data points do not naturally belong entirely to a single group —
they may share characteristics of multiple groups at once. Fuzzy clustering handles this more realistically by
allowing partial, overlapping membership.
Fig 5.1 — Fuzzy membership functions: a point can partially belong to two clusters at once
Example
Consider classifying a set of fruit images purely by colour, where we have two clusters: 'ripe' (red/yellow) and
'unripe' (green). A fruit image that is mostly yellow with a slight green tinge cannot be said to belong 100% to
either cluster — fuzzy clustering would assign it something like 0.7 membership to 'ripe' and 0.3 membership to
'unripe', which more realistically reflects its actual, in-between appearance, compared to a hard clustering method
that would be forced to put it entirely into just one of the two categories.
Soft/Fuzzy (partial
Partition-based, iterative, Must be specified (C) in
Fuzzy C-Means membership in multiple
weighted advance
clusters)