Feature Scaling for Machine Learning
Learning to locate the point of divergence is part of the skill.
Why Linear Models Hit a Ceiling
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 that a kernelized support vector machine uses to get past it.
Reading the Failure in Code Output
Begin by generating a small two-class dataset and fitting a linear support vector classifier to it. In this experiment 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 whole point of the experiment.
- y is cluster modulo 2, so the two classes interleave across the four blobs
- coef_ holds one weight per input feature
- intercept_ is the single offset term; together with coef_ it describes one straight line
Run the code yourself and notice two things. The training accuracy is well below perfect. The model also reports exactly one weight per input feature plus one intercept. Those numbers describe a single straight line. A linear classifier cannot bend, so when the classes interleave, no choice of weights and intercept avoids the misclassified points. The source reports the same qualitative outcome: a linear model can separate these points only with a line, and it does not do a very good job on this dataset.
Lifting Points with a Squared Feature
What do you think happens?
Suppose you 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?
Reveal answer
Yes, the extra coordinate can make a flat plane separate the classes that no line could separate in the original plane.
Linearity is relative to the coordinates you give the model. Changing the coordinates changes what the same family of linear models can do.
Each row of the original matrix is a point of the form (feature0, feature1). After the lift, each row is a point of the form (feature0, feature1, feature1 squared). The number of points stays the same. Only the number of coordinates grows. The lift is itself a one-line change, which appends the squared second feature as a new column of the input array.
- X[:, [1]] selects feature1 as a column vector so it can be stacked
- the number of rows is unchanged while the number of columns grows by one
- the fitted plane has one more weight, one for each of the three coordinates
The shape printout tells the story: the number of points is unchanged, but the number of features has grown by one. A linear SVM fitted to the expanded array finds a plane. If you project that plane back into the original two-dimensional plot, the boundary is no longer a straight line. It curves, and in the source's example it becomes something closer to an ellipse. This is the sense in which adding nonlinear features makes a linear model more powerful.
The Cost of Guessing Features
Adding a squared input works well in a small example, but the approach has a practical warning. Often you do not know which features to add, and the candidate list grows quickly. Every pairwise interaction in a 100-feature space, for instance, adds a large number of columns, which makes the computation expensive. You need a way to get the benefit of a high-dimensional representation without building it explicitly.
How the Kernel Trick Avoids Expansion
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.
The classifier only ever compares points through their pairwise scalar products. If a kernel can produce those products directly, the high-dimensional coordinates are never needed. That is why the source describes the trick 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, is harder to describe in finite terms because it corresponds to an infinite-dimensional feature space. One informal reading is that it considers polynomials of all degrees but gives less and less weight to the higher-degree features.
Support Vectors and Distance-Based Prediction
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. The support vectors are the border points that define the boundary, and the remaining points relate to the boundary only through their absence from that definition.
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.
Here $\lVert x_1 - x_2 \rVert$ is the Euclidean distance between two data points, and $\gamma$ (gamma) controls how quickly similarity fades with distance. The number of rows in support_vectors_ is the number of training points the model actually kept. Many fitted models will have far fewer support vectors than training points, which is the concrete form of the statement that only the border points matter.
Gamma and C as Complexity Controls
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.
Rescaling the Breast Cancer Features
The source applies an RBF kernel SVM to the Breast Cancer dataset with default settings. Here the failure is less visible than in the synthetic example, which is why it is worth tracing carefully. Fit the model on the raw training features and compare training and test accuracy.
raw train accuracy: 1.0
raw test accuracy: 0.63Locate the point of divergence. The training score is perfect, but the test score is only 0.63. The model has memorized the training points and does not generalize. The first suspect is model complexity, but the more useful suspect is input scale. The source notes that the features of this dataset differ by completely different orders of magnitude. SVMs are very sensitive to the scaling of the data, because they generally need all features to vary on a similar scale.
Rescaling the Breast Cancer features
The raw RBF SVM memorizes its training set and scores 0.63 on the test set. How do we rescale the features without leaking test information, and what does the result look like?
- 1Fit the scaler on training data only
A scaler such as MinMaxScaler stores the minimum and range of each feature. Computing these on the training set only keeps the test set out of preprocessing.
- 2Apply the same transform to the test data
The stored training minimum and range are reused for the test set, so both sets are scaled the same way.
- 3Refit the SVM on the scaled training data
With the features on a similar scale, training and test performance move closer together, which is the key result the source reports.
- 4Raise C once underfitting appears
The model is now in an underfitting regime, so the source increases C to 1000 to let the boundary fit more training points.
After rescaling and with C set to 1000, the source reports training accuracy of 0.988 and test accuracy of 0.972.
- fit is called on X_train only, so the scaling statistics come from training data
- transform is reused on X_test so both sets share one scaling
- C=1000 is the setting the source raises after rescaling
svc = SVC().fit(X_train, y_train)
# train 1.0, test 0.63Raw features: perfect training score, weak test score
scaler = MinMaxScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)
svc = SVC(C=1000).fit(X_train_s, y_train)
# train 0.988, test 0.972Rescaled features with C=1000: training and test scores close together
Mistakes Beginners Make
Common mistake Blaming the algorithm when the representation is the problem
What it looks likeTuning LinearSVC on the merged-blob dataset and expecting accuracy to rise sharply.
Why it failsA linear rule cannot bend, so no choice of weights and intercept avoids the misclassified points.
Do this insteadAsk first whether the inputs can be re-described so a linear rule becomes possible.
Common mistake Treating a perfect training score as success
What it looks likeTraining accuracy of 1.0 with a test accuracy of 0.63 on the raw Breast Cancer features.
Why it failsThe training score measures memorization of the training points, not generalization.
Do this insteadCompare the test score, and look for the point where training and test performance diverge.
Common mistake Fitting the scaler on the full dataset or on the test set
What it looks likeCalling fit on X_test, or on the combined data before splitting.
Why it failsThe statistics leak information about the test set into preprocessing and make the two sets scaled differently.
Do this insteadCall fit on the training data only, then reuse that transform for the test data.
Common mistake Assuming more features are always better
What it looks likeAdding every pairwise interaction of a 100-feature space as explicit columns.
Why it failsThe number of added columns grows quickly and makes the computation expensive.
Do this insteadUse a kernel, which gives the scalar products of the expanded space without writing the expansion down.
Common mistake Raising C without checking for underfitting, or lowering gamma without checking the boundary's smoothness
Practice: Diagnosing a Model
A colleague fits an RBF SVM on raw features and reports training accuracy 1.0 and test accuracy 0.63. Without changing the algorithm, name the most useful suspect, describe how you would rescale the features without leaking test information, and explain what result would suggest you should then adjust C.
Hints
- Compare the gap between training and test scores before deciding what to change.
- The source identifies input scale as the more useful suspect than model complexity here.
- Fit the scaler on training data only, then transform both sets.
- Underfitting appears when the model fails to fit training points that a more flexible boundary could capture.
Key Takeaways
- A linear classifier draws a flat boundary in whatever coordinates it is given, so the same rule can fail or succeed depending on the representation.
- Adding a derived feature such as a squared input can turn a non-separable problem into one a plane can separate, but choosing such features by hand is difficult and expensive.
- The kernel trick computes the scalar products of the expanded space directly from the original points, so the expanded coordinates are never built.
- Support vectors are the border points that define a kernelized SVM's boundary; gamma sets the radius of similarity and C controls how strongly single points can pull the boundary.
- When a model memorizes training data, check input scale first: SVMs generally need features on a similar scale, and scalers must be fitted on training data only.