Concepts / Linear Models for Classification and Regression

Linear Models for Classification and Regression

A baseline is a simple reference point: if a more advanced technique cannot beat it, the extra complexity is probably not worth the cost.

  • Programming
Interactive lab

Try it: k-Nearest Neighbours

How a k-nearest-neighbours classifier labels a new point: measure its distance to every known point, take the K closest, and let them vote.

How it works

  1. Measure the straight-line (Euclidean) distance from the new point to every labelled point.
  2. Rank the points from nearest to farthest.
  3. Keep the K nearest.
  4. Count how many of them belong to each class; the class with the most votes is the prediction (a tie goes to the class of the nearest tied neighbour).

Default run (15 steps): 10 labelled points and a new query point at (5, 3.5). K = 3. … Prediction: class A — A has the most votes.

Simplified: Small 2-D educational dataset (at most 30 points, three classes). Real KNN uses many features and usually scales them first.

Educational simulation

Loading the simulation…

Is k-NN Worth Trying First?

Imagine you have just learned the k-Nearest Neighbors method and want to know whether it is worth using on a real problem. The answer depends on a trade-off. The method is one of the easiest supervised learning ideas to explain, and it often produces reasonable results without much tuning. At the same time, the way it makes predictions can become expensive as your data grows, and it can struggle when each data point carries many features. This article asks a practical question: when does the simplicity of k-NN pay off, and when does it become a liability?

The second half of the article moves to linear models. They avoid the two drawbacks that limit k-NN, and they are the family behind LogisticRegression and LinearSVC. You will follow a single mechanism step by step: a weighted sum of features, an intercept, and a threshold at zero. Keep the k-NN trade-off in mind as you go, because it explains why linear models are often the next thing to try.

The Two k-NN Parameters

In principle, a k-NN classifier has two important parameters. The first is the number of neighbors, which is the value k in the name of the method. The second is the way you measure distance between data points. These two choices work together: the number of neighbors decides how many nearby training examples take part in a vote or average, and the distance measure decides what counts as nearby in the first place.

For the number of neighbors, practical experience suggests that a small value such as three or five often works well. The source is clear, however, that you should still adjust this parameter for your own data rather than accept a default guess. For the distance measure, the default is Euclidean distance, which works well in many settings. The source notes that choosing the right distance measure is somewhat beyond its scope, so for now treat Euclidean distance as the standard starting point.

Worked example

How k and the distance measure change the neighbors

Four labeled training points are 2D: A at (1, 1) labeled 0, B at (2, 2) labeled 0, C at (8, 8) labeled 1, and D at (1.5, 1) labeled 0. A new query point is at (2, 1.5). Using Euclidean distance and k equal to 3, which training points vote, and what is the predicted label?

  1. 1
    Compute the distance to B

    The difference is (0, 0.5), so the Euclidean distance is 0.5.

  2. 2
    Compute the distance to D

    The difference is (0.5, 0.5), so the distance is about 0.71.

  3. 3
    Compute the distance to A

    The difference is (1, 0.5), so the distance is about 1.12.

  4. 4
    Compute the distance to C

    The difference is (6, 6.5), so the distance is about 8.85, which is far larger than the others.

  5. 5
    Take the three nearest and vote

    B, D, and A are the three nearest. All three have label 0, so the majority vote predicts label 0.

Result

Predicted label 0. Changing k or the distance measure could change which points are the nearest neighbors, which is why both parameters matter.

Why k-NN Is a Useful Baseline

  • It is very easy to understand: a prediction is explained by pointing to the training examples closest to the new point.
  • It often gives reasonable performance without many adjustments, so you do not need a complicated structure before getting a useful first result.
  • Building the model is usually very fast, because much of the work happens when a prediction is requested rather than when the model is set up.

Because of these properties, k-NN is a good baseline method. A baseline is a simple reference point: if a more advanced technique cannot beat it, the extra complexity is probably not worth the cost. Trying k-NN first gives you a clear number to compare against.

Where k-NN Gets Slow and Weak

The main cost of k-NN appears at prediction time. Building the model is usually quick, but when the training set is very large, prediction can become slow. The size can be measured in two ways: the number of features, or the number of samples. A training set that is large in either dimension makes each prediction more expensive, because the new point has to be compared against many stored examples.

k-NN also does not perform well on datasets with many features, and it does particularly badly on sparse datasets, where most features are 0 most of the time. Each prediction compares the new point against every stored row, so with hundreds of features each comparison involves far more values, and the distances may stop being informative. This is why the source concludes that k-NN is seldom the final choice even though the code looks short and simple.

k-NN decides everything by comparing distances, so the scale and quality of the input values feed directly into the result. The source therefore states that when using k-NN, it is important to preprocess your data. Preprocessing means preparing the raw values before they reach the model, so that the distances the algorithm computes reflect the patterns you care about. Features measured on very different scales can dominate the distance calculation, which is why preprocessing matters before you trust a k-NN result.

How a Linear Score Becomes a Class

A linear model for binary classification starts with the same kind of calculation as a linear regression model. It forms a weighted sum of the input features and adds an intercept. Here $w$ holds the coefficients, $x$ holds the features, and $b$ is the intercept.

Formula

The difference lies in the final step. A regression model returns this weighted sum as its answer. A linear classifier thresholds the value at zero. If the value is smaller than zero, the model predicts class -1. If the value is larger than zero, it predicts class +1. This prediction rule is common to all linear models for classification. The models differ in how they find the coefficients $w$ and the intercept $b$, not in how they turn the score into a class.

Features xWeighted sum w timesxAdd intercept bScore greater thanzero?Class +1Class -1multiply by coefficientsaddcheck signyesno
What sequence of steps turns the features into a weighted sum, adds the intercept, and then assigns one of two class labels based on the sign of the score?
Worked example

Thresholding one score

A linear classifier has coefficients w = (2, -1), intercept b = 0.5, and a new point x = (1, 3). Which class does it predict?

  1. 1
    Compute the weighted sum

    $w \cdot x = 2 \times 1 + (-1) \times 3 = -1$.

  2. 2
    Add the intercept

    The score is $-1 + 0.5 = -0.5$.

  3. 3
    Threshold at zero

    The score is smaller than zero, so the rule assigns class -1.

Result

The model predicts class -1.

Decision Boundaries as Lines and Hyperplanes

The rule above creates a boundary between the two classes. For regression, the output is a linear function of the features, which is a line, a plane, or a hyperplane in higher dimensions. For classification, the decision boundary is the set of points where the score sits exactly at the threshold. A binary linear classifier therefore separates two classes using a line, a plane, or a hyperplane. Any new point on one side of that boundary gets one class, and any point on the other side gets the other class.

Coefficients wScore equals zeroDecision boundaryScore above zero:class +1Intercept bScore below zero:class -1tiltsoffsetsdefinesone sideother side
Why does setting the score w times x plus b to zero carve the feature space into two regions, and how does the boundary move when w or b changes?

The source illustrates this with the forge dataset. Both LinearSVC and LogisticRegression are fit with their default parameters, and each produces a straight line. The area on one side of the line is classified as class 1 and the area on the other side as class 0. The two lines are similar, and both misclassify two training points. That agreement is the point of the example: two different algorithms can learn very similar boundaries from the same data.

Why LogisticRegression Is a Classifier

A common first reaction to the name LogisticRegression is to assume it predicts a number, the way LinearRegression does. That assumption is wrong. LogisticRegression is a classification algorithm, not a regression algorithm, even though its name suggests otherwise. Linear models are used heavily for classification, meaning they predict which category an input belongs to, and LogisticRegression is one of the two most common linear classification algorithms.

The two most common linear classification algorithms are logistic regression, available as LogisticRegression in the linear_model module, and linear support vector machines, available as LinearSVC in the svm module. The name SVC stands for support vector classifier. Both are linear classifiers, and both apply L2 regularization by default. Once you see how a linear model turns a score into a class label, the name stops being confusing.

The many algorithms for learning linear models differ in two ways. The first is how they measure how well a particular combination of coefficients and intercept fits the training data, which is the loss function. The source notes that this choice matters little for many applications. The second is whether they use regularization, and if so, what kind. Regularization is the choice that matters most for controlling how a model generalizes.

Tuning C: Fit Versus Simplicity

For both LogisticRegression and LinearSVC, the parameter that sets the strength of regularization is called C. Higher values of C correspond to less regularization. A high C asks the model to fit the training set as well as possible. A low C asks the model to keep the coefficient vector close to zero. So C is a single dial that trades off fitting the training data against keeping the model simple. A low C pushes coefficients toward zero, while a higher C allows a closer fit to the training set.

The source also describes a second way C acts. A low C makes the algorithm adjust to the majority of the data points, while a higher C gives more weight to classifying each individual point correctly. The source illustrates this with LinearSVC on the forge dataset across three values of C. With a very small C, the model chooses a relatively horizontal line and misclassifies two points. With a slightly higher C, the line tilts to respond to the two misclassified samples. With a very high C, the line tilts sharply and classifies all class 0 points correctly, but still misclassifies one class 1 point, because no straight line can separate this dataset perfectly.

Relativelyhorizontal line2 training pointsmisclassifiedSharply tilted lineAll class 0 correct,1 class 1 wrongLikely overfittingsmall Cvery high Cwarned by source
How does the fitted decision boundary change between a small C and a large C, and which setting makes the model more likely to overfit?

The source warns that this most aggressive model is likely overfitting, since it tries hard to classify every point and may miss the overall layout of the classes. A very high C can overfit, so judge the value of C by comparing training and test accuracy rather than training accuracy alone. The source reports, for an L1 penalty on the same kind of task, training and test accuracies of 0.91 and 0.92 for C equal to 0.001, 0.96 and 0.96 for C equal to 1, and 0.99 and 0.98 for C equal to 100. The training accuracy keeps rising with C, but the test accuracy is the signal that tells you when the extra fit stops helping.

Mistakes Beginners Make

  • Common mistake

    Assuming LogisticRegression predicts a number because of its name

    Why it fails

    LogisticRegression is a classification algorithm, not a regression algorithm.

    Do this instead

    Treat it as a classifier that outputs class labels, and use LinearRegression when you need a numeric output.

  • Common mistake

    Judging C by training accuracy alone

    Why it fails

    A very high C can overfit, and training accuracy keeps rising as C grows.

    Do this instead

    Compare training and test accuracy before choosing C.

  • Common mistake

    Reading coefficients as clear evidence about a class

    What it looks like

    On the Breast Cancer dataset, the coefficient for mean perimeter is negative for C equal to 100 and C equal to 1, but positive for the strongly regularized model.

    Why it fails

    The sign of a coefficient depends on which model you inspect, so one feature can look supportive of either class.

    Do this instead

    Take interpretations of linear model coefficients with a grain of salt.

  • Common mistake

    Running k-NN on raw features with different scales

    Why it fails

    k-NN decides everything by comparing distances, so features on large scales can dominate the result.

    Do this instead

    Preprocess the data before fitting k-NN, as the source recommends.

  • Common mistake

    Choosing k-NN for a large, many-feature dataset without checking prediction speed

Predict the Class Before the Reveal

What do you think happens?

A linear classifier computes a score of 2.3 for a new point. Which class does it predict?

  • Class +1

  • Class -1

  • It cannot be determined from the score

Reveal answer
Answer:

Class +1

The rule thresholds the score at zero. A score larger than zero is assigned class +1.

MEDIUM

A dataset has a modest number of samples, a handful of features, and a deadline. Decide whether k-NN is a sensible first model. Consider three questions: Is the model easy to explain to your team? Is the training set small enough that prediction will stay fast? Are the features numerous or sparse in a way that might hurt distance comparisons? Write down your answer and the reason for it.

Hints
  • Think about where k-NN spends its time: at prediction, not at setup.
  • The source frames k-NN as a baseline, not necessarily the final model.

Key Takeaways

  • k-NN has two main parameters: the number of neighbors k, where small values such as three or five often work well, and the distance measure, where Euclidean distance is the default.
  • k-NN is easy to explain and often a useful baseline, but prediction can be slow for large training sets and it struggles with many features, especially sparse ones.
  • A linear classifier forms a weighted sum $w \cdot x + b$ and thresholds it at zero, so its decision boundary is a line, plane, or hyperplane.
  • LogisticRegression is a classification algorithm despite its name, and C controls regularization: higher C means a closer fit to the training set and a greater risk of overfitting.
  • Judge the value of C by comparing training and test accuracy, not training accuracy alone.

Related concepts

More concepts starting with L