Skip to content
JNTUK · B.Tech study libraryFree access · No sign-up
JNTUK · R23 · CSE · Semester 3-2

Machine Learning exam preparation.

Practice questions for every unit in the style of the R23 end exam, a model answer for each, and a one-page revision summary. Built on the official syllabus units.

  • Practice questions in the exam's style
  • Drafted with AI and checked by a second AI pass. Doubtful points were verified against public sources. Report a mistake
Units
5
Questions
60
2-mark
30
10-mark
30
Checked on

Exam guide

Paper pattern

Semester-end theory paper, 70 marks, from the JNTUK B.Tech R23 Regulations, end-examination pattern for theory subjects.

  1. Question 1 · 20 marksTen compulsory short-answer questions of 2 marks each (two from every unit).
  2. Questions 2 to 6 · 50 marksFive either/or questions of 10 marks each, one per unit. You answer one of the two in each.
  • The semester-end examination carries 70 marks; internal assessment carries 30.
  • Mid-semester examinations are separate: a 20-minute objective paper (10 marks) and a 90-minute subjective paper with three either/or questions of 10 marks (condensed to 15 marks).
  • The regulations text does not state the length of the end examination. Use the duration printed on your hall ticket or question paper.

Read the R23 regulations (PDF) ↗

How to split your time

This plan assumes a 3-hour paper. If yours is different, keep the same proportions. Marks per minute stay roughly even across Question 1 and the 10-mark answers.

  1. 10 minRead the paper and choose one option in each either/or question
  2. 30 minQuestion 1: ten short answers (about 3 minutes each)
  3. 130 minQuestions 2 to 6: one 10-mark answer per unit (about 26 minutes each)
  4. 10 minFinal check of numbering, calculations and diagrams

Study tips for Machine Learning

  • Practise the hand calculations until they are quick: Euclidean and Manhattan distances, a k-NN vote, entropy, Gini index and information gain for one split, a naive Bayes posterior, and one K-means iteration.
  • Write out a confusion matrix for every classification example you solve, then compute accuracy, precision, recall and F1 from it, because these metrics come up across several units.
  • For each algorithm, keep a short card with what it learns, its main parameter (k, tree depth, number of trees, learning rate, number of clusters), how it predicts, and one strength and one weakness.
  • Learn the figures by drawing them from memory: the stages of machine learning, a small decision tree, a perceptron, a multilayer perceptron with its forward and backward pass, and a cluster hierarchy.
  • Compare related methods side by side: hard and soft clustering, agglomerative and divisive clustering, the perceptron and the SVM, and linear and logistic regression, stating what each one outputs.
Unit 1

Introduction to Machine Learning

Syllabus: Evolution of machine learning; Paradigms for machine learning; Learning by rote and learning by induction; Reinforcement learning; Types of data; Matching; Stages in machine learning; Data acquisition, feature engineering and data representation; Model selection, model learning, model evaluation and model prediction; Search and learning; Data sets

One-page revision summary

  • Machine learning grew from 1950s programs such as Samuel's checkers player and the perceptron, through expert systems and statistical learning, to deep learning powered by big data and GPUs.
  • A paradigm for learning is a way of gaining knowledge; the paradigms include learning by rote, deduction, abduction, induction and reinforcement learning.
  • Rote learning stores examples and answers only exact matches, while learning by induction generalises from examples and can handle unseen inputs.
  • Supervised learning uses labelled examples, unsupervised learning finds structure such as clusters in unlabelled data, and semi-supervised learning uses both.
  • In reinforcement learning an agent learns, by trial and error, a policy that maximises the discounted return from delayed rewards.
  • Data can be nominal, ordinal, interval, ratio or binary; structured data fit a table, while text, images, time series and graphs are first turned into features.
  • Matching compares a pattern with stored patterns: exact matching is used for lookup, and approximate matching uses a distance or similarity measure chosen to suit the data type.
  • The stages in machine learning are data acquisition, feature engineering, data representation, model selection, model learning, model evaluation and model prediction, with feedback from evaluation.
  • Feature engineering cleans, extracts, selects and scales features, and data representation usually turns each example into a fixed-length feature vector.
  • Model selection chooses the model family and hyperparameters on validation data; model learning fits the parameters on training data.
  • Model evaluation uses unseen test data and measures such as accuracy, precision, recall, F1 score or mean squared error; model prediction applies the model to new data.
  • Learning is a search through a hypothesis space guided by an evaluation criterion, and restricting the space (a bias) makes the search feasible.
  • Greedy searches such as forward feature selection and decision tree splitting are fast but can miss the best solution that exhaustive search would find.
  • A data set is split into training, validation and test sets; k-fold cross-validation uses each of k parts once for validation when data are scarce.
  • Common benchmark data sets include Iris (150 flowers, 4 features, 3 classes of 50) from the UCI Machine Learning Repository and MNIST (70,000 handwritten digit images of 28 × 28 pixels).

Learn these by heart

  • A program learns from experience E for task T and performance measure P if its performance at T, measured by P, improves with E.
  • Euclidean d(x, y) = √Σ(xi − yi)²; Manhattan d(x, y) = Σ|xi − yi|; Hamming distance = number of positions where two binary patterns differ.
  • SMC = (M11 + M00)/(M11 + M00 + M10 + M01); Jaccard = M11/(M11 + M10 + M01).
  • Return G = r1 + γ r2 + γ² r3 + …; Q-learning: Q(s, a) ← Q(s, a) + α[r + γ max Q(s′, a′) − Q(s, a)].
  • Min–max scaling: x′ = (x − min)/(max − min); accuracy = correct predictions / total predictions.
  • With d features there are 2^d − 1 non-empty subsets; greedy forward selection needs at most d(d + 1)/2 evaluations.

2-mark questions

1 What is machine learning? Define it in terms of task, performance measure and experience, with an example. 2 marks
Model answer

Machine learning lets programs improve at a task from data instead of hand-written rules; Arthur Samuel used the term for his checkers program. In Tom Mitchell's definition, a program learns from experience E for task T and performance measure P if its performance at T, measured by P, improves with E. Example: T = spam filtering, P = accuracy, E = labelled emails.

2 Distinguish between learning by rote and learning by induction. 2 marks
Model answer

Learning by rote memorises the examples it has seen and answers a query only by retrieving an exact stored match, like a lookup table or a cache; it cannot handle unseen inputs. Learning by induction generalises from specific examples to a general rule or model, so it can predict outputs for new inputs, although the generalisation may be wrong.

3 What is reinforcement learning? Name its main elements. 2 marks
Model answer

Reinforcement learning is learning by trial and error: an agent acts in an environment, receives a numerical reward after each action, and learns a policy that maximises the total discounted reward over time. No correct action is given for any state. Its main elements are the agent, environment, state, action, reward, policy and value function.

4 Distinguish nominal, ordinal, interval and ratio data with one example of each. 2 marks
Model answer

Nominal data are categories with no order, such as blood group or colour. Ordinal data are ordered categories whose gaps cannot be measured, such as grades low, medium, high. Interval data are numbers with equal gaps but no true zero, such as temperature in °C. Ratio data have a true zero, so ratios are meaningful, such as weight or age.

5 Find the Hamming distance, simple matching coefficient (SMC) and Jaccard coefficient of the binary patterns X = 1 0 1 1 0 1 and Y = 1 1 1 0 0 1. 2 marks
Model answer

Position by position: both 1 (M11) = 3, both 0 (M00) = 1, and mismatches (M10 + M01) = 2, at positions 2 and 4. Hamming distance = 2. SMC = (M11 + M00)/6 = 4/6 = 0.67. Jaccard = M11/(M11 + M10 + M01) = 3/5 = 0.6, because Jaccard ignores 0–0 matches.

6 Why is a data set divided into training, validation and test sets? 2 marks
Model answer

The training set is used to fit the model's parameters. The validation set is used to compare models and tune hyperparameters, such as k in k-NN. The test set is used only at the end, to estimate how well the chosen model works on unseen data. Keeping the sets separate prevents an over-optimistic estimate caused by overfitting.

10-mark questions

1 Trace the evolution of machine learning from its beginnings to deep learning, with a timeline diagram. 10 marks
Model answer

Machine learning grew out of artificial intelligence, statistics and pattern recognition. Its history is a move from hand-written rules to models that learn from data, driven by better algorithms, more data and faster computers.

Evolution of machine learning, decade by decadeA top-to-bottom timeline: 1950s Samuel and the perceptron, 1960s nearest neighbour, 1970s expert systems, 1980s ID3 and backpropagation, 1990s SVMs and boosting, 2000s big data and random forests, and 2010s deep learning.1950s: Samuel,perceptron1960s: nearestneighbour1970s: expertsystems1980s: ID3,backpropagation1990s: SVMs,boosting2000s: bigdata, forests2010s: deeplearningXOR limit ofperceptronrules hardto writeGPUs, big data
Evolution of machine learning, decade by decade

1. 1950s, the beginnings. Alan Turing asked whether machines can think and proposed the imitation game. Arthur Samuel's checkers program improved by playing against itself and remembering board positions, and Samuel used the term machine learning for it. Frank Rosenblatt's perceptron learned the weights of a linear classifier from examples.

2. 1960s, pattern recognition. Statistical pattern recognition grew, and the nearest neighbour rule (give a pattern the class of its closest stored example) was analysed. At the end of the decade Minsky and Papert showed that a single-layer perceptron cannot learn functions such as XOR, and interest in neural networks fell.

3. 1970s, expert systems. AI concentrated on expert systems, whose rules were written by human experts, for example for medical diagnosis. Writing and maintaining thousands of rules was slow and costly (the knowledge acquisition bottleneck), which pushed researchers towards learning rules from data.

4. 1980s, learning rules and networks. Decision tree learners such as ID3 induced rules from labelled examples, and backpropagation made it practical to train multilayer neural networks. Machine learning became a research field of its own.

5. 1990s, statistical learning. Support vector machines (SVMs), kernel methods and boosting put learning on a firm theoretical footing, and reinforcement learning produced programs such as TD-Gammon, which learned backgammon by playing itself. Data mining applied these methods to business databases.

6. 2000s, big data and ensembles. The web brought big data; random forests and other ensembles became popular, and deep networks were trained layer by layer.

7. 2010s, deep learning. With GPUs and large labelled data sets such as ImageNet, deep convolutional networks took the lead in image recognition. AlphaGo combined deep learning with reinforcement learning to beat a top Go player, and large language models followed.

In short, machine learning moved from memorising and hand-coding knowledge to learning by induction from data. Each stage removed a limitation of the one before, and today machine learning is the main way of building AI systems.

2 Explain the paradigms for machine learning: learning by rote, learning by deduction, learning by abduction, learning by induction and reinforcement learning, with an example of each. 10 marks
Model answer

A paradigm for machine learning is a basic way in which a system gains knowledge. The paradigms differ in what the learner is given (facts, rules, examples or rewards) and in the kind of reasoning that produces the new knowledge.

Paradigms for machine learningA tree with Paradigms for learning at the top and five branches: rote (memorise, retrieve), deduction (rule to case), abduction (best explanation), induction (examples to rule) and reinforcement (rewards). Induction branches into supervised, unsupervised and semi-supervised learning.Paradigmsfor learningRote: memorise,retrieveDeduction:rule to caseAbduction: bestexplanationInduction:examples to ruleReinforcement:rewardsSupervised(labels)Unsupervised(no labels)Semi-supervised
Paradigms for machine learning

1. Learning by rote. The learner memorises facts or computed results exactly as given and later retrieves them. Nothing is generalised: a query is answered only if an exact match is found in memory. Examples are a lookup table, caching the results of a function, and Samuel's checkers program, which stored board positions with their scores. Retrieval is fast, but memory grows quickly and unseen inputs cannot be handled.

2. Learning by deduction. The learner derives a specific case from general rules it already holds, by logically valid inference. From "all mammals are warm-blooded" and "a whale is a mammal" it concludes "a whale is warm-blooded". Deduction is truth-preserving: if the rules are true, so is the conclusion. It adds no knowledge beyond what the rules imply, but makes that knowledge explicit and faster to use.

3. Learning by abduction. The learner infers the best (most plausible) explanation of an observation from a known rule. Rule: if it rains, the grass is wet. Observation: the grass is wet. Abduced explanation: it rained. The explanation may be wrong, since a sprinkler could also wet the grass, so abduction is not truth-preserving. It is used in fault and medical diagnosis.

4. Learning by induction. The learner generalises from specific examples to a general rule. Having seen many emails labelled spam or not spam, it learns a rule that labels new emails. Most machine learning is inductive:

  • supervised learning uses examples with labels (classification, regression);
  • unsupervised learning has no labels and finds structure such as clusters;
  • semi-supervised learning uses a few labelled and many unlabelled examples.

An induced rule can be wrong, so it is always tested on new data.

5. Reinforcement learning. The learner, called an agent, is never told the correct action. It acts in an environment, receives rewards or penalties, and learns a policy that maximises the long-term reward, as a program does when it learns a game by playing it many times.

In short, rote learning memorises, deduction applies general rules to a case, abduction explains observations, induction generalises from examples, and reinforcement learning learns from rewards for its actions.

3 Explain the stages in machine learning, from data acquisition and feature engineering to model selection, learning, evaluation and prediction, with a neat diagram and a running example. 10 marks
Model answer

Building a machine learning system is a sequence of stages. Each stage uses the output of the one before, and the evaluation stage can send the work back for changes. Running example: deciding whether an email is spam.

Stages in machine learningA top-to-bottom flow: data acquisition, feature engineering, data representation, model selection on the validation set, model learning on the training set, model evaluation on the test set, and model prediction. An arrow from model evaluation goes back to model selection when the result is not good enough.Data stagesModel stagesData acquisitionFeatureengineeringDatarepresentationModel selection:validationModel learning:training setModel evaluation:test setModel predictiongood enoughnot goodenough
Stages in machine learning

1. Data acquisition. Collect data for the task from databases, logs, sensors, web pages or surveys, with labels when the task is supervised. Example: 1,000 emails, each labelled spam or not spam. Noisy, biased or missing data limit every later stage.

2. Feature engineering. Turn raw data into useful features: remove noise, fill missing values, extract features (number of links, presence of words such as "free"), select the relevant ones and scale them. Min–max scaling, x′ = (x − min)/(max − min), maps link counts 2, 5 and 11 to 0, 0.333 and 1.

3. Data representation. Decide how each example is given to the learner: usually a fixed-length feature vector (one row of a pattern matrix), but also a string, tree or graph. Here each email becomes a vector of word counts and link counts.

4. Model selection. Choose the model family and its hyperparameters, for example a decision tree of a given depth, naive Bayes, or k-NN with a chosen k. Candidates are compared on a validation set or by cross-validation. Split used here: 700 training, 150 validation and 150 test emails.

5. Model learning. Fit the chosen model's parameters to the training set by minimising an error or maximising a likelihood, which is a search through the space of possible models.

6. Model evaluation. Measure the trained model on the test set, which it has never seen, with accuracy, precision, recall and F1 score (or mean squared error for regression). If 135 of the 150 test emails are classified correctly, accuracy = 135/150 = 0.90. If this is not good enough, go back to model selection or feature engineering.

7. Model prediction. Deploy the model to label new data, such as incoming mail, and keep monitoring its performance, because the data may change over time.

In short, the data stages (acquisition, feature engineering, representation) decide what the learner can see, and the model stages (selection, learning, evaluation, prediction) decide how well it generalises. Going round this loop several times is normal.

4 What is reinforcement learning? Explain the agent–environment interaction, reward, return, policy and value, and work out one Q-learning update. 10 marks
Model answer

Reinforcement learning (RL) is the paradigm in which an agent learns what to do by interacting with an environment and receiving rewards, instead of being shown correct answers. Unlike supervised learning, no correct label is given for any step; unlike unsupervised learning, there is feedback.

Agent and environment in reinforcement learningA loop: the agent, which follows policy π, sends action a(t) to the environment; the environment returns the next state s(t+1) and the reward r(t+1), and both go back to the agent.Agent (policy π)Next states(t+1)Reward r(t+1)Environmentaction a(t)
Agent and environment in reinforcement learning

1. Elements of RL.

  • Agent: the learner and decision maker, such as a robot.
  • Environment: everything the agent interacts with.
  • State s: the current situation, as the agent observes it.
  • Action a: a choice the agent makes in a state.
  • Reward r: a number returned after each action, saying how good the immediate result was.
  • Policy π: the agent's rule for choosing an action in each state.
  • Value function: the expected future reward from a state, V(s), or from taking action a in state s, Q(s, a).

2. The interaction loop. At time t the agent observes state s(t) and chooses action a(t) with its policy. The environment moves to state s(t+1) and returns reward r(t+1), and the loop repeats until the episode ends. The agent tries to maximise the return, the discounted sum of rewards G = r1 + γ r2 + γ² r3 + …, where the discount factor γ (0 ≤ γ ≤ 1) makes later rewards count less. For rewards 0, 0 and 10 with γ = 0.9, G = 0 + 0.9 × 0 + 0.81 × 10 = 8.1.

3. Q-learning. The agent keeps a table of Q(s, a) values and after every step updates one entry:

Q(s,a) ← Q(s,a)
   + α [r + γ max Q(s′,a′) − Q(s,a)]

Here α is the learning rate and the max is over the actions a′ in the next state s′. Worked update with Q(s, a) = 2, α = 0.5, γ = 0.9, r = 1 and max Q(s′, a′) = 5:

  • target = r + γ × max Q(s′, a′) = 1 + 0.9 × 5 = 5.5
  • error = 5.5 − 2 = 3.5
  • new Q(s, a) = 2 + 0.5 × 3.5 = 3.75

4. Exploration and exploitation. The agent must sometimes try new actions (explore) to find better rewards, and otherwise take the best known action (exploit). An ε-greedy policy takes a random action with probability ε, say 0.1, and the best known action otherwise.

5. Features. Learning is by trial and error, rewards are often delayed, and the data depend on the agent's own actions. RL is used in game playing (backgammon, Go), robot control and resource scheduling.

In short, RL learns a policy from rewards through repeated interaction, and Q-learning estimates action values from experience without needing a model of the environment.

5 Explain the types of data used in machine learning and how patterns of each type are matched. Then match the test pattern T = (4, 3) with the stored patterns P1 = (1, 1) and P2 = (2, 3) of class A and P3 = (5, 4) and P4 = (6, 6) of class B, using Euclidean and Manhattan distances. 10 marks
Model answer

Learning works on data, and most learning methods depend on matching: comparing a new pattern with stored patterns, or with a learned description, to decide how alike they are. How two patterns are matched depends on the type of data.

1. Types of data.

  • Numerical (quantitative): interval data have equal gaps but no true zero (temperature in °C); ratio data have a true zero (height, salary).
  • Categorical (qualitative): nominal data have no order (colour, blood group); ordinal data are ordered (grade low, medium, high).
  • Binary: two values such as 0/1; symmetric when both values matter equally, asymmetric when only a 1 (presence) matters, as with items in a shopping basket.
  • Structured data fit a table of rows and columns; unstructured data such as text, images and audio, and sequence or graph data such as time series and networks, are first turned into features.

2. Kinds of matching.

  • Exact matching: the stored pattern must equal the query, as in rote learning or a database lookup.
  • Approximate matching: a proximity measure (a distance or a similarity) finds the closest pattern.
  • Numerical data: Euclidean distance d = √Σ(xi − yi)² or Manhattan distance d = Σ|xi − yi|.
  • Nominal data: count the attributes that agree; (red, small, round) and (red, large, round) agree on 2 of 3, a similarity of 0.67.
  • Ordinal data: replace the levels by ranks (low = 1, medium = 2, high = 3) and use a numerical distance.
  • Binary data: Hamming distance, the simple matching coefficient, or the Jaccard coefficient, which ignores 0–0 matches and suits asymmetric data.

3. Worked example. Match the test pattern T = (4, 3) with the four stored patterns:

Pat  x1  x2  Class  Euclidean  Manhattan
P1    1   1    A      3.61         5
P2    2   3    A      2.00         2
P3    5   4    B      1.41         2
P4    6   6    B      3.61         5

For P3: Euclidean = √((4 − 5)² + (3 − 4)²) = √2 = 1.41 and Manhattan = |4 − 5| + |3 − 4| = 2. For P2: Euclidean = √(2² + 0²) = 2 and Manhattan = 2 + 0 = 2. In the figure E is the Euclidean and M the Manhattan distance.

Matching test pattern T = (4, 3) with stored patternsThe test pattern T = (4, 3) is joined to four stored patterns, each edge showing the Euclidean distance E and the Manhattan distance M: P1 class A (E 3.61, M 5), P2 class A (E 2.00, M 2), P3 class B (E 1.41, M 2) and P4 class B (E 3.61, M 5). P3 leads to the result: best match P3, class B.Test T = (4, 3)P1 (1, 1)class AP2 (2, 3)class AP3 (5, 4)class BP4 (6, 6)class BBest match:P3, class BE 3.61, M 5E 2.00, M 2E 1.41, M 2E 3.61, M 5smallest E
Matching test pattern T = (4, 3) with stored patterns
  • Euclidean distance: the best match is P3 (1.41), so T is given class B.
  • Manhattan distance: P2 (class A) and P3 (class B) tie at 2, so this match alone cannot decide the class. More neighbours do not help here, because P1 (A) and P4 (B) tie next at 5, so a tie-break rule is needed, such as another measure: the Euclidean distance picks P3.

In short, the matching measure must suit the data type, and the choice of measure can change which stored pattern counts as the best match, as the tie above shows.

6 Explain how learning can be viewed as search. Illustrate with the search space of feature subsets for three features, and compare exhaustive search with greedy forward selection. 10 marks
Model answer

Learning can be viewed as search. The learner explores a space of possible models (hypotheses) and looks for the one that best fits the training data under a criterion such as error, accuracy or likelihood. So every learner has a hypothesis space, an evaluation criterion and a search strategy.

1. Hypothesis spaces are huge. With d binary features there are 2^(2^d) Boolean functions, which is 65,536 for d = 4. If hypotheses are restricted to conjunctions in which each feature is 0, 1 or "don't care", there are only 3^d + 1 (the extra one rejects everything), which is 82 for d = 4. Such a restriction is a bias that makes the search feasible.

2. Search strategies.

  • Exhaustive search evaluates every candidate; it finds the best but only works for small spaces.
  • Greedy (hill-climbing) search takes the best local step and never goes back; decision tree induction chooses the best split at each node this way.
  • Gradient descent searches a continuous parameter space: w ← w − η ∂E/∂w. For E(w) = (w − 3)², η = 0.25 and a start at w = 0, w becomes 1.5, 2.25 and 2.625, approaching the minimum at w = 3.
  • Heuristic methods such as beam search and genetic algorithms trade some optimality for speed.

3. Worked example: feature subset selection. With features f1, f2 and f3 the search space is the 2^3 = 8 subsets, from the empty set up to {f1, f2, f3}. Assume these validation accuracies for a classifier trained on each subset:

Subset         Accuracy
{f1}           0.70
{f2}           0.80
{f3}           0.65
{f1, f2}       0.85
{f1, f3}       0.72
{f2, f3}       0.78
{f1, f2, f3}   0.83
Search space of feature subsets for f1, f2 and f3A lattice of feature subsets from the empty set at the top, through {f1}, {f2} and {f3}, then {f1, f2}, {f1, f3} and {f2, f3}, to {f1, f2, f3} at the bottom, each with its validation accuracy. Forward selection picks {f2} in step 1 and {f1, f2} in step 2, and stops because {f1, f2, f3} is worse.Empty set{f1}: 0.70{f2}: 0.80,step 1{f3}: 0.65{f1, f2}:0.85, step 2{f1, f3}: 0.72{f2, f3}: 0.78{f1, f2, f3}:0.83, stop
Search space of feature subsets for f1, f2 and f3
  • Exhaustive search evaluates all 7 non-empty subsets and picks {f1, f2} with 0.85.
  • Greedy forward selection starts from the empty set. Step 1: of {f1}, {f2} and {f3} the best is {f2} (0.80). Step 2: of {f1, f2} and {f2, f3} the best is {f1, f2} (0.85). Step 3: {f1, f2, f3} gives 0.83, which is lower, so it stops with {f1, f2} after 6 evaluations.
  • The saving grows quickly: for d = 20, exhaustive search needs 2^20 − 1 = 1,048,575 evaluations, but forward selection needs at most 20 × 21/2 = 210. The price is that greedy search can miss the best subset when features are useful only together.

In short, learning = hypothesis space + evaluation + search. A good learner restricts the space sensibly and uses a search method that finds a good hypothesis in reasonable time.

Unit 2

Nearest Neighbor-Based Models

Syllabus: Introduction to proximity measures; Distance measures; Non-metric similarity functions; Proximity between binary patterns; Classification algorithms based on distance measures; The k-nearest neighbor classifier; The radius distance nearest neighbor algorithm; KNN regression; Performance of classifiers; Performance of regression algorithms

One-page revision summary

  • A proximity measure says how alike (similarity) or how different (dissimilarity or distance) two patterns are, and every nearest neighbor method depends on it.
  • A metric distance satisfies non-negativity with d(x, y) = 0 if and only if x = y, symmetry, and the triangle inequality.
  • The Minkowski distance gives Manhattan distance for p = 1, Euclidean distance for p = 2 and Chebyshev distance (the largest difference) as p → ∞.
  • Features should be scaled, for example by min–max or z-score scaling, so that a feature with a large range does not dominate the distance.
  • Non-metric similarity functions, such as cosine similarity, squared Euclidean distance and KL divergence, break at least one metric property but can still rank neighbors.
  • For binary patterns, count n11, n10, n01 and n00 position by position before computing SMC, Jaccard or Hamming distance.
  • Jaccard suits asymmetric binary attributes, where a shared 0 means little, while SMC suits symmetric ones.
  • Classifiers based on distance measures include 1-NN, k-NN, distance-weighted k-NN, the minimum distance (nearest mean) classifier and the radius distance nearest neighbor algorithm.
  • k-NN is a lazy learner: it stores the training set and labels a test pattern by a majority vote of its k closest training patterns.
  • A small k is sensitive to noise and a large k blurs class boundaries; an odd k avoids two-class ties, and k is chosen by cross-validation.
  • The radius distance nearest neighbor algorithm votes among all training patterns within distance r and rejects a test pattern with no neighbor inside r as an outlier.
  • KNN regression predicts the mean, or the distance-weighted mean, of the target values of the k nearest training patterns.
  • A confusion matrix counts TP, FN, FP and TN, and accuracy, error rate, precision, recall, specificity and F1 are computed from it.
  • Accuracy can mislead when classes are imbalanced, so precision, recall and F1 are reported alongside it.
  • Classifiers and regressors are tested by hold-out, k-fold cross-validation or leave-one-out, never on their own training data.
  • Regression algorithms are judged by MAE, MSE, RMSE and R²; R² = 1 is a perfect fit and R² = 0 is no better than predicting the mean.

Learn these by heart

  • Minkowski: Lp(x, y) = (Σ |xi − yi|^p)^(1/p); L1 is Manhattan, L2 is Euclidean, L∞ = max |xi − yi|.
  • Metric: d(x, y) ≥ 0, and d(x, y) = 0 if and only if x = y; d(x, y) = d(y, x); d(x, z) ≤ d(x, y) + d(y, z).
  • Cosine similarity: cos θ = (x · y)/(‖x‖ ‖y‖).
  • SMC = (n11 + n00)/(n11 + n10 + n01 + n00); Jaccard = n11/(n11 + n10 + n01); Hamming = n10 + n01.
  • Accuracy = (TP + TN)/N; precision = TP/(TP + FP); recall = TP/(TP + FN); F1 = 2PR/(P + R).
  • MAE = Σ|y − ŷ|/n; MSE = Σ(y − ŷ)²/n; RMSE = √MSE; R² = 1 − Σ(y − ŷ)²/Σ(y − ȳ)².

2-mark questions

1 What is a proximity measure? How are similarity and dissimilarity related? 2 marks
Model answer

A proximity measure is a number that says how alike or how different two patterns are. A similarity is large for alike patterns; a dissimilarity (distance) is small for them and zero for identical patterns. One converts to the other, for example s = 1/(1 + d), or d = 1 − s when s lies in [0, 1].

2 Find the Manhattan, Euclidean and Chebyshev distances between X = (2, 3) and Y = (5, 7). 2 marks
Model answer

The coordinate differences are |2 − 5| = 3 and |3 − 7| = 4.

  • Manhattan (p = 1): 3 + 4 = 7
  • Euclidean (p = 2): √(3² + 4²) = √25 = 5
  • Chebyshev (p → ∞): max(3, 4) = 4

All three are Minkowski distances; here the value falls as p grows.

3 What is a non-metric similarity function? Give an example. 2 marks
Model answer

It is a proximity function that breaks at least one metric property, usually the triangle inequality or symmetry. Squared Euclidean distance is an example: for the points 0, 1 and 2 on a line, d(0,2) = 4, which exceeds d(0,1) + d(1,2) = 1 + 1 = 2. Kullback–Leibler (KL) divergence, which is not symmetric, is another.

4 Find the simple matching coefficient (SMC) and the Jaccard coefficient for the binary patterns x = 1 1 0 0 1 0 and y = 1 0 0 1 1 0. 2 marks
Model answer

Comparing position by position: n11 = 2 (both 1), n10 = 1, n01 = 1 and n00 = 2 (both 0).

  • SMC = (n11 + n00)/6 = 4/6 = 0.667
  • Jaccard = n11/(n11 + n10 + n01) = 2/4 = 0.5

Jaccard ignores the 0–0 matches, so it suits sparse patterns where a shared 0 means little.

5 What is the radius distance nearest neighbor algorithm? 2 marks
Model answer

Instead of a fixed number k of neighbors, it takes every training pattern lying within a chosen distance r of the test pattern and assigns the majority class among them. The number of neighbors therefore changes with the local density. If no pattern lies within r, the test pattern is rejected as an outlier, or r is enlarged.

6 Define precision and recall of a classifier. 2 marks
Model answer

For the positive class, precision = TP/(TP + FP) is the fraction of patterns predicted positive that really are positive, and recall = TP/(TP + FN) is the fraction of actual positives that the classifier finds. For example, TP = 8, FP = 2 and FN = 4 give precision = 8/10 = 0.8 and recall = 8/12 = 0.667.

10-mark questions

1 What is a proximity measure? State the properties of a metric and explain the Minkowski family of distance measures with a numerical example. 10 marks
Model answer

Nearest neighbor methods classify a pattern by comparing it with stored patterns, so they need a proximity measure: a function that says how alike (similarity) or how different (dissimilarity, or distance) two patterns are. A distance is small for alike patterns and zero for identical ones; a similarity is large for alike patterns. One can be converted into the other, for example s = 1/(1 + d).

1. Properties of a metric. A distance d is a metric when, for all patterns x, y and z:

  • Non-negativity: d(x, y) ≥ 0, with d(x, y) = 0 if and only if x = y.
  • Symmetry: d(x, y) = d(y, x).
  • Triangle inequality: d(x, z) ≤ d(x, y) + d(y, z).

A measure that breaks any of these is non-metric.

2. Minkowski distance. For patterns with n features,

Lp(x, y) = (Σ |xi − yi|^p)^(1/p), with p ≥ 1.

  • p = 1: Manhattan (city-block) distance, the sum of the absolute differences.
  • p = 2: Euclidean distance, the straight-line distance.
  • p → ∞: Chebyshev distance, the largest single difference.

Every Lp with p ≥ 1 is a metric.

Proximity measures and the Minkowski family for X = (1, 4, 2), Y = (4, 0, 8)A tree: a proximity measure is either a similarity or a dissimilarity (distance), linked by s = 1/(1 + d); a distance is metric or non-metric, and the metric Minkowski Lp distance gives Manhattan (p = 1, L1 = 13), Euclidean (p = 2, L2 = 7.810) and Chebyshev (p → ∞, L∞ = 6).ProximitymeasureDissimilarity(distance)SimilarityMetricNon-metricMinkowski LpManhattan:L1 = 13Euclidean:L2 = 7.810Chebyshev:L∞ = 6s = 1/(1 + d)breaks apropertyp = 1p = 2p → ∞
Proximity measures and the Minkowski family for X = (1, 4, 2), Y = (4, 0, 8)

3. Worked example. X = (1, 4, 2) and Y = (4, 0, 8). The absolute differences are 3, 4 and 6.

  • L1 = 3 + 4 + 6 = 13
  • L2 = √(9 + 16 + 36) = √61 = 7.810
  • L3 = (27 + 64 + 216)^(1/3) = 307^(1/3) = 6.746
  • L∞ = max(3, 4, 6) = 6

The distance never increases as p grows, and the biggest difference dominates more and more.

4. Practical points.

  • A feature measured on a large scale dominates the sum, so features are normally scaled first, for example by min–max scaling to [0, 1] or by z-scores.
  • Euclidean distance squares each difference, so one large difference counts for more than it does in Manhattan distance.
  • Mahalanobis distance, √((x − y)ᵀ S⁻¹ (x − y)) with S the covariance matrix, also allows for different scales and correlated features.

In short, a proximity measure is the heart of every nearest neighbor method, and the Minkowski family gives a range of metric distances from L1 to L∞.

2 Explain non-metric similarity functions with examples. How is proximity measured between binary patterns? Compute the simple matching coefficient, the Jaccard coefficient and the Hamming distance for two binary patterns. 10 marks
Model answer

Many useful proximity measures do not satisfy all the metric properties (non-negativity with d(x, y) = 0 if and only if x = y, symmetry and the triangle inequality). They are called non-metric similarity functions. A plain nearest neighbor search can still use them, because it only ranks the stored patterns by proximity.

1. Non-metric similarity functions.

  • Cosine similarity: cos θ = (x · y)/(‖x‖ ‖y‖). It compares direction, not length, so it suits documents described by word counts. For x = (2, 1, 0) and y = (4, 2, 0), cos θ = 1 although x ≠ y, so the cosine distance 1 − cos θ is 0 for two different patterns, which breaks the identity property.
  • Squared Euclidean distance breaks the triangle inequality: for the points 0, 1 and 2 on a line, 4 > 1 + 1.
  • Kullback–Leibler (KL) divergence between probability distributions is not symmetric: for P = (0.5, 0.5) and Q = (0.9, 0.1), KL(P‖Q) = 0.511 but KL(Q‖P) = 0.368 (natural logarithms).

2. Binary patterns. When every feature is 0 or 1 (absent or present), compare x and y position by position and count n11 (both 1), n10 (x is 1, y is 0), n01 (x is 0, y is 1) and n00 (both 0). Then:

  • Simple matching coefficient SMC = (n11 + n00)/(n11 + n10 + n01 + n00), which counts agreements of both kinds.
  • Jaccard coefficient J = n11/(n11 + n10 + n01), the size of the overlap of the two sets of 1s divided by the size of their union; it ignores 0–0 matches.
  • Hamming distance H = n10 + n01, the number of positions that differ.

3. Worked example. Two shopping baskets over 8 items (1 = bought):

Item  1 2 3 4 5 6 7 8
x     1 0 1 0 0 0 0 0
y     1 0 0 0 0 1 0 0

n11 = 1 (item 1), n10 = 1 (item 3), n01 = 1 (item 6) and n00 = 5.

  • SMC = (1 + 5)/8 = 0.75
  • J = 1/(1 + 1 + 1) = 0.333
  • H = 1 + 1 = 2
Items bought in baskets x and yTwo overlapping circles for the items bought in x (items 1 and 3) and in y (items 1 and 6): the overlap holds item 1 (n11 = 1), x only holds item 3 (n10 = 1) and y only holds item 6 (n01 = 1), while the 5 items outside both circles are the 0–0 matches (n00 = 5), so Jaccard = overlap/union = 1/3.Universe: 8 items; n00 = 5 outsideItems bought in xitems 1 and 3Items bought in yitems 1 and 6n11 = 1(item 1)n10 = 1(item 3)n01 = 1(item 6)
Items bought in baskets x and y

SMC calls the baskets fairly similar only because both customers skipped the same five items. Jaccard looks only at items bought by at least one of them, so it gives the fairer value for such asymmetric attributes. SMC suits symmetric attributes, where 0 and 1 matter equally, such as day shift or night shift.

In short, non-metric functions widen the choice of proximity, and for binary patterns the choice between SMC and Jaccard depends on whether a shared 0 carries meaning.

3 Explain the k-nearest neighbor (k-NN) classifier and other classification algorithms based on distance measures. Classify the test pattern Q = (4, 4) with k = 1, 3 and 5, using the training patterns P1 (3, 3) A, P2 (5, 4) B, P3 (4, 6) A, P4 (2, 5) A, P5 (6, 6) B, P6 (7, 3) B, P7 (1, 1) A and P8 (8, 5) B. 10 marks
Model answer

Nearest neighbor methods are the simplest classification algorithms based on distance measures. They store the labelled training patterns and do all the work when a test pattern arrives, so they are called lazy learners.

1. Distance-based classifiers.

  • Nearest neighbor (1-NN): the test pattern takes the class of the single closest training pattern.
  • k-nearest neighbor (k-NN): find the k closest training patterns and take a majority vote.
  • Distance-weighted k-NN: each neighbor votes with a weight such as 1/d, so closer neighbors count more.
  • Minimum distance classifier: each class is represented by its mean, and the closest mean wins.

2. The k-NN algorithm.

  • Compute the distance (here Euclidean) from Q to every training pattern.
  • Sort the training patterns by distance.
  • Take the first k and assign the class with the most votes.

3. Worked example. Squared distances d² keep the arithmetic exact:

Pt  x1 x2 Class  d²      d
P2  5  4  B       1  1.000
P1  3  3  A       2  1.414
P3  4  6  A       4  2.000
P4  2  5  A       5  2.236
P5  6  6  B       8  2.828
P6  7  3  B      10  3.162
P8  8  5  B      17  4.123
P7  1  1  A      18  4.243
  • k = 1: the nearest pattern is P2, so Q is class B.
  • k = 3: P2 (B), P1 (A) and P3 (A) give A 2, B 1, so Q is class A.
  • k = 5: adding P4 (A) and P5 (B) gives A 3, B 2, so Q is class A.
3-NN decision for the test pattern Q = (4, 4)The test pattern Q (4, 4) is linked to its three nearest neighbors: P2 (5, 4) of class B at distance 1.000, P1 (3, 3) of class A at 1.414 and P3 (4, 6) of class A at 2.000. Their vote is A 2, B 1, so Q is class A.3 nearest neighborsQ (4, 4)P1 (3, 3): AP2 (5, 4): BP3 (4, 6): AVote: A 2, B 1Q is class Ad = 1.414d = 1.000d = 2.000
3-NN decision for the test pattern Q = (4, 4)

Distance-weighted 3-NN with w = 1/d gives class A a total weight of 1/1.414 + 1/2 = 1.207 and class B 1/1 = 1.000, so again A. The minimum distance classifier uses the class means A = (2.5, 3.75) and B = (6.5, 4.5); Q lies 1.521 from mean A and 2.550 from mean B, so it also says A.

4. Choosing k and practical points.

  • A small k depends on one or two neighbors, so a single noisy pattern can change the answer; here k = 1 alone gives B.
  • A large k smooths the decision but lets a bigger class outvote a smaller one.
  • An odd k avoids ties between two classes, and k is usually chosen by cross-validation.
  • Features should be scaled first, and each test pattern needs a distance to every training pattern, which is slow for a large training set.

In conclusion, k-NN needs no training and can follow class boundaries of any shape; here it classifies Q as class A for k = 3 and k = 5.

4 Explain the radius distance nearest neighbor algorithm and compare it with the k-NN classifier. With radius r = 1.5, classify T1 = (2, 2) and T2 = (8, 1) using the training patterns R1 (1, 1) A, R2 (1, 2) A, R3 (2, 1) A, R4 (3, 3) B, R5 (4, 4) B, R6 (5, 4) B and R7 (4, 5) B. 10 marks
Model answer

The k-NN classifier always uses a fixed number k of neighbors, however far away they are. The radius distance nearest neighbor algorithm fixes a distance instead: every training pattern within radius r of the test pattern takes part in the vote.

1. Algorithm.

radius_nn(train, t, r):
  near = [c for (p, c) in train
          if dist(p, t) <= r]
  if near is empty:
    return "reject (outlier)"
  return majority class in near
  • Compute the distance from t to every training pattern.
  • Keep the patterns with distance ≤ r; they form the neighborhood of t.
  • Assign the majority class of the neighborhood. If it is empty, reject t as an outlier, enlarge r or fall back to 1-NN.

2. Worked example, r = 1.5, Euclidean distance. Distances from T1 = (2, 2):

Pt  Point   Class      d
R2  (1, 2)  A      1.000
R3  (2, 1)  A      1.000
R1  (1, 1)  A      1.414
R4  (3, 3)  B      1.414
R5  (4, 4)  B      2.828
R6  (5, 4)  B      3.606
R7  (4, 5)  B      3.606

Four patterns lie within 1.5: R1, R2 and R3 (class A) and R4 (class B). The vote is A 3, B 1, so T1 is class A.

Radius distance nearest neighbor decisions with r = 1.5T1 (2, 2) has four training patterns within radius 1.5: R2 and R3 of class A at 1.000, and R1 of class A and R4 of class B at 1.414; the vote A 3, B 1 makes T1 class A. T2 (8, 1) has no training pattern within 1.5, so it is rejected as an outlier.Within r = 1.5 of T1T1 (2, 2)R2: A, d = 1.000R3: A, d = 1.000R1: A, d = 1.414R4: B, d = 1.414Vote: A 3, B 1T1 is class AT2 (8, 1)No patternwithin r = 1.5Reject T2 asan outliernearest 4.243
Radius distance nearest neighbor decisions with r = 1.5

For T2 = (8, 1), the nearest pattern is R6 at √18 = 4.243, far beyond r, so the neighborhood is empty and T2 is rejected as an outlier. A 3-NN classifier would still call T2 class B (R6 at 4.243, R5 at 5.000, R4 at 5.385), even though T2 is far from every training pattern.

3. Comparison with k-NN.

  • Neighborhood: k-NN uses a fixed count; the radius method uses a fixed region, so its count changes with the local density (four for T1, none for T2).
  • Outliers: the radius method can refuse to classify a pattern unlike anything in the training set; k-NN always answers.
  • Parameter: r depends on the scale of the features, so features are scaled first, and r is chosen by validation, just as k is.
  • Weakness: in sparse regions a small r leaves many patterns unclassified, while a large r lets a dense class outvote a sparse one.

In conclusion, the radius distance nearest neighbor algorithm suits data whose density varies and can flag outliers; here it labels T1 as class A and rejects T2.

5 How is the performance of a classifier measured? Explain the ways of testing a classifier, the confusion matrix and the measures derived from it. A k-NN spam filter tested on 50 e-mails gives TP = 18, FN = 4, FP = 6 and TN = 22; compute its accuracy, error rate, precision, recall, specificity and F1 score. 10 marks
Model answer

A classifier is judged by how well it labels patterns it has not seen. Scoring it on its own training data is misleading, above all for 1-NN, where each training pattern is its own nearest neighbor. So the data are split, and the predictions on the test part are summarised in a confusion matrix.

1. Ways of testing.

  • Hold-out: train on, say, two-thirds of the data and test on the rest.
  • k-fold cross-validation: split the labelled data into k folds; each fold i in turn is the test set while the other k − 1 folds form the training set, and the k scores are averaged.
  • Leave-one-out: k-fold with one pattern per fold. It is cheap for k-NN, which has no model to retrain, and is a common way to choose k.
k-fold cross-validation of a classifierThe labelled data are split into k folds; fold i is the test set while the other k − 1 folds form the training set; the classifier labels fold i and its score is recorded, the loop moves to the next fold, and after k folds the k scores are averaged.Labelled dataSplit intok foldsFold i: test setOther k − 1folds: trainingClassify foldi, score itAverage thek scoresi = 1next foldi + 1after k folds
k-fold cross-validation of a classifier

2. Confusion matrix (two classes). Rows give the actual class and columns the predicted class:

              Pred spam  Pred not
Actual spam   TP = 18    FN = 4
Actual not    FP = 6     TN = 22

3. Measures, worked for the spam filter (N = 50):

  • Accuracy = (TP + TN)/N = 40/50 = 0.80
  • Error rate = 1 − accuracy = 0.20
  • Precision = TP/(TP + FP) = 18/24 = 0.75: of the e-mails flagged as spam, 75% were spam.
  • Recall (sensitivity) = TP/(TP + FN) = 18/22 = 0.818: the filter caught 81.8% of the spam.
  • Specificity = TN/(TN + FP) = 22/28 = 0.786: 78.6% of genuine e-mails got through.
  • F1 = 2PR/(P + R) = 2 × 0.75 × 0.818/(0.75 + 0.818) = 0.783, the harmonic mean of precision and recall.

4. Reading the measures.

  • Accuracy hides class imbalance: a filter that calls every e-mail not spam scores 28/50 = 0.56 here, and far more when spam is rare, yet it catches nothing.
  • Precision matters when a false alarm is costly (a genuine e-mail lost); recall matters when a miss is costly (a disease left undetected).
  • With more than two classes, the matrix has one row and one column per class, and precision and recall are found for each class and then averaged.

In conclusion, a confusion matrix built from cross-validated predictions gives a fair picture of a classifier; this filter has accuracy 0.80, precision 0.75, recall 0.818 and F1 0.783.

6 Explain KNN regression and the measures used to judge a regression algorithm. A KNN regressor with k = 2 is trained on (x, y) = (1, 3.0), (2, 4.0), (3, 6.0), (5, 7.0), (6, 9.0) and (8, 10.0). Predict y for the test inputs x = 1.6, 2.4, 4.6 and 7.4, whose actual values are 3.2, 4.5, 7.4 and 9.6, and compute MAE, MSE, RMSE and R². 10 marks
Model answer

In regression the target is a number, not a class. KNN regression keeps the nearest neighbor idea but replaces the vote by an average.

1. KNN regression.

  • Find the k training patterns nearest to the test input.
  • Predict ŷ as the mean of their y values, or as the distance-weighted mean Σ wi yi / Σ wi with wi = 1/di.
  • A small k follows noise; a large k flattens the prediction towards the overall mean.
KNN regression and its evaluationA test input x and the training set (x, y) feed a step that finds the k = 2 nearest xi; the prediction ŷ is the mean of their y values; ŷ and the actual y give the error e = y − ŷ, and the errors over the test set give MAE, MSE, RMSE and R².Test input xTrainingset (x, y)Find k = 2nearest xiŷ = meanof their yActual yError e = y − ŷMAE, MSE,RMSE, R²over thetest set
KNN regression and its evaluation

2. Predictions with k = 2. There is one input, so d = |x − xi|. Each neighbor is written as its xi with the distance in brackets:

x    nearest xi (d)    ŷ    y    y − ŷ
1.6  2 (0.4), 1 (0.6)  3.5  3.2  −0.3
2.4  2 (0.4), 3 (0.6)  5.0  4.5  −0.5
4.6  5 (0.4), 6 (1.4)  8.0  7.4  −0.6
7.4  8 (0.6), 6 (1.4)  9.5  9.6   0.1

For example, at x = 2.4 the neighbors are x = 2 (y = 4.0) and x = 3 (y = 6.0), so ŷ = (4.0 + 6.0)/2 = 5.0. With 1/d weights (1/0.4 = 2.5 and 1/0.6 = 1.667) the prediction becomes (2.5 × 4.0 + 1.667 × 6.0)/(2.5 + 1.667) = 4.8, nearer the closer neighbor.

3. Performance of regression algorithms, with errors e = y − ŷ over n = 4 test points:

  • Mean absolute error MAE = Σ|e|/n = (0.3 + 0.5 + 0.6 + 0.1)/4 = 1.5/4 = 0.375
  • Mean squared error MSE = Σe²/n = (0.09 + 0.25 + 0.36 + 0.01)/4 = 0.71/4 = 0.1775
  • Root mean squared error RMSE = √MSE = √0.1775 = 0.421, in the same units as y
  • Coefficient of determination R² = 1 − SSres/SStot. The mean of the actual values is ȳ = 6.175, SStot = Σ(y − ȳ)² = 24.8875 and SSres = Σe² = 0.71, so R² = 1 − 0.71/24.8875 = 0.971.

4. Reading the measures.

  • MAE treats all errors alike; MSE and RMSE square them, so they punish large errors more.
  • R² = 1 is a perfect fit, R² = 0 is no better than always predicting the mean, and R² is negative for a model worse than that.
  • Like classifiers, regressors are judged on test data or by cross-validation, never on their training points.

In conclusion, KNN regression predicts by averaging nearby targets; here it explains about 97% of the variation in the test targets, with an RMSE of 0.421.

Unit 3

Models Based on Decision Trees and the Bayes Classifier

Syllabus: Decision trees for classification; Impurity measures; Properties of decision trees; Regression based on decision trees; The bias-variance trade-off; Random forests for classification and regression; Introduction to the Bayes classifier: Bayes' rule and inference; The Bayes classifier and its optimality; Multi-class classification; Class conditional independence and the naive Bayes classifier

One-page revision summary

  • A decision tree classifies a pattern by applying feature tests from the root down to a leaf, whose class label is the prediction.
  • Trees are grown top-down and greedily, choosing at each node the test with the largest impurity reduction and stopping when a node is pure or too small.
  • Entropy, the Gini index and the misclassification error 1 − max pi are impurity measures that are zero for a pure node and largest when the classes are equally mixed.
  • Information gain favours attributes with many values, and the gain ratio, gain divided by split information, corrects this bias.
  • Decision trees read as if-then rules, need no feature scaling, handle mixed feature types and give axis-parallel decision boundaries.
  • A fully grown tree overfits and is unstable, so stopping rules (pre-pruning) or pruning after growth (post-pruning) are used.
  • A regression tree picks the split that minimises the sum of squared errors and predicts the mean target of a leaf, giving a piecewise constant function.
  • Shallow trees have high bias and low variance, deep trees have low bias and high variance, and the depth is tuned on validation data.
  • A random forest grows many deep trees on bootstrap samples with a random subset of features at each node and combines them by majority vote or by averaging.
  • On average about 36.8% of the patterns are left out of each bootstrap sample, and predicting them with the trees that did not see them gives the out-of-bag error estimate.
  • Bayes' rule updates the prior P(Ci) to the posterior P(Ci|x) using the likelihood P(x|Ci) and the evidence P(x).
  • The Bayes classifier chooses the class with the largest posterior and has the lowest possible error, the Bayes error, when priors and class conditional densities are known.
  • With equal priors, the Bayes classifier reduces to choosing the class with the largest likelihood P(x|Ci).
  • For C classes the Bayes classifier simply picks the largest of C posteriors, while two-class methods need schemes such as one-vs-rest (C classifiers) or one-vs-one (C(C − 1)/2 classifiers).
  • Naive Bayes assumes the features are independent given the class, so it needs only one-dimensional probabilities for each feature and class.
  • A zero count makes a whole naive Bayes product zero, so Laplace smoothing adds one to every count.
  • For continuous features, Gaussian naive Bayes models each feature within each class by a normal density with its own mean and variance.

Learn these by heart

  • Entropy H(S) = −Σ pi log2 pi; Gini(S) = 1 − Σ pi²; Gain(S, A) = H(S) − Σv (|Sv|/|S|) H(Sv).
  • Regression tree split: minimise SSE = Σleft (y − ȳL)² + Σright (y − ȳR)²; a leaf predicts the mean y.
  • Expected squared error = Bias² + Variance + irreducible noise σ².
  • Bayes' rule: P(Ci|x) = P(x|Ci) P(Ci) / Σj P(x|Cj) P(Cj).
  • Bayes classifier: choose the class maximising P(x|Ci) P(Ci); P(error|x) = 1 − max P(Ci|x).
  • Naive Bayes: P(x|Ci) = Π P(xj|Ci); Laplace estimate (count + 1)/(nC + k).
  • Random forest: bootstrap samples plus m random features per node (m ≈ √d for classification); vote for classes, average for regression.

2-mark questions

1 Calculate the entropy and the Gini index of a decision tree node that holds 6 positive and 2 negative training examples. 2 marks
Model answer

Here p+ = 6/8 = 0.75 and p− = 2/8 = 0.25.

Entropy = −0.75 log2 0.75 − 0.25 log2 0.25 = 0.3113 + 0.5 = 0.8113 bits.

Gini index = 1 − (0.75² + 0.25²) = 1 − 0.625 = 0.375.

Both are 0 for a pure node; for two classes their maximums are 1 and 0.5.

2 State two advantages and two limitations of decision tree classifiers. 2 marks
Model answer

Advantages:

  • Easy to interpret: every root-to-leaf path is an if-then rule.
  • Handle numeric and categorical features directly, with no feature scaling.

Limitations:

  • Greedy splitting gives only a locally best tree, and a fully grown tree overfits.
  • Unstable: a small change in the training data can produce a very different tree.
3 What is the bias-variance trade-off in a learning model? 2 marks
Model answer

The expected squared error of a model is bias² + variance + irreducible noise. Bias is the error from overly simple assumptions (underfitting); variance is the sensitivity of the model to the particular training sample (overfitting). Making a model more flexible, for example growing a deeper tree, lowers bias but raises variance, so the best model balances the two.

4 Why does a random forest choose a random subset of features at each split? 2 marks
Model answer

With all d features available, the same strong features would be chosen near the root of every tree, making the trees highly correlated, so averaging them would remove little variance. Choosing m of the d features at random at each node (commonly m ≈ √d for classification) decorrelates the trees and lowers the variance of their combined vote.

5 Why is the Bayes classifier said to be optimal? 2 marks
Model answer

The Bayes classifier assigns x to the class with the largest posterior P(Ci|x). The probability of error at x is then 1 − max P(Ci|x), the smallest possible value at every x. Hence its total error, the Bayes error, is the lowest that any classifier can achieve when the true priors and class conditional densities are known.

6 State the naive Bayes rule for assigning a pattern x = (x1, …, xd) to one of C classes. 2 marks
Model answer

Under class conditional independence the features are independent given the class, so P(x|Ci) = P(x1|Ci) × P(x2|Ci) × … × P(xd|Ci). Naive Bayes assigns x to class Ck, where k is the value of i = 1, …, C that maximises P(Ci) × Π P(xj|Ci). The evidence P(x) is dropped because it is the same for every class.

10-mark questions

1 Explain how a decision tree classifies a pattern. Describe the top-down procedure for building a decision tree and discuss the properties of decision trees. 10 marks
Model answer

A decision tree is a supervised classifier that arranges tests on feature values as a tree. Each internal node tests one feature, each branch is one outcome of that test, and each leaf holds a class label.

Classifying a pattern: start at the root, apply its test, follow the branch that matches the pattern's value, and repeat until a leaf is reached; the leaf's label is the predicted class. In the loan tree below, the root tests Credit history; a Bad history gives Reject, while a Good history leads to a test on Income, and Low income leads to a test on Employed, where Yes gives Approve and No gives Reject. An applicant with a good credit history, low income and a job is therefore classified as Approve after three tests.

Decision tree for a loan applicationThe root tests Credit history: Bad leads to the leaf Reject and Good leads to a test on Income. High income leads to Approve, and Low income leads to a test on Employed, where Yes gives Approve and No gives Reject.Credit history?RejectIncome?Employed?ApproveApproveRejectBadGoodLowHighYesNo
Decision tree for a loan application

Building the tree (top-down and greedy):

1. Place all training patterns at the root.

2. If all patterns at a node belong to one class, or a stopping rule holds (too few patterns, maximum depth reached), make the node a leaf labelled with the majority class.

3. Otherwise, for every candidate feature (and every threshold of a numeric feature) compute the reduction in impurity, measured by entropy (information gain) or the Gini index.

4. Choose the test with the largest reduction and create one child for each outcome.

5. Send each pattern to the child that matches its outcome and repeat steps 2 to 4 on every child.

6. Prune the grown tree by removing branches that do not improve accuracy on validation data.

Properties of decision trees:

  • Interpretability: every root-to-leaf path is an if-then rule, for example IF Credit history = Good AND Income = High THEN Approve.
  • Axis-parallel boundaries: a test such as x1 ≤ 5 cuts the feature space with a boundary parallel to an axis, so the decision regions are rectangles (hyper-rectangles).
  • Mixed data: categorical and numeric features are handled directly, and no feature scaling is needed.
  • Built-in feature selection: a feature that never reduces impurity is never used.
  • Multi-class: a leaf can carry any of several class labels, so more than two classes need no extra scheme.
  • Greedy construction: each split is only locally best; finding the smallest tree that fits the training data is NP-hard, so heuristics are used.
  • Overfitting and instability: a fully grown tree fits noise, and a small change in the data can change the tree; pruning or ensembles such as random forests reduce this.

In conclusion, a decision tree is a fast, readable classifier built greedily by choosing the purest split at each node, and it must be pruned to generalise well.

2 State Bayes' rule and explain how it is used for inference. Describe the Bayes classifier for C classes and show why it is optimal. Classify a pattern x given P(C1) = 0.5, P(C2) = 0.3, P(C3) = 0.2 and P(x|C1) = 0.1, P(x|C2) = 0.4, P(x|C3) = 0.3. 10 marks
Model answer

Bayes' rule links the probability of a class before and after the data are seen. For classes Ci (i = 1, …, C) and a feature vector x:

P(Ci|x) = P(x|Ci) P(Ci) / P(x), where P(x) = Σj P(x|Cj) P(Cj)

  • P(Ci) is the prior: the belief in class Ci before x is seen.
  • P(x|Ci) is the likelihood, the class conditional probability (or density) of x.
  • P(x) is the evidence; it is the same for every class and only normalises.
  • P(Ci|x) is the posterior.

Inference: Bayes' rule turns knowledge of how each class generates data, P(x|Ci), into knowledge of which class produced the observed x, P(Ci|x). The prior is updated by the evidence: posterior ∝ likelihood × prior.

The Bayes classifier assigns x to class Ck, where k is the i that maximises P(x|Ci) P(Ci). The rule is the same for any number of classes, so multi-class classification needs no extra scheme: compute C products and pick the largest.

Bayes classifier for three classesThe feature vector x feeds three products, P(x|C1)P(C1), P(x|C2)P(C2) and P(x|C3)P(C3), worth 0.05, 0.12 and 0.06. They are divided by P(x) = 0.23, the largest posterior 0.5217 is picked, and x is assigned to C2.Feature vector xP(x|C1) P(C1)P(x|C2) P(C2)P(x|C3) P(C3)Divide byP(x) = 0.23Largestposterior 0.5217Assign x to C20.050.120.06
Bayes classifier for three classes

Optimality:

1. If x is assigned to Ck, the probability of error at x is P(error|x) = 1 − P(Ck|x).

2. This is smallest when P(Ck|x) is the largest posterior, which is exactly the Bayes choice.

3. The overall error is P(error) = ∫ P(error|x) p(x) dx. Since p(x) ≥ 0, making the error smallest at every x makes the integral smallest.

4. So when the priors and likelihoods are known, no classifier has a lower error probability; this minimum is the Bayes error.

Worked example (three classes):

Class P(Ci) P(x|Ci) Product Posterior
C1    0.5   0.1     0.05    0.2174
C2    0.3   0.4     0.12    0.5217
C3    0.2   0.3     0.06    0.2609
Total               0.23    1.0000

1. Products: 0.5 × 0.1 = 0.05, 0.3 × 0.4 = 0.12, 0.2 × 0.3 = 0.06.

2. Evidence: P(x) = 0.05 + 0.12 + 0.06 = 0.23.

3. Posteriors (divide each product by P(x)): 0.05/0.23 = 0.2174, 0.12/0.23 = 0.5217, 0.06/0.23 = 0.2609.

4. The largest posterior is 0.5217, so x is assigned to C2, with P(error|x) = 1 − 0.5217 = 0.4783.

C1 has the largest prior, but the likelihood of x moves the decision to C2.

In conclusion, Bayes' rule converts priors and likelihoods into posteriors, and choosing the class with the maximum posterior gives the minimum possible probability of error.

3 Eight students are described by (CGPA, Internship, Sports → Placed): (High, No, No → Yes), (High, Yes, No → Yes), (High, Yes, Yes → Yes), (Medium, No, No → No), (Medium, Yes, No → Yes), (Low, No, No → No), (Low, No, Yes → No), (Low, Yes, No → No). Build a decision tree using information gain and classify a student with Medium CGPA, an internship and sports. 10 marks
Model answer

A decision tree is built top-down: at each node the attribute with the largest information gain becomes the test. Entropy is H(S) = −Σ pi log2 pi, and the gain of attribute A is Gain(S, A) = H(S) − Σv (|Sv|/|S|) H(Sv).

No CGPA   Intern Sports Placed
1  High   No     No     Yes
2  High   Yes    No     Yes
3  High   Yes    Yes    Yes
4  Medium No     No     No
5  Medium Yes    No     Yes
6  Low    No     No     No
7  Low    No     Yes    No
8  Low    Yes    No     No

Step 1: Entropy of the whole set. There are 4 Yes and 4 No, so H(S) = −0.5 log2 0.5 − 0.5 log2 0.5 = 1.

Step 2: Gain of each attribute.

Attribute  Branch  Yes No  H(Sv)
CGPA       High    3   0   0
           Medium  1   1   1
           Low     0   3   0
Internship Yes     3   1   0.8113
           No      1   3   0.8113
Sports     Yes     1   1   1
           No      3   3   1
  • CGPA: remainder = (3/8)(0) + (2/8)(1) + (3/8)(0) = 0.25, so Gain = 1 − 0.25 = 0.75.
  • Internship: H(3/4, 1/4) = −0.75 log2 0.75 − 0.25 log2 0.25 = 0.8113; remainder = (4/8)(0.8113) + (4/8)(0.8113) = 0.8113, so Gain = 0.1887.
  • Sports: both branches are half Yes and half No, so remainder = 1 and Gain = 0.

CGPA has the largest gain (0.75) and becomes the root.

Step 3: Expand the branches. High (students 1 to 3) are all Yes, giving the leaf Placed = Yes. Low (students 6 to 8) are all No, giving the leaf Placed = No. Medium holds students 4 (No) and 5 (Yes), with entropy 1.

Step 4: Split the Medium branch. Internship separates it perfectly (Yes: student 5, Placed = Yes; No: student 4, Placed = No), so its gain is 1 − 0 = 1. Sports is No for both students and has gain 0. Internship becomes the test, and both children are pure leaves.

Decision tree for the placement dataThe root tests CGPA: High leads to the leaf Placed = Yes, Low leads to the leaf Placed = No, and Medium leads to a test on Internship. Internship Yes gives Placed = Yes and Internship No gives Placed = No.CGPA?Placed = YesInternship?Placed = NoPlaced = YesPlaced = NoHighMediumLowYesNo
Decision tree for the placement data

Step 5: Classify the new student (Medium, Internship = Yes, Sports = Yes). CGPA = Medium leads to the Internship test, and Internship = Yes leads to the leaf Placed = Yes.

Check with the Gini index: Gini(S) = 1 − (0.5² + 0.5²) = 0.5. After the CGPA split the weighted Gini is (2/8)(0.5) = 0.125, a reduction of 0.375, against 0.125 for Internship and 0 for Sports, so the Gini index chooses the same root.

In conclusion, the tree uses only CGPA and Internship; Sports carries no information about placement in this data and never appears in the tree.

4 Seven emails are described by (Offer, Link, Unknown sender → Class): (Yes, Yes, Yes → Spam), (Yes, Yes, No → Spam), (No, No, Yes → Spam), (Yes, No, Yes → Ham), (Yes, No, No → Ham), (No, Yes, No → Ham), (No, No, No → Ham). Explain the naive Bayes classifier and use it to classify a new email with Offer = No, Link = Yes and Unknown sender = Yes. 10 marks
Model answer

The naive Bayes classifier applies Bayes' rule with the assumption of class conditional independence: given the class, the features are independent. For x = (x1, …, xd),

P(x|C) = P(x1|C) × P(x2|C) × … × P(xd|C)

and x is assigned to the class with the largest score P(C) × Π P(xj|C). The evidence P(x) is the same for every class and is needed only to turn scores into posteriors. The assumption replaces one d-dimensional distribution per class with d one-dimensional ones, which can be estimated from little data.

Steps:

1. Estimate each prior P(C) as the fraction of training patterns in class C.

2. Estimate each P(xj = v|C) as the fraction of class-C patterns whose feature j has value v.

3. For a new x, multiply the prior of each class by its matching conditional probabilities.

4. Pick the class with the largest product; dividing each product by their sum gives the posteriors.

Worked example. Spam has 3 emails and Ham has 4, so P(Spam) = 3/7 and P(Ham) = 4/7. The counts that match the new email are:

Feature value    Spam (of 3) Ham (of 4)
Offer = No       1           2
Link = Yes       2           1
Unknown = Yes    2           1

Spam score = 3/7 × 1/3 × 2/3 × 2/3 = 4/63 = 0.0635

Ham score = 4/7 × 2/4 × 1/4 × 1/4 = 1/56 = 0.0179

Naive Bayes scores for the new emailThe three feature values Offer = No, Link = Yes and Unknown = Yes each feed both the Spam score and the Ham score. The Spam score 0.0635 and the Ham score 0.0179 are compared, and the larger gives Class = Spam.Offer = NoLink = YesUnknown = YesSpam score0.0635Ham score 0.0179Pick thelargest scoreClass = Spam
Naive Bayes scores for the new email

Posteriors: 4/63 = 32/504 and 1/56 = 9/504, so P(Spam|x) = 32/41 = 0.7805 and P(Ham|x) = 9/41 = 0.2195. The email is classified as Spam, even though Ham has the larger prior: the Link and Unknown sender evidence outweighs it.

Laplace smoothing: no count used here is zero, so these results use no smoothing. A zero count would make a whole product zero; Laplace smoothing estimates P(xj = v|C) as (count + 1)/(nC + k), where nC is the class size and k the number of values of the feature. Here it would give 0.0617 for Spam against 0.0317 for Ham, still Spam.

The same steps work for any number of classes: compute one score per class and choose the largest.

In conclusion, naive Bayes is fast and needs only simple counts. It often classifies well even when the independence assumption is only roughly true, because the decision depends only on which score is largest.

5 Explain how decision trees are used for regression. For x (hours studied) = 1, 2, 3, 4, 5, 6 with y (marks) = 30, 34, 32, 60, 64, 62, find the best first split by the sum of squared errors. Relate the depth of a regression tree to the bias-variance trade-off. 10 marks
Model answer

A regression tree predicts a continuous target. It has the same structure as a classification tree, but each leaf stores a number, the mean target of the training patterns that reach it, so the tree is a piecewise constant function of the input.

Building a regression tree:

1. For each feature, take the midpoints between neighbouring sorted values as candidate thresholds t.

2. For the test x ≤ t, compute SSE = Σleft (y − ȳL)² + Σright (y − ȳR)², where ȳL and ȳR are the mean targets of the two sides.

3. Choose the feature and threshold with the smallest SSE.

4. Repeat on each child until a stopping rule holds: maximum depth, minimum patterns per leaf, or too small a drop in SSE.

Worked example. Before any split the mean is 47 and SSE = 1366.

t    L mean  L SSE  R mean  R SSE   Total
1.5  30.0    0.0    50.4    1019.2  1019.2
2.5  32.0    8.0    54.5    683.0   691.0
3.5  32.0    8.0    62.0    8.0     16.0
4.5  39.0    596.0  63.0    2.0     598.0
5.5  44.0    1096.0 62.0    0.0     1096.0

For t = 3.5 the left marks 30, 34, 32 have mean 32 and SSE = 4 + 4 + 0 = 8, and the right marks 60, 64, 62 have mean 62 and SSE = 4 + 4 + 0 = 8, a total of 16. This is the smallest total, so the first test is x ≤ 3.5: Yes leads to the leaf predicting 32 marks (for example, 2 hours of study) and No to the leaf predicting 62 marks (for example, 5 hours).

Regression tree after the first splitThe root tests Hours x ≤ 3.5. The Yes branch leads to a leaf that predicts 32 marks and the No branch leads to a leaf that predicts 62 marks.Hours x ≤ 3.5?Predict 32 marksPredict 62 marksYesNo
Regression tree after the first split

Bias-variance trade-off. For squared-error loss the expected error at x splits into three parts:

E[(y − f̂(x))²] = Bias² + Variance + σ²

where Bias = E[f̂(x)] − f(x), Variance = E[(f̂(x) − E[f̂(x)])²], both taken over training sets, and σ² is noise that no model can remove.

  • A shallow tree, like the one-split tree above, has few leaves and may miss real structure: high bias, low variance.
  • A deep tree with one pattern per leaf reproduces every training target (training SSE = 0) and so fits the noise, such as the drop from 34 to 32 marks between 2 and 3 hours: low bias, high variance.
  • So the depth, the minimum leaf size or the amount of pruning is chosen on validation data to keep the total error smallest, and averaging many deep trees, as a random forest does, lowers the variance.

In conclusion, a regression tree splits to minimise squared error and predicts leaf means, and its depth controls the balance between bias and variance.

6 Explain the random forest method for classification and regression. Show how the outputs of the trees are combined, and explain why a random forest generalises better than a single decision tree. 10 marks
Model answer

A random forest is an ensemble of decision trees, each trained on a different random version of the training data, whose outputs are combined. It adds random feature selection to bagging (bootstrap aggregating).

Training, for B trees, n training patterns and d features:

1. For b = 1 to B, draw a bootstrap sample: n patterns chosen at random with replacement from the training set.

2. Grow a decision tree on the sample. At every node choose m of the d features at random (commonly m ≈ √d for classification and m ≈ d/3 for regression) and pick the best split among those m only, using the Gini index or entropy for classification and squared error for regression.

3. Grow each tree deep, usually without pruning, so that each tree has low bias.

Random forest training and predictionThe training set is sampled with replacement into bootstrap samples 1, 2 and B, and each sample grows its own tree using random m features at each node. Trees 1, 2 and B feed a vote or average step that gives the final prediction.Sampled with replacementRandom m features per nodeTraining setBootstrapsample 1Bootstrapsample 2Bootstrapsample BTree 1Tree 2Tree BVote or averageFinal prediction
Random forest training and prediction

Final prediction:

  • Classification: every tree votes and the majority class wins. If five trees predict A, B, A, C, A for a pattern, A has 3 of the 5 votes and is the output.
  • Regression: the tree outputs are averaged. If five trees predict 52, 55, 50, 54 and 59, the forest predicts (52 + 55 + 50 + 54 + 59)/5 = 270/5 = 54.

Why it generalises better:

  • A single deep tree has low bias but high variance: a small change in the data can change its splits.
  • The average of B trees, each with variance σ² and pairwise correlation ρ, has variance ρσ² + (1 − ρ)σ²/B. More trees shrink the second term, and the random choice of m features lowers ρ, so the first term shrinks too. For example, with σ² = 1, ρ = 0.3 and B = 100 the variance is 0.3 + 0.007 = 0.307 instead of 1.
  • The bias stays close to that of one deep tree, so the total error falls.

Out-of-bag (OOB) estimate: a bootstrap sample misses a given pattern with probability (1 − 1/n)ⁿ, which approaches 1/e ≈ 0.368 for large n, so each tree leaves out about 36.8% of the patterns. Predicting every pattern only with the trees that did not see it gives the OOB error, an estimate of test error without a separate test set.

Other properties: the trees can be trained in parallel, the forest gives a feature importance score (the total impurity decrease due to each feature), and it copes well with many features. The price is that the single readable tree is lost.

In conclusion, a random forest combines bootstrap sampling, random feature subsets and voting or averaging to turn many unstable, low-bias trees into one stable and accurate model.

Unit 4

Linear Discriminants for Machine Learning

Syllabus: Introduction to linear discriminants; Linear discriminants for classification; The perceptron classifier and the perceptron learning algorithm; Support vector machines; The linearly non-separable case; Non-linear SVM and the kernel trick; Logistic regression; Linear regression; Multi-layer perceptrons; Backpropagation for training an MLP

One-page revision summary

  • A linear discriminant g(x) = wᵀx + w0 assigns a class by the sign of g(x), and its boundary g(x) = 0 is a hyperplane with normal w.
  • Linear discriminants learn the decision boundary directly instead of estimating each class density first.
  • For c classes a linear machine keeps one gi(x) per class and selects the largest, which gives convex decision regions with no unclaimed gaps.
  • The perceptron changes its weights only on misclassified samples and converges in a finite number of updates when the classes are linearly separable.
  • On non-separable data such as XOR the perceptron never settles, so training uses an epoch limit.
  • An SVM picks the separating hyperplane with the largest margin 2/‖w‖ by minimising ½‖w‖² subject to yi(wᵀxi + b) ≥ 1.
  • Only support vectors get αi > 0, so the SVM solution w = Σ αi yi xi depends on them alone.
  • For non-separable data the soft-margin SVM adds slack ξi and the penalty C Σ ξi; a large C gives a narrow margin and a small C a wider one.
  • The kernel trick replaces every dot product xiᵀxj by K(xi, xj) = φ(xi)ᵀφ(xj), so the SVM separates the data linearly in feature space without computing φ.
  • Common kernels are linear, polynomial (xᵀz + c)^p, Gaussian RBF exp(−γ‖x − z‖²) and sigmoid; a valid kernel satisfies Mercer's condition.
  • Logistic regression models P(y = 1 | x) = σ(wᵀx + b) and is trained by minimising cross-entropy with gradient descent; its boundary is linear.
  • Linear regression fits ŷ = w0 + w1x by least squares and is judged by SSE, MSE and R² = 1 − SSE/SST.
  • A multi-layer perceptron needs non-linear hidden units; with only linear units it reduces to one linear model.
  • Backpropagation does a forward pass, sends δ terms back from the output to the hidden layers by the chain rule, then updates every weight by η × δ × input.
  • Backpropagation can stall in local minima, train slowly with a poor learning rate, and suffer vanishing gradients in deep sigmoid networks.

Learn these by heart

  • Linear discriminant: g(x) = wᵀx + w0; signed distance from the boundary r = g(x)/‖w‖.
  • Perceptron rule: w ← w + η(t − o)x and b ← b + η(t − o).
  • SVM margin = 2/‖w‖; soft margin minimises ½‖w‖² + C Σ ξi subject to yi(wᵀxi + b) ≥ 1 − ξi.
  • Sigmoid: σ(z) = 1/(1 + e^(−z)) and σ′(z) = σ(z)(1 − σ(z)); logistic gradient ∂L/∂wj = (p − y)xj.
  • Least squares: w1 = Σ(x − x̄)(y − ȳ)/Σ(x − x̄)² and w0 = ȳ − w1x̄.
  • Backpropagation: δo = (t − o)o(1 − o), δj = hj(1 − hj) Σk δk wjk, Δw = η × δ × input.

2-mark questions

1 Define a linear discriminant function and its decision boundary. 2 marks
Model answer

A linear discriminant function is g(x) = wᵀx + w0, a weighted sum of the features plus a bias w0. For two classes, x goes to class C1 if g(x) > 0 and to C2 if g(x) < 0. The decision boundary g(x) = 0 is a hyperplane whose normal is the weight vector w.

2 State the perceptron learning rule. 2 marks
Model answer

For a sample x with target t and output o = step(wᵀx + b), the perceptron sets w ← w + η(t − o)x and b ← b + η(t − o), where η is the learning rate. Weights change only for misclassified samples. On linearly separable data the updates stop after a finite number of steps.

3 What are support vectors in a support vector machine? 2 marks
Model answer

Support vectors are the training points nearest the separating hyperplane. In the separable case they lie on the margin planes wᵀx + b = ±1, so yi(wᵀxi + b) = 1. Only they get non-zero Lagrange multipliers αi, so they alone fix w = Σ αi yi xi and b; removing any other point leaves the hyperplane unchanged.

4 What is a slack variable in a soft-margin SVM? 2 marks
Model answer

A slack variable ξi ≥ 0 relaxes the constraint of point xi to yi(wᵀxi + b) ≥ 1 − ξi. ξi = 0 means on or outside the margin, 0 < ξi < 1 means inside the margin on the correct side, and ξi > 1 means misclassified. The objective ½‖w‖² + C Σ ξi penalises the total slack.

5 A logistic regression model has weights w1 = 1.5, w2 = −0.5 and bias b = −1. Find the probability of class 1 for x = (2, 1). 2 marks
Model answer

z = w1x1 + w2x2 + b = 1.5(2) − 0.5(1) − 1 = 1.5.

P(y = 1 | x) = σ(z) = 1/(1 + e^(−1.5)) = 1/(1 + 0.2231) = 0.8176.

Since 0.8176 ≥ 0.5, the point is assigned to class 1.

6 Why can a single-layer perceptron not learn XOR, and how does a multi-layer perceptron solve it? 2 marks
Model answer

XOR gives 1 for (0, 1) and (1, 0) and 0 for (0, 0) and (1, 1). No straight line separates these pairs, so a single perceptron, with its one linear boundary, cannot learn it. A multi-layer perceptron adds a hidden layer: one hidden unit computes OR, another NAND, and the output unit ANDs them.

10-mark questions

1 Explain linear discriminant functions for two-class and multi-class classification. For g(x) = 2x1 + x2 − 4, classify the points (3, 1), (1, 1) and (1, 2) and find their distances from the decision boundary. 10 marks
Model answer

A linear discriminant classifies a pattern with a function that is linear in its features. Instead of first estimating the probability density of each class, it learns the decision boundary directly, so it is simple, fast and easy to interpret. The perceptron, the support vector machine and logistic regression are all linear discriminants; they differ in how they choose the weights.

1. Discriminant function. For a feature vector x = (x1, …, xd), g(x) = wᵀx + w0 = w1x1 + … + wdxd + w0, where w is the weight vector and w0 is the bias (threshold).

2. Two-class rule. Assign x to class C1 if g(x) > 0 and to class C2 if g(x) < 0. The decision boundary g(x) = 0 is a hyperplane: a line in two dimensions, a plane in three.

3. Geometry. w is normal (perpendicular) to the hyperplane and fixes its orientation; w0 fixes its position. The hyperplane lies at distance |w0|/‖w‖ from the origin, and the signed distance of a point x from it is r = g(x)/‖w‖. So g(x) tells both how far x is from the boundary and on which side.

4. Multi-class rule (linear machine). For c classes keep one function per class, gi(x) = wiᵀx + wi0. Every input feeds every gi(x), and the classifier selects the class with the largest value. The boundary between classes i and j is the hyperplane gi(x) = gj(x), and every decision region is convex. Separate one-versus-rest classifiers can leave regions that no class, or more than one class, claims; the largest-value rule leaves no such gaps.

Linear machine for three classesInputs x1 and x2 each feed three linear discriminant functions g1(x), g2(x) and g3(x). The classifier selects the largest of the three values and outputs that class.Input x1Input x2g1(x)g2(x)g3(x)Selectlargest gi(x)Class of x
Linear machine for three classes

5. Worked example. g(x) = 2x1 + x2 − 4, so w = (2, 1), w0 = −4 and ‖w‖ = √5 = 2.236.

Point   g(x)            Class     r
(3, 1)  6 + 1 − 4 = 3   C1        1.342
(1, 1)  2 + 1 − 4 = −1  C2        −0.447
(1, 2)  2 + 2 − 4 = 0   boundary  0

The boundary 2x1 + x2 = 4 lies 4/√5 = 1.789 from the origin.

For three classes with g1 = x1 − x2, g2 = x2 − 1 and g3 = 0.5 − x1, the point (2, 1) gives g1 = 1, g2 = 0 and g3 = −1.5, so it goes to class 1.

6. Limitation. A linear discriminant can separate only classes that are linearly separable. Overlapping or curved classes need slack variables, kernels or hidden layers.

In short, a linear discriminant reduces classification to the sign (two classes) or the largest value (many classes) of a weighted sum, and the weight vector sets the orientation of the boundary.

2 Explain the perceptron classifier and the perceptron learning algorithm. Train a perceptron for the AND function starting from w1 = 0.4, w2 = 0.4, bias b = 0.3 with learning rate η = 0.2. 10 marks
Model answer

The perceptron, proposed by Frank Rosenblatt, is the simplest neural classifier. It is a linear discriminant whose weights are learned from its own mistakes.

1. Model. Inputs x1, …, xd have weights w1, …, wd, and a bias b acts as the weight of a constant input 1. The unit forms the weighted sum net = w·x + b and passes it through a step function: output o = 1 if net > 0, else o = 0. During training the output is compared with the target t. The boundary net = 0 is a hyperplane.

Perceptron and its learning loopInputs x1 and x2 and a bias input 1 feed a weighted sum, which passes through a step function to give output o. The error e = t − o drives the update of w and b, which feeds back into the weighted sum.Input x1Input x2Bias input 1Weighted sum netStep functionOutput oError e = t − oUpdate w and bw1w2bnetcompare with tenew weights
Perceptron and its learning loop

2. Learning algorithm.

initialise w, b; choose rate η
repeat (one pass = one epoch):
  for each sample (x, t):
    o = 1 if w·x + b > 0 else 0
    e = t − o
    w = w + η·e·x
    b = b + η·e
until an epoch has no error

The error e is 0 for a correct output, so only misclassified samples change the weights. A false 0 (e = +1) adds ηx to w and raises w·x for that sample; a false 1 (e = −1) subtracts it.

3. Convergence. The perceptron convergence theorem says that if the classes are linearly separable, the algorithm finds a separating hyperplane after a finite number of updates. If they are not, as with XOR, the weights never settle, so an epoch limit is used.

4. Worked example: AND gate. Start with w1 = 0.4, w2 = 0.4, b = 0.3 and η = 0.2. Each row shows the weights after that sample.

Epoch 1
x1 x2 t  net  o  e   w1   w2   b
0  0  0  0.3  1  −1  0.4  0.4  0.1
0  1  0  0.5  1  −1  0.4  0.2  −0.1
1  0  0  0.3  1  −1  0.2  0.2  −0.3
1  1  1  0.1  1  0   0.2  0.2  −0.3

For example, the second row uses w = (0.4, 0.4), b = 0.1: net = 0.4 + 0.1 = 0.5, o = 1, e = −1, so w2 = 0.4 − 0.2(1) = 0.2 and b = 0.1 − 0.2 = −0.1.

Epoch 2 with w1 = w2 = 0.2, b = −0.3 gives net = −0.3, −0.1, −0.1 and 0.1 for the four samples, so the outputs 0, 0, 0, 1 equal the targets. No weight changes and training stops.

The learned boundary is 0.2x1 + 0.2x2 − 0.3 = 0, that is x1 + x2 = 1.5, which separates (1, 1) from the other three inputs.

In conclusion, the perceptron is simple and converges on linearly separable data, but it stops at any separating line, not the best one, and fails on non-separable data.

3 Explain the support vector machine for linearly separable data and its soft-margin form for the linearly non-separable case, with a worked example. 10 marks
Model answer

A support vector machine (SVM) is a linear discriminant that picks, among all separating hyperplanes, the one with the largest margin to the nearest training points. A wide margin generalises better.

1. Setup. Labels are yi = ±1; the hyperplane wᵀx + b = 0 is scaled so the nearest points give wᵀx + b = ±1. Then every point satisfies yi(wᵀxi + b) ≥ 1.

2. Margin. The planes wᵀx + b = +1 and −1 are 2/‖w‖ apart, so maximising the margin means: minimise ½‖w‖² subject to yi(wᵀxi + b) ≥ 1.

3. Solution. Solving this quadratic programme with Lagrange multipliers αi ≥ 0 gives w = Σ αi yi xi with Σ αi yi = 0. Only points exactly on the margin planes get αi > 0; these are the support vectors.

4. Example. Class −1: A(1, 1), B(0, 1), C(1, 0). Class +1: D(2, 2), E(3, 2), F(2, 3). Take w = (1, 1), b = −3, so g(x) = x1 + x2 − 3, and compute y·g(x):

Point   y    g(x)  y·g(x)
A(1,1)  −1   −1    1
B(0,1)  −1   −2    2
C(1,0)  −1   −2    2
D(2,2)  +1   1     1
E(3,2)  +1   2     2
F(2,3)  +1   2     2

Every y·g(x) ≥ 1. With αA = αD = 1, w = −1(1, 1) + 1(2, 2) = (1, 1) and Σ αi yi = 0, so the optimality conditions hold and this is the maximum-margin hyperplane. A and D are the support vectors; the margin is 2/√2 = 1.414.

5. Linearly non-separable case. When classes overlap, no w meets every constraint, so slack variables ξi ≥ 0 relax them: minimise ½‖w‖² + C Σ ξi subject to yi(wᵀxi + b) ≥ 1 − ξi, where ξi = max(0, 1 − yi g(xi)) is the hinge loss. A large C punishes violations (narrow margin, risk of overfitting); a small C allows more of them for a wider margin. In the dual, each αi gets the upper bound C.

Slack of a point in a soft-margin SVMCompute y·g(x) for a point. If it is at least 1 the slack is 0 (points A to F); if it is between 0 and 1 the point is inside the margin with slack between 0 and 1 (H, 0.6); if it is negative the point is misclassified with slack above 1 (G, 2.4).Compute y·g(x)ξ = 0: on oroutside marginξ in (0, 1):inside marginξ in (1, ∞):misclassifiedA to F: ξ = 0H: ξ = 0.6G: ξ = 2.4y·g ≥ 1y·g in (0, 1)y·g negative
Slack of a point in a soft-margin SVM

6. Example continued. Add G(2.2, 2.2) to class −1 and H(1.8, 1.6) to class +1. G = 0.6D + 0.2E + 0.2F lies inside the class +1 triangle, so no line separates the classes. For the same hyperplane, G has negative y·g = −1.4 and ξ = 2.4 (misclassified); H has y·g = 0.4 and ξ = 0.6 (inside the margin, correct side); A to F stay on or outside the margin with ξ = 0. With C = 1 this hyperplane costs ½(2) + 1(3.0) = 4.0; training seeks the w and b of lowest cost.

In conclusion, the SVM maximises the margin, depends only on its support vectors, and uses C to trade margin width against errors.

4 What is a non-linear SVM? Explain the kernel trick using the polynomial kernel K(x, z) = (xᵀz)², and show how a kernel makes the XOR problem linearly separable. 10 marks
Model answer

A linear SVM fails when no hyperplane in the input space separates the classes, as in XOR. A non-linear SVM maps each input x to a feature vector φ(x) in a higher-dimensional feature space where the classes become linearly separable, and fits the maximum-margin hyperplane there. Seen back in the input space, that hyperplane is a curved boundary.

1. Only dot products matter. The SVM dual problem is: maximise Σ αi − ½ Σi Σj αi αj yi yj (xiᵀxj) subject to 0 ≤ αi ≤ C and Σ αi yi = 0. The data enter only through dot products xiᵀxj, and the classifier is f(x) = sign(Σ αi yi xiᵀx + b).

2. The kernel trick. Replace every dot product by a kernel K(xi, xj) = φ(xi)ᵀφ(xj) that is computed directly from the original vectors, so φ is never formed explicitly. The classifier becomes f(x) = sign(Σ αi yi K(xi, x) + b). The cost depends on the number of training points, not on the dimension of the feature space, which for the Gaussian kernel is infinite.

Non-linear SVM with and without the kernel trickThe input space x can go through an explicit map φ(x) to feature space vectors, or straight to a kernel K(xi, xj) by the kernel trick. Both give the dot products for a linear SVM in the feature space, which appears as a non-linear boundary in x.Input space xExplicitmap φ(x)Featurespace vectorsKernel K(xi, xj)Linear SVM infeature spaceNon-linearboundary in xdot productskernel tricksame dotproducts
Non-linear SVM with and without the kernel trick

3. Checking a kernel. For x = (x1, x2), K(x, z) = (xᵀz)² equals φ(x)ᵀφ(z) with φ(x) = (x1², √2x1x2, x2²). Take x = (1, 2) and z = (3, 1):

Kernel: xᵀz = 3 + 2 = 5, K = 5² = 25
φ(x) = (1, 2.828, 4)
φ(z) = (9, 4.243, 1)
φ(x)ᵀφ(z) = 9 + 12 + 4 = 25

Both give 25, but the kernel never built the three-dimensional vectors.

4. XOR. With bipolar inputs, (1, 1) and (−1, −1) are class −1, and (1, −1) and (−1, 1) are class +1. The middle feature √2x1x2 is +1.414 for both class −1 points and −1.414 for both class +1 points, so the plane "middle feature = 0" separates them in the feature space. In the input space this boundary is x1x2 = 0, the two axes, which no single line can form.

5. Common kernels.

  • Linear: K(x, z) = xᵀz.
  • Polynomial: K(x, z) = (xᵀz + c)^p.
  • Gaussian (RBF): K(x, z) = exp(−γ‖x − z‖²). For the points above with γ = 0.5, ‖x − z‖² = 5 and K = e^(−2.5) = 0.0821.
  • Sigmoid: K(x, z) = tanh(κxᵀz + c), a valid kernel only for some κ and c.

6. Mercer's condition. A symmetric function K is a valid kernel when every kernel matrix it produces is positive semi-definite; then a feature space with K(x, z) = φ(x)ᵀφ(z) exists.

In conclusion, the kernel trick lets an SVM learn non-linear boundaries while keeping the same convex training problem. The kernel, its parameters (p or γ) and C are chosen by validation.

5 Compare linear regression and logistic regression. Fit a least-squares line to the points (1, 3), (2, 5), (3, 6), (4, 8), and show one gradient-descent step of logistic regression. 10 marks
Model answer

Linear regression and logistic regression both start from the weighted sum of the input features, z = w0 + w1x1 + … + wdxd. Linear regression uses z directly as a real number; logistic regression passes z through the sigmoid to get a class probability, which makes it a linear discriminant for classification.

1. Linear regression. The model is ŷ = w0 + w1x. Least squares chooses w0 and w1 to minimise the squared error SSE = Σ(yi − ŷi)². Setting both partial derivatives to zero gives w1 = Σ(x − x̄)(y − ȳ)/Σ(x − x̄)² and w0 = ȳ − w1x̄.

2. Worked fit. Here x̄ = 2.5 and ȳ = 5.5.

x  y  x−x̄   y−ȳ   product  (x−x̄)²
1  3  −1.5  −2.5  3.75     2.25
2  5  −0.5  −0.5  0.25     0.25
3  6  0.5   0.5   0.25     0.25
4  8  1.5   2.5   3.75     2.25
Sum               8.00     5.00

w1 = 8/5 = 1.6 and w0 = 5.5 − 1.6(2.5) = 1.5, so ŷ = 1.5 + 1.6x. The predictions 3.1, 4.7, 6.3, 7.9 leave residuals −0.1, 0.3, −0.3, 0.1, so SSE = 0.2 and MSE = 0.05. With SST = Σ(y − ȳ)² = 13, R² = 1 − 0.2/13 = 0.985. At x = 5 the line predicts 9.5.

Linear and logistic regression from one weighted sumInput x gives the weighted sum z. Linear regression outputs the real number ŷ = z and is fitted by least squares; logistic regression turns z into the probability p = σ(z), predicts class 1 if p ≥ 0.5 and is trained with the cross-entropy loss.Linear regressionLogistic regressionInput xWeighted sum zReal numberŷ = zLeastsquares (SSE)Probabilityp = σ(z)Class 1if p ≥ 0.5Cross-entropy lossweights wsigmoidfitted bypredicttrained by
Linear and logistic regression from one weighted sum

3. Logistic regression. P(y = 1 | x) = p = σ(z) = 1/(1 + e^(−z)), a value in (0, 1). Predict class 1 when p ≥ 0.5, that is when z ≥ 0, so the decision boundary z = 0 is a hyperplane.

4. Training. There is no closed form. The weights maximise the likelihood, which is the same as minimising the cross-entropy (log loss) L = −[y ln p + (1 − y) ln(1 − p)]. Its gradient is ∂L/∂wj = (p − y)xj, so gradient descent repeats wj ← wj − η(p − y)xj, with x0 = 1 for the bias.

5. One step. Take w0 = −1, w1 = 1, a sample x = 2 with y = 1, and η = 0.1. Then z = 1, p = σ(1) = 0.7311 and L = −ln 0.7311 = 0.3133. The gradients are (p − y)x = −0.5379 for w1 and −0.2689 for w0, so the new weights are w1 = 1.0538 and w0 = −0.9731. Now z = 1.1345, p = 0.7567 and the loss falls to 0.2788.

6. Comparison.

  • Output: a real number versus a probability.
  • Loss: squared error versus cross-entropy.
  • Fitting: closed-form least squares versus iterative gradient descent.
  • Use: predicting a quantity versus predicting a class.

In conclusion, both models learn one weight per feature; the sigmoid and log loss turn the regression line into a probabilistic linear classifier.

6 Explain the multi-layer perceptron and the backpropagation algorithm. Carry out one forward and backward pass for a 2-2-1 sigmoid network. 10 marks
Model answer

A multi-layer perceptron (MLP) is a feed-forward network with an input layer, one or more hidden layers and an output layer, each fully connected to the next. Its units use a non-linear activation such as the sigmoid σ(a) = 1/(1 + e^(−a)); without it the layers would collapse into one linear map. The hidden layer lets an MLP form non-linear boundaries, such as the one XOR needs. It is trained by backpropagation: gradient descent in which the chain rule carries the error backwards, layer by layer.

1. Forward pass. Each unit computes net = Σ (weight × input) and outputs σ(net), layer by layer, up to the output o. For target t the error is E = ½(t − o)².

2. Output error term. δo = (t − o)·o(1 − o), because σ′(a) = σ(a)(1 − σ(a)).

3. Hidden error terms (backward pass). δj = hj(1 − hj)·Σk δk wjk, where wjk joins hidden unit j to output unit k.

4. Update. Each weight changes by Δw = η × δ of the unit it enters × the input it carries. All δ values use the old weights.

5. Repeat for every sample over many epochs until E is small.

2-2-1 MLP: forward pass and backward passInputs x1 and x2 feed hidden units h1 and h2 through weights 0.4, 0.2, −0.3 and 0.6, and the hidden units feed output o through 0.5 and 0.7. In the backward pass the error E gives δo, which is sent back as δh1 and δh2, and then all weights are updated.Forward passBackward passInput x1 = 1Input x2 = 0.5h1 = 0.62246h2 = 0.5o = 0.65954E = ½(t − o)²δo = 0.07645δh1 = 0.00898,δh2 = 0.01338Update allweights0.40.2−0.30.60.50.7target t = 1backwardvia 0.5and 0.7
2-2-1 MLP: forward pass and backward pass

Worked example (2-2-1 network, biases taken as 0). x1 = 1, x2 = 0.5, t = 1, η = 0.5. Weights: x1→h1 0.4, x2→h1 0.2, x1→h2 −0.3, x2→h2 0.6, h1→o 0.5, h2→o 0.7.

Forward pass
net_h1 = 0.4(1) + 0.2(0.5) = 0.5
h1 = σ(0.5) = 0.62246
net_h2 = −0.3(1) + 0.6(0.5) = 0
h2 = σ(0) = 0.5
net_o = 0.5(0.62246) + 0.7(0.5)
      = 0.66123
o = σ(0.66123) = 0.65954
E = ½(0.34046)² = 0.05796

Backward pass
δo  = 0.34046 × 0.65954 × 0.34046
    = 0.07645
δh1 = 0.62246 × 0.37754 × 0.07645
      × 0.5 = 0.00898
δh2 = 0.5 × 0.5 × 0.07645 × 0.7
    = 0.01338

New weights (old + η δ input)
h1→o  0.5 + 0.5(0.07645)(0.62246)
      = 0.5238
h2→o  0.7 + 0.5(0.07645)(0.5) = 0.7191
x1→h1 0.4 + 0.5(0.00898)(1) = 0.4045
x2→h1 0.2 + 0.5(0.00898)(0.5) = 0.2022
x1→h2 −0.3 + 0.5(0.01338)(1) = −0.2933
x2→h2 0.6 + 0.5(0.01338)(0.5) = 0.6033

A second forward pass with the new weights gives o = 0.6655 and E = 0.0560, so the error has fallen.

In conclusion, backpropagation makes multi-layer networks trainable: the forward pass computes outputs, the backward pass spreads the error as δ terms, and gradient descent updates every weight. Its weaknesses are local minima, slow training with a poor learning rate, and vanishing gradients when many sigmoid layers are stacked.

Unit 5

Clustering

Syllabus: Introduction to clustering and partitioning of data; Matrix factorization; Clustering of patterns; Divisive clustering; Agglomerative clustering; Partitional clustering and K-means clustering; Soft partitioning and soft clustering; Fuzzy C-means clustering; Rough clustering and the rough K-means algorithm; Expectation maximization-based clustering; Spectral clustering

One-page revision summary

  • Clustering groups unlabelled patterns so that similarity is high within a cluster and low between clusters, using a proximity measure such as Euclidean distance.
  • A hard partition of the data divides the patterns into K non-empty, non-overlapping clusters whose union is the whole data set.
  • Clustering of patterns needs a pattern representation, a proximity measure and a grouping algorithm, and each cluster is then summarised by a representative such as its centroid or medoid.
  • Clustering methods are broadly hierarchical (agglomerative or divisive) or partitional (K-means and its soft variants such as fuzzy C-means, rough K-means and EM).
  • In the matrix factorization view X ≈ BC, B is the n × K membership matrix and C the K × d centroid matrix, and K-means minimises ‖X − BC‖² with 0/1 rows in B.
  • Relaxing B to non-negative fractional rows turns the factorization into soft clustering, and non-negative matrix factorization can be read the same way.
  • Divisive clustering starts with one all-inclusive cluster and splits recursively, using monothetic splits, splinter groups or minimum spanning tree cuts because 2^(n−1) − 1 two-way splits exist.
  • Agglomerative clustering starts from singletons and merges the closest pair, with single, complete or average linkage defining the distance between clusters.
  • Single linkage can chain clusters together through intermediate points, while complete linkage favours compact clusters of similar diameter.
  • K-means alternates nearest-centroid assignment and mean update, never increases the SSE, and stops at a local minimum that depends on the initial centroids.
  • Soft clustering lets a pattern belong to more than one cluster, through fuzzy memberships, posterior probabilities or rough upper approximations.
  • Fuzzy C-means minimises Σ Σ (u_ik)^m d_ik², with each pattern's memberships summing to 1 and centres computed as u^m-weighted means.
  • Rough K-means puts a pattern in one lower approximation when a single centroid is clearly nearest, and otherwise in the upper approximations of every cluster within the threshold ε.
  • A rough K-means centroid is a weighted mean of its lower approximation and its boundary, with the larger weight on the lower approximation.
  • EM-based clustering fits a Gaussian mixture by maximum likelihood, alternating the E-step (responsibilities) and the M-step (weights, means and covariances).
  • EM never decreases the log-likelihood but can stop at a local maximum, so it is started from several initial values or from a K-means result.
  • Spectral clustering builds a similarity graph, takes the eigenvectors of its Laplacian for the K smallest eigenvalues, and runs K-means on the rows of that eigenvector matrix.
  • The number of zero eigenvalues of the graph Laplacian equals the number of connected components of the similarity graph.

Learn these by heart

  • K-means objective: SSE = Σ_k Σ_(x in C_k) ‖x − m_k‖², where m_k is the mean of cluster C_k.
  • Hard partition as a factorization: X ≈ BC, with one 1 in each row of B and the centroids as the rows of C.
  • Two-cluster splits of n patterns: 2^(n−1) − 1, for example 31 for six patterns.
  • Fuzzy C-means: u_ik = 1 / Σ_j (d_ik / d_jk)^(2/(m−1)) and c_i = Σ_k (u_ik)^m x_k / Σ_k (u_ik)^m.
  • Rough K-means centroid: m_k = w_lower × mean(lower) + w_upper × mean(boundary), with w_lower + w_upper = 1 and w_lower > w_upper.
  • EM: γ_ik = π_k N(x_i | μ_k, S_k) / Σ_j π_j N(x_i | μ_j, S_j), then π_k = N_k / n and μ_k = Σ_i γ_ik x_i / N_k.
  • Graph Laplacian: L = D − W with d_ii = Σ_j w_ij; the Fiedler vector belongs to the second-smallest eigenvalue.

2-mark questions

1 What is clustering of patterns, and how does it differ from classification? 2 marks
Model answer

Clustering of patterns groups unlabelled patterns into clusters, so that patterns in the same cluster are more similar to one another than to patterns in other clusters, judged by a proximity measure such as Euclidean distance. Classification learns from labelled patterns and assigns new patterns to known classes; clustering is unsupervised and discovers the groups itself.

2 How can a hard partition of n patterns into K clusters be written as a matrix factorization? 2 marks
Model answer

Write the n × d data matrix as X ≈ BC. B is the n × K cluster-indicator matrix, with a single 1 in each row marking that pattern's cluster, and C is the K × d matrix of cluster centroids. K-means chooses B and C to minimise ‖X − BC‖², the sum of squared errors.

3 In how many ways can six patterns be split into two non-empty clusters, and why does this make divisive clustering costly? 2 marks
Model answer

n patterns can be split into two non-empty clusters in 2^(n−1) − 1 ways, so six patterns give 2^5 − 1 = 31 splits. The count roughly doubles with every added pattern, so testing every split at each level is infeasible. Practical divisive methods split on one feature at a time (monothetic) or grow a splinter group (polythetic).

4 Distinguish hard partitioning from soft partitioning of data. 2 marks
Model answer

In hard partitioning every pattern belongs to exactly one cluster: its membership u_ik is 0 or 1 and Σ_k u_ik = 1. In soft partitioning a pattern may belong to several clusters at once, through fuzzy memberships in [0, 1] that sum to 1 (fuzzy C-means), posterior probabilities (EM), or membership of more than one upper approximation (rough K-means).

5 In fuzzy C-means with fuzzifier m = 2, a pattern is at distance 1 from centre c1 and at distance 3 from centre c2. Find its two memberships. 2 marks
Model answer

The rule is u_i = 1 / Σ_j (d_i/d_j)^(2/(m−1)), and with m = 2 the exponent is 2. So u1 = 1/[(1/1)² + (1/3)²] = 1/(1 + 1/9) = 0.9 and u2 = 1/[(3/1)² + (3/3)²] = 1/(9 + 1) = 0.1. They sum to 1, and the nearer centre gets the larger share.

6 What is the graph Laplacian used in spectral clustering? State two of its properties. 2 marks
Model answer

For a similarity graph with weight matrix W, the degree matrix D is diagonal with d_ii = Σ_j w_ij, and the unnormalised Laplacian is L = D − W. L is symmetric and positive semidefinite. Its smallest eigenvalue is 0, with the constant vector as eigenvector, and the number of zero eigenvalues equals the number of connected components.

10-mark questions

1 Explain agglomerative hierarchical clustering. Apply single linkage to five patterns A to E with distances d(A,B) = 2, d(A,C) = 6, d(A,D) = 10, d(A,E) = 9, d(B,C) = 5, d(B,D) = 9, d(B,E) = 8, d(C,D) = 4, d(C,E) = 7 and d(D,E) = 3, draw the dendrogram, and explain how divisive clustering builds a hierarchy from the top. 10 marks
Model answer

Agglomerative clustering is a bottom-up hierarchical method. It starts with every pattern as a cluster of its own and, at each step, merges the two closest clusters until a single cluster remains. The result is a nested sequence of partitions drawn as a dendrogram; cutting the dendrogram at a chosen height gives a partition.

1. Compute the n × n distance matrix and treat each pattern as a cluster.

2. Find the pair of clusters with the smallest inter-cluster distance and merge them.

3. Update the distance from the new cluster to every other cluster. Single linkage uses the minimum distance between their members, complete linkage the maximum and average linkage the mean.

4. Repeat steps 2 and 3 until one cluster remains, recording each merge distance.

The distance matrix for the example is:

     A    B    C    D    E
A    0    2    6   10    9
B    2    0    5    9    8
C    6    5    0    4    7
D   10    9    4    0    3
E    9    8    7    3    0
  • Merge 1: the smallest entry is d(A,B) = 2, so {A,B} is formed at 2.
  • Merge 2: now d(C,{A,B}) = min(6,5) = 5, d(D,{A,B}) = min(10,9) = 9, d(E,{A,B}) = min(9,8) = 8, d(C,D) = 4, d(C,E) = 7 and d(D,E) = 3. The smallest is 3, so {D,E} is formed at 3.
  • Merge 3: d({A,B},C) = 5, d(C,{D,E}) = min(4,7) = 4 and d({A,B},{D,E}) = min(10,9,9,8) = 8, so C joins {D,E} at 4.
  • Merge 4: d({A,B},{C,D,E}) = min(5,8) = 5, so all five patterns form one cluster at 5.
Single-linkage dendrogram for patterns A to EA dendrogram drawn top to bottom: A and B merge at 2, D and E merge at 3, C joins {D,E} at 4, and {A,B} joins {C,D,E} at 5 to form one cluster.{A,B,C,D,E} at 5{A,B} at 2{C,D,E} at 4{D,E} at 3ABCDE
Single-linkage dendrogram for patterns A to E

Cutting the dendrogram between heights 4 and 5 gives two clusters, {A,B} and {C,D,E}. The linkage rule matters: with complete linkage, C would instead join {A,B} at 6 and the final merge would happen at 10.

Divisive clustering works top-down. It starts with all patterns in one cluster and repeatedly splits a cluster into two until each cluster is a single pattern or the required number of clusters is reached. Since n patterns allow 2^(n−1) − 1 two-way splits, practical methods split on one feature at a time (monothetic) or move the most dissimilar patterns into a splinter group (polythetic). One simple divisive scheme deletes the edges of the minimum spanning tree in decreasing order of weight. Here that tree has edges A–B (2), D–E (3), C–D (4) and B–C (5); deleting B–C first separates {A,B} from {C,D,E}, and the later deletions give the same hierarchy read from the top.

In conclusion, agglomerative clustering merges from the bottom and divisive clustering splits from the top, and both record their result as a dendrogram.

2 Explain partitional clustering and the K-means algorithm. Apply K-means with K = 2 to P1(1,1), P2(2,1), P3(1,2), P4(5,4), P5(6,5) and P6(5,6), taking P1 and P2 as the initial centroids, and show the final partition as a matrix factorization. 10 marks
Model answer

Partitional clustering divides n patterns into K non-overlapping clusters at a single level, instead of building a hierarchy. It optimises a criterion, most often the sum of squared errors SSE = Σ_k Σ_(x in C_k) ‖x − m_k‖², where m_k is the centroid of cluster C_k. K-means is the standard partitional algorithm.

1. Choose K and K initial centroids.

2. Assign each pattern to the cluster of its nearest centroid.

3. Recompute each centroid as the mean of the patterns assigned to it.

4. Repeat steps 2 and 3 until no pattern changes cluster, then stop.

The K-means loopA flow from choosing K and the initial centroids to assigning each pattern to its nearest centroid, then recomputing the centroids as means; if any pattern changed cluster the loop returns to the assignment step, otherwise K-means stops with the final clusters.Choose K,initial centroidsAssign tonearest centroidRecomputecentroids as meansAny patternchanged cluster?Stop: finalclustersyesno
The K-means loop

Iteration 1 uses m1 = (1,1) and m2 = (2,1), with squared Euclidean distances d1² and d2²:

Pt   d1²   d2²   cluster
P1    0     1    C1
P2    1     0    C2
P3    1     2    C1
P4   25    18    C2
P5   41    32    C2
P6   41    34    C2

The new centroids are m1 = mean(P1,P3) = (1, 1.5) and m2 = mean(P2,P4,P5,P6) = (4.5, 4).

Iteration 2:

Pt    d1²     d2²    cluster
P1    0.25   21.25   C1
P2    1.25   15.25   C1
P3    0.25   16.25   C1
P4   22.25    0.25   C2
P5   37.25    3.25   C2
P6   36.25    4.25   C2

P2 moves to C1, so m1 = mean(P1,P2,P3) = (1.33, 1.33) and m2 = mean(P4,P5,P6) = (5.33, 5). In iteration 3 every pattern keeps its cluster, so K-means stops with the final clusters C1 = {P1,P2,P3} and C2 = {P4,P5,P6}. The SSE falls from 85 with the initial centroids to 9.5 in iteration 2 and to 4 at the end (4/3 for C1 plus 8/3 for C2).

Matrix factorization view: write the 6 × 2 data matrix as X ≈ BC, where B is the 6 × 2 cluster-indicator matrix and C holds the centroids as rows:

B rows: P1, P2, P3 = [1 0]
        P4, P5, P6 = [0 1]
C = [ 1.33  1.33 ]   (m1)
    [ 5.33  5.00 ]   (m2)

Each row of BC is the centroid of that pattern's cluster, so ‖X − BC‖² = SSE = 4. K-means is therefore a factorization in which every row of B is 0/1 with a single 1; allowing fractional rows leads to soft clustering.

In conclusion, K-means is simple and fast, costing O(nKd) per iteration, but it needs K in advance, depends on the initial centroids and reaches only a local minimum of the SSE.

3 Explain soft partitioning and the fuzzy C-means algorithm. Perform one iteration of fuzzy C-means with m = 2 on A(1,1), B(2,1), C(3,3), D(5,4) and E(6,5), starting from centres c1 = (2,2) and c2 = (5,5). 10 marks
Model answer

In hard partitioning each pattern belongs to exactly one cluster. Soft partitioning lets a pattern belong to several clusters with different degrees. Fuzzy C-means (FCM) is the soft version of K-means: every pattern x_k has a membership u_ik in [0, 1] for each cluster i, with Σ_i u_ik = 1.

FCM minimises J_m = Σ_i Σ_k (u_ik)^m ‖x_k − c_i‖², where m > 1 is the fuzzifier; m = 2 is a common choice. A larger m gives softer memberships, and as m approaches 1 the result approaches hard K-means.

1. Fix the number of clusters c, the fuzzifier m and a tolerance ε, and choose initial centres.

2. Update the memberships: u_ik = 1 / Σ_j (d_ik / d_jk)^(2/(m−1)), where d_ik = ‖x_k − c_i‖. With two clusters and m = 2 this becomes u_1k = d_2k² / (d_1k² + d_2k²).

3. Update the centres: c_i = Σ_k (u_ik)^m x_k / Σ_k (u_ik)^m.

4. Repeat steps 2 and 3, and stop when the memberships change by less than ε.

The fuzzy C-means loopA flow from fixing c, m and the tolerance ε to initial centres, then updating the memberships u_ik and the centres c_i in turn; while the memberships change by ε or more the loop repeats, otherwise it stops with a fuzzy partition.Fix c, m andtolerance εInitial centresUpdatememberships u_ikUpdatecentres c_iChange lessthan ε?Stop: fuzzypartitionnoyes
The fuzzy C-means loop

Worked iteration with squared distances to c1 = (2,2) and c2 = (5,5):

Pt      d1²  d2²   u1     u2
A(1,1)   2   32   0.941  0.059
B(2,1)   1   25   0.962  0.038
C(3,3)   2    8   0.800  0.200
D(5,4)  13    1   0.071  0.929
E(6,5)  25    1   0.038  0.962

For example, u1 for A is 32 / (2 + 32) = 16/17 = 0.941, and u1 for C is 8 / (2 + 8) = 0.8.

The centres are then updated with the weights u²:

  • Cluster 1: Σu1² = 0.8858 + 0.9246 + 0.6400 + 0.0051 + 0.0015 = 2.4570, Σu1²x = 4.6893 and Σu1²y = 3.7582, so c1 = (4.6893/2.4570, 3.7582/2.4570) = (1.91, 1.53).
  • Cluster 2: Σu2² = 1.8317, Σu2²x = 9.9850 and Σu2²y = 8.1967, so c2 = (5.45, 4.47).

The objective J_m falls from 6.33 to 4.89 after the centre update, and to 4.72 once the memberships are recomputed. C, which lies between the two groups, keeps a split membership (0.71 and 0.29 in the next iteration), something hard K-means cannot express.

In conclusion, FCM gives graded memberships and smoother centres, but it costs more per iteration, needs c and m in advance, and its memberships are relative, so an outlier far from every centre still receives about 1/c in each cluster.

4 Explain rough clustering with lower and upper approximations, and describe the rough K-means algorithm. Run one iteration on A(1,1), B(2,1), C(1,2), D(6,5), E(7,5), F(6,6) and G(4,3) with K = 2, initial centroids A and D, threshold ε = 1, w_lower = 0.7 and w_upper = 0.3. 10 marks
Model answer

Rough clustering is a soft clustering method based on rough set theory. Each cluster C_k is described by two sets instead of one: a lower approximation, holding the patterns that certainly belong to C_k, and an upper approximation, holding the patterns that possibly belong to it. The boundary, upper minus lower, holds the patterns whose membership is uncertain. Three rules hold:

  • A pattern belongs to at most one lower approximation.
  • A pattern in the lower approximation of C_k is also in its upper approximation.
  • A pattern that is in no lower approximation belongs to at least two upper approximations.

The rough K-means algorithm:

1. Choose K, initial centroids, a threshold ε and weights w_lower + w_upper = 1 with w_lower > w_upper.

2. For each pattern x, find its nearest centroid m_i, and let T be the set of other clusters j with d(x, m_j) − d(x, m_i) ≤ ε. This difference test is Lingras and West's original form; many later texts use the ratio test d(x, m_j) / d(x, m_i) ≤ ζ, with a threshold ζ ≥ 1, instead.

3. If T is empty, put x in the lower (and upper) approximation of C_i. Otherwise put x in the upper approximations of C_i and of every cluster in T, and in no lower approximation.

4. Update each centroid: if the boundary of C_k is empty, m_k = mean(lower); if the lower approximation is empty, m_k = mean(boundary); otherwise m_k = w_lower × mean(lower) + w_upper × mean(boundary).

5. Repeat steps 2 to 4 until the approximations stop changing.

Worked iteration with Euclidean distances to m1 = A = (1,1) and m2 = D = (6,5):

Pt      d to m1  d to m2  difference
A(1,1)    0.00     6.40     6.40
B(2,1)    1.00     5.66     4.66
C(1,2)    1.00     5.83     4.83
D(6,5)    6.40     0.00     6.40
E(7,5)    7.21     1.00     6.21
F(6,6)    7.07     1.00     6.07
G(4,3)    3.61     2.83     0.78

Every difference except G's exceeds ε = 1, so A, B and C go to the lower approximation of C1, and D, E and F to that of C2. G is nearest to m2, but 3.61 − 2.83 = 0.78 ≤ 1, so G joins the upper approximations of both C1 and C2 and forms their boundary. With the ratio test and ζ = 1.5, only G passes (3.61/2.83 = 1.27), so the result is the same.

Upper approximations of C1 and C2 after one rough K-means iterationTwo overlapping circles for the upper approximations of C1 and C2 among the seven patterns: A, B and C lie only in C1 as its lower approximation, D, E and F lie only in C2 as its lower approximation, and G lies in the overlap as the boundary of both.Universe: All seven patternsC1 upper approximationC2 upper approximationA, B, C:lower of C1D, E, F:lower of C2G: boundaryof C1 and C2
Upper approximations of C1 and C2 after one rough K-means iteration

The centroids are then updated:

  • m1 = 0.7 × mean(A,B,C) + 0.3 × G = 0.7 × (1.33, 1.33) + 0.3 × (4, 3) = (2.13, 1.83).
  • m2 = 0.7 × mean(D,E,F) + 0.3 × G = 0.7 × (6.33, 5.33) + 0.3 × (4, 3) = (5.63, 4.63).

In the next iteration G is at distances 2.20 and 2.31 from the new centroids, a difference of 0.11 ≤ 1, so G stays in the boundary; nothing else changes and the algorithm stops. Plain K-means from the same start would force G into C2 and pull its centroid to (5.75, 4.75).

In conclusion, rough K-means keeps uncertain patterns out of the cluster cores, so borderline points distort the centroids less, but ε and the two weights must be chosen.

5 Explain expectation maximization (EM) based clustering with a Gaussian mixture model. Perform one EM iteration on A(1,1), B(2,1), C(3,1), D(4,3) and E(5,3) with two components, initial means μ1 = (1,1) and μ2 = (5,3), equal mixing weights and a fixed variance σ² = 1 in each direction. 10 marks
Model answer

EM-based clustering assumes that the data come from a mixture of K probability distributions, usually Gaussians, one per cluster: p(x) = Σ_k π_k N(x | μ_k, S_k), where the mixing weights π_k sum to 1 and S_k is the covariance matrix of component k. Which component produced each pattern is a hidden variable, so EM finds maximum likelihood estimates by alternating between estimating the hidden memberships and refitting the parameters. Each pattern receives a probability of belonging to every cluster, so EM is a soft clustering method.

1. Initialise π_k, μ_k and S_k, for example from a K-means run.

2. E-step: compute the responsibility of component k for pattern x_i, γ_ik = π_k N(x_i | μ_k, S_k) / Σ_j π_j N(x_i | μ_j, S_j).

3. M-step: with N_k = Σ_i γ_ik, set π_k = N_k / n, μ_k = Σ_i γ_ik x_i / N_k and S_k = Σ_i γ_ik (x_i − μ_k)(x_i − μ_k)ᵀ / N_k.

4. Compute the log-likelihood L = Σ_i log Σ_k π_k N(x_i | μ_k, S_k) and repeat steps 2 and 3 until it has converged. EM never decreases L.

5. Assign each pattern to the component with the largest responsibility.

The EM loop for Gaussian mixture clusteringA flow from initialising π_k, μ_k and S_k to the E-step, which computes responsibilities, and the M-step, which computes new π_k, μ_k and S_k; if the log-likelihood has not converged the loop returns to the E-step, otherwise each pattern is assigned by its largest γ.Initialiseπ_k, μ_k, S_kE-step:responsibilitiesM-step: newπ_k, μ_k, S_kLog-likelihoodconverged?Assign bylargest γnoyes
The EM loop for Gaussian mixture clustering

Worked iteration. To keep the arithmetic short, S_k = I is kept fixed (σ² = 1), so with equal weights γ_i1 = 1 / (1 + e^((d1² − d2²)/2)), where d1² and d2² are the squared distances to μ1 and μ2.

Pt      d1²  d2²    γ1      γ2
A(1,1)   0   20   1.0000  0.0000
B(2,1)   1   13   0.9975  0.0025
C(3,1)   4    8   0.8808  0.1192
D(4,3)  13    1   0.0025  0.9975
E(5,3)  20    0   0.0000  1.0000

For C, γ1 = 1 / (1 + e^(−2)) = 0.8808. The M-step then gives:

  • N1 = 1.0000 + 0.9975 + 0.8808 + 0.0025 + 0.0000 = 2.8808, so π1 = 2.8808/5 = 0.576 and μ1 = Σγ_i1 x_i / N1 = (5.6475, 2.8858)/2.8808 = (1.96, 1.00).
  • N2 = 5 − 2.8808 = 2.1192, so π2 = 0.424 and μ2 = (9.3525, 6.1142)/2.1192 = (4.41, 2.89).

The log-likelihood rises from −15.52 to −13.72 in this one iteration. Both means move towards the middle, and C, shared 0.88 to 0.12, contributes to both of them. Iterating until convergence gives μ1 ≈ (2.00, 1.02) and μ2 ≈ (4.46, 2.94), with {A, B, C} in cluster 1 and {D, E} in cluster 2.

In conclusion, EM generalises K-means: K-means is the limit of EM with equal spherical variances shrinking to zero, where every responsibility becomes 0 or 1. EM gives probabilities and can model clusters of different shapes and sizes, but it is slower and can converge to a local maximum.

6 Explain the steps of spectral clustering. Apply them, with K = 2, to the four-node similarity graph with w(A,B) = 1, w(B,C) = 0.2 and w(C,D) = 1, all other weights being 0. 10 marks
Model answer

Spectral clustering treats the patterns as nodes of a weighted similarity graph and looks for groups of nodes joined by strong edges but separated from each other by weak ones. It uses eigenvectors of the graph Laplacian to map the patterns into a new space where K-means works well, so it can find non-convex clusters, such as two concentric rings, that K-means on the raw data cannot.

1. Build the similarity matrix W, for example w_ij = exp(−‖x_i − x_j‖² / 2σ²), or a k-nearest-neighbour or ε-neighbourhood graph.

2. Form the degree matrix D, a diagonal matrix with d_ii = Σ_j w_ij, and the Laplacian L = D − W (or the normalised form I − D^(−1/2) W D^(−1/2)).

3. Compute the eigenvectors of L for its K smallest eigenvalues and place them as the columns of an n × K matrix U.

4. Treat each row of U as the new representation of its pattern and cluster the rows with K-means.

5. Give each original pattern the cluster of its row.

Steps of spectral clusteringA top-to-bottom flow: patterns, the similarity matrix W, the Laplacian L = D − W, the matrix U from K eigenvectors, K-means on the rows of U, and finally the cluster of each pattern.Patternsx_1 to x_nSimilaritymatrix WLaplacianL = D − WU from KeigenvectorsK-means onrows of UCluster ofeach pattern
Steps of spectral clustering

Why it works: finding the smallest cut between two groups, balanced by their sizes (the ratio cut), is a hard combinatorial problem. Relaxing the 0/1 group indicator to real values turns it into finding the eigenvector of the second-smallest eigenvalue of L, called the Fiedler vector.

For the example, W with the degrees and L = D − W are:

W    A    B    C    D   degree
A    0    1    0    0    1.0
B    1    0   0.2   0    1.2
C    0   0.2   0    1    1.2
D    0    0    1    0    1.0

L     A     B     C     D
A   1.0  -1.0   0.0   0.0
B  -1.0   1.2  -0.2   0.0
C   0.0  -0.2   1.2  -1.0
D   0.0   0.0  -1.0   1.0

The eigenvalues of L are 0, 0.180, 2 and 2.220. The eigenvalue 0 has the constant eigenvector (0.5, 0.5, 0.5, 0.5). For the second, try v = (1, b, −b, −1): the first row of Lv = λv gives 1 − b = λ and the second gives −1 + 1.2b + 0.2b = λb. Eliminating b gives λ² − 2.4λ + 0.4 = 0, so λ2 = 1.2 − √1.04 = 0.180 and b = 0.820. Normalised, the Fiedler vector is (0.547, 0.448, −0.448, −0.547).

The rows of U are A (0.5, 0.547), B (0.5, 0.448), C (0.5, −0.448) and D (0.5, −0.547). K-means with K = 2 on these rows separates them by the sign of the second coordinate, giving {A, B} and {C, D}. This split cuts only the weak edge B–C, with cut weight 0.2, the smallest cut of the graph.

In conclusion, spectral clustering needs an eigen-decomposition, which costs O(n³) for a dense W, and its result depends on the similarity graph and σ; in return it captures cluster shapes that centroid-based methods miss.

Public sources that settled doubtful points

Only the points the second AI pass doubted were looked up. These are the pages that confirmed or contradicted them; nothing here is copied from them.

33 pages

Further reading

Titles only, for your own study. Nothing on this page is copied from them. The units follow the official JNTUK R23 CSE syllabus (PDF) ↗.

  • Machine Learning: Theory and Practice · M. N. Murty and V. S. Ananthanarayana
  • Machine Learning · Tom M. Mitchell
  • Machine Learning in Action · Peter Harrington
  • Introduction to Data Mining · Pang-Ning Tan, Michael Steinbach and Vipin Kumar