IAE Academy

GATE DA

Logistic regression, k-nearest neighbour and naive Bayes

Logistic regression, k-nearest neighbour and naive Bayes are the three basic classifiers in the GATE DA Machine Learning unit. Logistic regression turns a linear score into a probability and is trained by minimising cross-entropy. k-NN predicts from stored data using distances, and naive Bayes from probabilities counted in the training data. Typical questions ask for a class probability from given weights, a gradient or a gradient-descent update, a k-NN vote, or a posterior from a small training table. You need both the formulas and the working habits for each.

4 previous-year questions · 4 solved · 6 practice questions

Logistic regression: the model

Convention used throughout: is a feature vector, the weight vector, the bias. Labels are ; a variant with labels in is noted where it changes a formula. Samples are the rows of , is the model's predicted probability of class 1 for sample , always means the sigmoid, and is the natural logarithm. Despite its name, logistic regression is a classifier. It models the probability of class 1 by passing a linear score through the sigmoid.

SIGMOID (LOGISTIC FUNCTION)

The output lies in (0, 1). ; as and as .

SIGMOID IDENTITIES

The derivative is at most 0.25, reached at . This identity is what makes the gradient of the cross-entropy loss so simple.

LOGISTIC REGRESSION MODEL

Binary classification. The prediction is class 1 when this probability exceeds the chosen threshold, which is 0.5 unless the question states another.

LOG-ODDS (LOGIT) IS LINEAR

With the other features fixed, each unit increase in adds to the log-odds, which multiplies the odds by .

DECISION BOUNDARY

The boundary is a hyperplane, so logistic regression is a linear classifier. is normal to the boundary and points towards the class-1 side. Changing moves the hyperplane parallel to itself.

EXAM TIP

To classify at threshold 0.5 you do not need the sigmoid: check the sign of . Compute only when the question asks for the probability itself.

Logistic regression: loss, gradient and training

The weights are found by maximum likelihood, which is the same as minimising the cross-entropy (log-loss). There is no closed-form solution, so gradient descent or a similar iterative method is used. The loss is convex in , so gradient descent cannot get stuck in a bad local minimum. If the training data are linearly separable, however, no finite minimiser exists (see the list below).

LOG-LIKELIHOOD

Each sample contributes . Maximising and minimising give the same weights.

CROSS-ENTROPY LOSS (NATURAL LOG)

For one sample the loss is if and if . Using instead only multiplies the loss by a constant.

THE SAME LOSS WITH LABELS IN {−1, +1}

This is identical to the cross-entropy above, rewritten for labels using . Check which label convention a question uses before you substitute.

GRADIENT OF THE LOSS

Labels in . This has the same form as linear regression's gradient when that loss is written , with in place of the linear prediction. For a single sample, drop the and the sum.

L2-REGULARISED LOSS AND GRADIENT

sets the strength of the penalty. The bias is usually not penalised, so is unchanged. Books scale differently (with or without or ), so use the form the question gives.

GRADIENT DESCENT UPDATE

is the learning rate. With the squared-error loss per sample instead, the gradient picks up an extra factor . Learning then slows when the sigmoid saturates, and the loss is no longer convex in .

Facts worth remembering

  1. The sign of gives the direction of the update. If and is small, the update moves the weights along .

  2. If the training data are linearly separable, the likelihood keeps rising as , so the unregularised weights never converge. An L2 penalty fixes this.

  3. Changing the threshold moves the decision boundary parallel to itself, so the model is a linear classifier at every threshold.

  4. For more than two classes, the softmax replaces the sigmoid: with .

WORKED EXAMPLE

A logistic regression model has and . For the sample with label : (a) find ; (b) do one gradient-descent step on this single sample with , and give the new weights and bias.

Solution
  1. , so . The model predicts class 0, but the label is 1.

  2. .

  3. and .

  4. .

  5. (to 4 d.p.).

  6. Check: the new score is , so .

Answer: (a) . (b) and . The probability for this sample rises to about 0.767.

k-nearest neighbour: the method

k-NN is a lazy, non-parametric method: training only stores the data. To predict for a query point, find the training points closest to it. For classification, take the majority class among them; for regression, take their average. Use Euclidean distance unless the question says otherwise.

EUCLIDEAN, MANHATTAN, MINKOWSKI AND CHEBYSHEV DISTANCE

Euclidean is , Manhattan is , and Chebyshev is the limit . is a metric for . The order is written here because means a predicted probability in these notes. The nearest neighbour can change from one metric to another, so always use the one the question names.

K-NN REGRESSION

is the set of the nearest training points. A distance-weighted version uses weights proportional to . A query that coincides with a training point () is usually given that point's value.

Procedure for a k-NN classification question

  1. Scale the features first if the question says so.

  2. Compute the distance from the query to every training point. Squared distances give the same ordering and save the square root.

  3. Sort the distances and pick the smallest. If two points tie for the -th place, follow the question's rule.

  4. Count the class labels among the neighbours. The majority class is the prediction.

  5. If the vote ties, follow the question's rule (a smaller , the nearest neighbour's class, or a fixed class). In a two-class problem an odd prevents vote ties. It does not prevent ties in distance.

Choice of k

Effect

Training error is zero, because each training point is its own nearest neighbour at distance 0. This holds unless identical feature vectors carry different labels. The boundary is jagged: high variance, sensitive to noise.

Small

Low bias, high variance: overfitting.

Large

High bias, low variance: a smoother boundary, with a risk of underfitting.

Every query gets the overall majority class (the global mean in regression), with unweighted votes.

k-NN works from distances, so a feature with a large numeric range dominates the others. Feature scaling (min–max or standardisation) puts the features on a comparable footing. Irrelevant features and high dimension also hurt: in many dimensions, the distances from a query to all points become similar and so less informative. This is the curse of dimensionality. Prediction is slow: a brute-force search touches all stored points, costing per query for features.

MIN-MAX AND Z-SCORE SCALING

and are the mean and standard deviation of the feature. Compute , , and from the training data, and apply the same values to the query.

Further facts

  1. The 1-NN decision boundary is made of pieces of the perpendicular bisectors between training points of different classes: the faces of the Voronoi cells around the training points.

  2. As (with i.i.d. data and smooth class densities), the error rate of 1-NN is at most twice the Bayes error rate, the lowest error any classifier can achieve.

  3. For categorical features, Hamming distance (the number of features that differ) is the usual choice.

EXAM TIP

In leave-one-out evaluation, the point being tested is removed from its own neighbour set. Forgetting this gives it a distance of 0 to itself and a wrong vote.

Naive Bayes classifier

Naive Bayes applies Bayes' theorem with one strong assumption: given the class, the features are conditionally independent. That turns a hard joint likelihood into a product of one-feature terms, each easy to estimate by counting.

NAIVE BAYES POSTERIOR

This assumes the features are conditionally independent given the class. The denominator is the same for every class, so you need it only when the question asks for an actual probability.

NAIVE BAYES DECISION RULE (MAP)

Compare the unnormalised scores. In practice the logs are summed, , to avoid numerical underflow. With equal priors, the rule reduces to picking the class with the largest likelihood (maximum likelihood).

ESTIMATES FROM COUNTS

is the number of training samples in class , and is how many of them have feature equal to . These are maximum-likelihood estimates and can be zero. Priors are smoothed only if the question says so.

LAPLACE (ADD-$\ALPHA$) SMOOTHING

is the number of distinct values feature can take (2 for a binary feature). is Laplace smoothing. It stops a single unseen value from forcing the whole product to zero.

MULTINOMIAL NAIVE BAYES (WORD COUNTS)

Used for text classification. is the number of times word appears across the training documents of class , is the vocabulary size, and is how often occurs in the document being classified.

GAUSSIAN NAIVE BAYES

For continuous features. and are the mean and variance of feature within class (here is a standard deviation, not the sigmoid). The maximum-likelihood variance divides by and the unbiased one by ; use the one the question states. The result is a density, so it can exceed 1. Multiply the terms together as before.

NUMBER OF PARAMETERS (D BINARY FEATURES, K CLASSES)

The independence assumption makes the parameter count grow linearly in instead of exponentially. The term counts the priors, since they sum to 1.

Procedure for a training-table question

  1. Count the samples in each class to get the priors .

  2. For each class and each feature value in the query, count the matching rows to get . Add smoothing if the question asks for it.

  3. Multiply the prior by the likelihoods to get one score per class.

  4. Pick the class with the largest score. For a posterior, divide that class's score by the sum of all the scores.

WORKED EXAMPLE

A training set of six emails has two binary features: Free (the word 'free' is present) and Win (the word 'win' is present). Rows (Free, Win, class): (Y,Y,Spam), (Y,N,Spam), (Y,Y,Spam), (N,N,Ham), (Y,N,Ham), (N,Y,Ham). Classify a new email with Free = Y and Win = Y, and give the posterior probability of Spam (a) without smoothing and (b) with Laplace smoothing on the likelihoods.

Solution
  1. Priors: and .

  2. (a) Spam: and , so the score is .

  3. Ham: and , so the score is .

  4. Posterior of Spam .

  5. (b) The features are binary, so add 1 to each numerator and 2 to each denominator. Spam: . Ham: .

  6. Posterior of Spam .

Answer: (a) ; (b) . Both classify the email as Spam. Here, smoothing pulls the posterior towards 0.5.

EXAM TIP

Naive Bayes can rank the classes correctly even when the independence assumption is false. Its posterior probabilities can then be unreliable, typically pushed towards 0 or 1 when correlated features count the same evidence twice. Priors matter too: a rare class needs a strong likelihood to win.

Comparing the three and common traps

Property

Logistic regression

k-NN

Naive Bayes

Type

Discriminative (models ), parametric

Instance-based, non-parametric

Generative (models ), parametric

What is learned

and , by gradient descent

Nothing (stores the data)

Priors and per-feature likelihoods, by counting

Decision boundary

Linear

Flexible, locally defined (piecewise linear for 1-NN)

Linear for binary or one-hot categorical features, and for Gaussian features with variances shared across classes. Quadratic for Gaussian features with class-specific variances.

Main hyperparameters

Learning rate, regularisation strength

, distance metric

Smoothing

Needs feature scaling

Helps gradient descent converge; matters when weights are regularised

Essential

No (Gaussian naive Bayes uses per-class variances)

Prediction cost per query

by brute force: touches every stored point

Key assumption

Log-odds are linear in the features

Nearby points share a label

Features are independent given the class

Traps to avoid

  1. Logistic regression predicts a class probability. It is not a regression model for a continuous target.

  2. A sigmoid output of 0.5 corresponds to log-odds 0, that is , not .

  3. In the gradient the error term is (prediction minus label). Flipping the sign makes the update move the wrong way.

  4. Check whether the labels are or before you use a loss or gradient formula.

  5. k-NN with has zero training error, but that says nothing about test error.

  6. Squared distances are fine for ranking neighbours, but not as the in a -weighted vote.

  7. In naive Bayes a zero count gives a zero likelihood that wipes out the whole product unless smoothing is used. The amount added to the denominator is , not .

  8. Do not drop the prior when the classes in the training table are imbalanced.

PREVIOUS-YEAR QUESTIONS

4 questions from the DA papers

Try each question first, then open the answer. We placed each question under a topic ourselves; the exam paper does not label topics.

See these papers in full: GATE DA 2025 · GATE DA 2024

GATE 2025 DA Q.35

GATE 2025 · DAQ.35 · 1 mark · NAT

The naive Bayes classifier is used to solve a two-class classification problem with class-labels , . Suppose the prior probabilities are and . Assuming a discrete feature space with

for a specific feature vector . The probability of misclassifying is ______ (Round off to two decimal places)

Answer and solution
See the question in the paper
GATE 2025 DA Q.35: answer and solution

GATE 2024 DA Q.18

GATE 2024 · DAQ.18 · 1 mark · MCQ

Match the items in Column 1 with the items in Column 2 in the following table:

| Column 1 | Column 2 |
|---|---|
| (p) Principal Component Analysis | (i) Discriminative Model |
| (q) Naïve Bayes Classification | (ii) Dimensionality Reduction |
| (r) Logistic Regression | (iii) Generative Model |

GATE 2024 DA question 18: A two-column table.Tap to open full size
Figure from the GATE 2024 DA paper. It is part of the question.
Figure description

A two-column table. Column 1 rows: (p) Principal Component Analysis, (q) Naïve Bayes Classification, (r) Logistic Regression. Column 2 rows: (i) Discriminative Model, (ii) Dimensionality Reduction, (iii) Generative Model.

  1. (A)

    (p) − (iii), (q) − (i), (r) − (ii)

  2. (B)

    (p) − (ii), (q) − (i), (r) − (iii)

  3. (C)

    (p) − (ii), (q) − (iii), (r) − (i)

  4. (D)

    (p) − (iii), (q) − (ii), (r) − (i)

Answer and solution
GATE 2024 DA Q.18: answer and solution

GATE 2024 DA Q.63

GATE 2024 · DAQ.63 · 2 marks · NAT

Given the two-dimensional dataset consisting of 5 data points from two classes (circles and squares) and assume that the Euclidean distance is used to measure the distance between two points. The minimum odd value of in -nearest neighbor algorithm for which the diamond () shaped data point is assigned the label square is ______.

GATE 2024 DA question 63: A 2D grid plot with x-axis and y-axis both marked 1, 2, 3.Tap to open full size
Figure from the GATE 2024 DA paper. It is part of the question.
Figure description

A 2D grid plot with x-axis and y-axis both marked 1, 2, 3. Circles (class 1) at (1,1) and (1,2). Squares (class 2) at (2,3), (3,3) and (3,2). A diamond-shaped query point at (2,1). Each point is labelled with its coordinates.

Answer and solution
GATE 2024 DA Q.63: answer and solution

PRACTICE

6 questions to test yourself

PRACTICE 11 mark · MCQ

A logistic regression model has weight for feature (natural log). With all other features fixed, increasing by 1 multiplies the odds by a factor of

  1. (A)

  2. (B)

    3

  3. (C)

  4. (D)

Answer and solution

Answer: (B)

  1. The log-odds equal , so increasing by 1 adds to the log-odds.

  2. Adding to the log of the odds multiplies the odds by .

PRACTICE 22 marks · NAT

A logistic regression model has and . A training sample has label . Take the cross-entropy loss (natural log) of this single sample. Find the gradient component , correct to three decimal places.

Answer and solution

Answer: (accepted range )

  1. .

  2. .

  3. .

PRACTICE 32 marks · NAT

Six training emails have binary features Free and Win. Rows (Free, Win, class): (Y,Y,Spam), (Y,N,Spam), (Y,Y,Spam), (N,N,Ham), (Y,N,Ham), (N,Y,Ham). A naive Bayes classifier uses Laplace smoothing with on the likelihoods: add 1 to each count and 2 to each class count, since each feature has two values. The priors are estimated without smoothing. For a new email with Free = Y and Win = N, find , correct to three decimal places.

Answer and solution

Answer: (accepted range )

  1. The priors are and .

  2. Spam: . One Spam row has Win = N, so . Score .

  3. Ham: . Two Ham rows have Win = N, so . Score .

  4. Posterior .

PRACTICE 41 mark · NAT

A naive Bayes classifier has classes and binary features. How many independent parameters (class priors plus class-conditional feature probabilities) must it estimate?

Answer and solution

Answer:

  1. Priors: the three class probabilities sum to 1, so are independent.

  2. Likelihoods: each binary feature needs one probability per class, giving .

  3. Total . A full joint model would need .

PRACTICE 52 marks · MSQ

One-dimensional training points with labels: (A), (A), (B), (B), (B). A k-NN classifier (Euclidean distance, majority vote) classifies the query . For which of the following settings is the predicted class A?

  1. (A)

  2. (B)

  3. (C)

  4. (D)

    , with vote ties broken in favour of class B

Answer and solution

Answer: (A), (B)

  1. Distances from 2.9: , , , , .

  2. : the nearest point is (A), so A.

  3. : the nearest three are (A), (B) and (A). Two A votes against one B, so A.

  4. : all points vote, 2 A against 3 B, so B.

  5. : adding (B) gives 2 A and 2 B. The tie is broken towards B, so B.

PRACTICE 61 mark · MCQ

A 1-nearest-neighbour classifier (Euclidean distance) has two training points, and . The query is . Its nearest neighbour is found (i) with the raw features and (ii) after dividing the second feature of every point, including the query, by 10. The nearest neighbours in (i) and (ii) are, respectively,

  1. (A)

    and

  2. (B)

    and

  3. (C)

    and

  4. (D)

    and

Answer and solution

Answer: (B)

  1. (i) Raw: and , so is nearest.

  2. (ii) Scaled: and , so and . Now is nearest.

  3. Scaling changes the answer: , then .

OFFICIAL GATE 2027 SYLLABUS WORDING

Copied from the GATE 2027 syllabus; see all 2027 syllabi.

GATE DA

logistic regression, k-nearest neighbour, naive Bayes classifier

Preparing in Kolkata? IAE Academy's course for GATE DA.