Concepts / Linear Models for Classification

Linear Models for Classification

A linear classifier draws a flat boundary in whatever coordinates it is given, so changing the representation can make the same linear rule useful on data that a line cannot separate.

  • Programming

Where a Straight Boundary Breaks

Most of the linear classifiers you have met so far separate classes with a single flat boundary: a line in two dimensions, a plane in three. That restriction is simple and fast, but it is also a hard ceiling. Some datasets simply do not have their two classes arranged on opposite sides of any straight cut. This article starts with exactly that failure, shows where it appears in code, and then builds the tools a kernelized support vector machine uses to get past it.

Keep one question in mind as you read: when a model's answer looks wrong, where in the pipeline did the answer first diverge from what you expected? Several mistakes in this article are not errors in the algorithm itself but in the data representation or the scale of the inputs. Learning to locate the point of divergence is part of the skill.

Reading the Symptom in Code Output

Begin with a small two-class dataset and fit a linear support vector classifier to it. The labels are produced by taking the cluster label modulo 2, which merges four blob centers into two classes. The classes are therefore not arranged as two clean halves, and that is the point of the experiment.

python
Notes on the code
  • make_blobs creates four cluster centers; the modulo step merges them into two labels
  • LinearSVC learns one flat boundary over the two input features

Run the code and notice two things. The training accuracy is well below perfect, and the model reports exactly one weight per input feature plus one intercept. Those three numbers describe a single straight line. A linear classifier cannot bend, so when the classes interleave, no choice of weights and intercept avoids every misclassified point. The source reports the same qualitative outcome: a linear model can only separate these points with a line and does not do a very good job on this dataset.

What do you think happens?

Keep feature0 and feature1 and add one new column: the square of feature1. Could a flat plane in this three-dimensional space separate the two classes, even though no line could separate them in the original plane?

  • No, adding a column cannot change what a flat boundary can do

  • Yes, the extra coordinate can make a flat plane separate the classes

Reveal answer
Answer:

Yes, the extra coordinate can make a flat plane separate the classes

Linearity is relative to the coordinates the model is given. A plane in the expanded space can correspond to a curved boundary in the original plane, so the same linear rule becomes useful.

Changing the Coordinates

The reveal is worth dwelling on. Linearity is a property relative to the coordinates you give the model. Change the coordinates and the same family of models behaves differently. Adding derived features such as a squared input can turn a non-separable problem into one that a plane can separate. The catch is that choosing those features by hand is difficult and expensive.

Read the diagram from top to bottom. On the left, each point is described by two coordinates and no line separates the classes. On the right, the same points are described by three coordinates, where the third is the square of the second. The number of points is unchanged, but the number of features has grown by one. A flat plane in this expanded space separates the classes. When that plane is projected back into the original two-dimensional plot, the boundary is no longer straight. In the source's example it curves into something closer to an ellipse. This is the sense in which nonlinear features make a linear model more powerful.

python
Notes on the code
  • X[:, 1:] selects the second feature column
  • The shape printout shows the same number of rows with one more column

The Kernel Trick

The kernel trick is the mathematical device that makes this possible. The learner needs only the scalar products between pairs of points in the expanded space, not the expanded coordinates themselves. A kernel is a function that takes two points in the original space and returns the value those scalar products would have had after expansion. The expansion is never written down.

Expand each pointbuild the high-dimensionalvectorDot productscomputed from expandedvectorsOriginal pointstwo low-dimensional vectorsKernel functionreturns the same scalarproductthendirectly
What is computed in the expanded feature space versus implicitly through the kernel function, and why does the kernel avoid constructing the high-dimensional vectors?

The two columns of the comparison reach the same quantity by different routes. The explicit route builds each expanded vector and then takes scalar products. The kernel route skips the expanded vectors and computes the scalar product directly from the original points. The classifier only ever compares points through these pairwise scalar products, so when a kernel can produce them directly, the high-dimensional coordinates are never needed. The source describes this as the reason kernelized SVMs are practical: it allows efficient computation in spaces that would otherwise be too large to handle.

Two kernels are commonly used with support vector machines. The polynomial kernel corresponds to all possible polynomials of the original features up to a chosen degree. The source's example of such a term is feature1 squared times feature2 to the fifth power. The radial basis function kernel, also called the Gaussian kernel, corresponds to an infinite-dimensional feature space and is harder to describe in finite terms. One informal way to read it is that it considers polynomials of all degrees, while giving less and less weight to features at higher degrees.

Formula

Here $\lVert x_1 - x_2 \rVert$ is the Euclidean distance between the two data points, and $\gamma$ (gamma) controls how quickly similarity fades with that distance. The source notes that the detailed mathematics of kernel SVMs is not essential for using them. What matters in practice is how the model makes a decision, which the next section explains.

Support Vectors and the Decision Boundary

During training, the SVM estimates how important each training point is to the boundary between the two classes. In practice only a subset of those points matter. They are the points lying on the border between the classes, and they are called support vectors. The name of the method comes from them.

Prediction works through distances. For a new point, the model measures its distance to each support vector and combines those distances with the learned importances. The source says these importances are stored in the dual_coef_ attribute of SVC. The Gaussian kernel supplies the distance measure. The number of rows in support_vectors_ is the number of training points the model actually kept. Many fitted models have far fewer support vectors than training points, which is the concrete form of the statement that only border points matter.

python
Notes on the code
  • support_vectors_ holds the rows the model kept
  • dual_coef_ stores the learned importance of each kept point

Tuning Gamma and C

Two parameters shape an RBF kernel SVM. Gamma sets the width of the Gaussian. A small gamma gives a large radius, so many points count as close to each other, and the boundary is smooth. A large gamma shrinks that radius, so the boundary bends around individual points and becomes more complex. The parameter C is a regularization term, similar in spirit to the one in linear models. A small C restricts how much any single point can influence the model. Raising C lets misclassified points pull the boundary toward themselves, so the boundary bends to classify them.

SettingChangeEffect on the boundary
gammaSmallLarge radius, many points count as close, smooth boundary
gammaLargeSmall radius, boundary bends around individual points, more complex
CSmallEach point has limited influence, simpler boundary
CLargeMisclassified points pull the boundary toward themselves, more complex

How gamma and C change the complexity of a kernelized SVM boundary

Worked example

Locating the divergence on Breast Cancer data

The source applies an RBF kernel SVM to the Breast Cancer dataset with default settings. The training score is perfect, but the test score is only 0.63. Where does the pipeline diverge from what we expect?

  1. 1
    Observe the gap

    The model has memorized the training points and does not generalize. The first suspect is model complexity.

  2. 2
    Find the better suspect

    The features of this dataset differ by completely different orders of magnitude. SVMs are very sensitive to the scaling of the data and generally need all features to vary on a similar scale, so input scale is the more useful suspect.

  3. 3
    Rescale using training statistics

    The minimum and range are computed on the training data and reused for the test data. Computing them separately on the test set would leak information about the test set into preprocessing and scale the two sets differently.

  4. 4
    Compare the result

    Rescaling moves the model from a heavily overfit state to one where training and test performance are close. The model is now in an underfitting regime.

  5. 5
    Raise C

    The source then increases C to 1000, which raises training accuracy to 0.988 and test accuracy to 0.972.

Result

The divergence came from input scale first. Only after the scale was fixed did a larger C help the model fit the training data well and generalize.

Mistakes Beginners Make with Linear and Kernel Models

  • Common mistake

    Tuning the linear model when the representation is the real problem

    What it looks like

    Changing regularization on LinearSVC while the classes interleave in the original two features.

    Why it fails

    A linear classifier draws a flat boundary in whatever coordinates it is given. No setting of weights and intercept avoids the misclassified points.

    Do this instead

    First ask whether the inputs can be re-described so that a linear rule becomes possible.

  • Common mistake

    Assuming the kernel trick builds the expanded features

    What it looks like

    Writing out every pairwise interaction of a 100-feature space to feed a linear model.

    Why it fails

    The kernel trick needs only the scalar products between pairs of points, and the expansion is never written down.

    Do this instead

    Use a kernel function that returns the scalar product directly from the original points.

  • Common mistake

    Fitting the scaler on the test set

    What it looks like

    Computing the minimum and range separately on the test data before rescaling it.

    Why it fails

    This leaks information about the test set into preprocessing and scales the two sets differently.

    Do this instead

    Compute the minimum and range on the training data and reuse them for the test data.

  • Common mistake

    Ignoring feature scale before blaming model complexity

    What it looks like

    Seeing a perfect training score and a test score of 0.63, then only lowering model complexity.

    Why it fails

    SVMs are very sensitive to the scaling of the data, and features with very different magnitudes can cause the overfit.

  • Common mistake

    Believing that raising C always improves generalization

Practice: Diagnosing a Failed Boundary

MEDIUM

A linear SVM gives low training accuracy on a two-class dataset whose classes interleave. Describe the symptom you would see in code output, then explain whether you would fix it by tuning the linear model or by changing the representation of the inputs. Justify your choice using the idea that linearity is relative to the coordinates.

Hints
  • Compare the training accuracy with 1.0 and think about what the model's weights and intercept describe.
  • Ask whether a derived feature such as a squared input could make a flat boundary possible.

Key Takeaways from Flat Boundaries and Kernels

  1. 1
    A linear classifier draws a flat boundary in whatever coordinates it is given, so a dataset that interleaves in the original features can show low training accuracy with no fix from tuning alone.
  2. 2
    Adding derived features such as a squared input can make a non-separable problem separable by a plane, but choosing those features by hand is difficult and expensive.
  3. 3
    The kernel trick computes the scalar products of the expanded representation directly from the original points, so high-dimensional similarity becomes practical.
  4. 4
    Support vectors are the border points that define a kernelized SVM's decision boundary, and gamma and C control how complex that boundary becomes.

At a glance

  • A linear classifier draws a flat boundary in whatever coordinates it is given, so the representation of the inputs matters as much as the model.
  • Adding a derived feature such as a squared input can turn a non-separable problem into one a plane can separate.
  • The kernel trick computes expanded-space scalar products directly from the original points, avoiding the explicit high-dimensional vectors.
  • Support vectors are the border points that define a kernelized SVM's boundary; gamma sets the width of the Gaussian and C controls how much individual points can pull the boundary.

Related concepts

More concepts starting with L