Concepts / Histograms for Feature Analysis

Histograms for Feature Analysis

Per-feature histograms ask how one feature behaves across classes. PCA asks how the features move together, and it summarizes that joint behavior in a small number of new directions.

  • Programming

A Tidy Picture and a Tempting Conclusion

Imagine you have a dataset with many measurements per sample and two known classes. You reduce the measurements to two principal components, draw a scatter plot, and color each point by its class. The two colors form neat, separate clusters. It is natural to conclude that the projection was built to separate the classes. That reasoning feels correct because the picture is so tidy, but it is wrong, and the mistake changes how you should judge the plot. This article starts from that misconception, tests it with a prediction, and then rebuilds the workflow step by step so you can see exactly where class information enters and where it does not.

What do you think happens?

When PCA chooses its two new axes, does it use the class labels to decide where those axes point?

  • Yes, it rotates the data so the classes are as far apart as possible

  • No, it finds the axes from correlations among the features, and the labels are used later only for coloring

Reveal answer
Answer:

No, it finds the axes from correlations among the features, and the labels are used later only for coloring

PCA is unsupervised. The call to fit receives only the scaled feature matrix, so the class target is never passed in. The labels appear only when the plot is drawn, where each already-projected point is colored by its known class.

Why Single-Feature Histograms Are Not Enough

Visualizing data with many features is hard. With two features, a single scatter plot shows everything. With a handful, a pair plot gives a partial view by showing every combination of two features side by side. The Breast Cancer dataset has 30 features, and a pair plot built from all of them would contain so many panels that no one could inspect them in detail. The problem is not only the number of plots. Even a complete set of pairwise views would miss interactions that involve three or more features at once.

A cheaper first look is to compute one histogram per feature, separated by class. Each histogram counts how many samples fall into each range of values for that feature. Overlaying the two classes shows how well that single feature distinguishes them. A feature whose two histograms mostly overlap is weak at separating the classes, while one whose histograms are largely disjoint is a stronger candidate. Histograms answer a per-feature question, though. They say nothing about how features relate to one another, and that gap is what PCA is meant to fill.

Key point

Per-feature histograms ask how one feature behaves across classes. PCA asks how the features move together, and it summarizes that joint behavior in a small number of new directions.

Scaling Before Rotation

Before PCA is applied, the features are scaled so that each one has unit variance. The source uses StandardScaler for this. The scaler is fitted to the raw data, and then the same fitted scaler transforms the data. The source treats this scaling step as necessary for PCA to work effectively, so it belongs in the workflow before any rotation is learned. Scaling comes first because the rotation is learned from the features as they enter PCA; the order of these steps is part of the workflow, not a detail to skip.

Tracing the Shape Through the Workflow

Using PCA resembles using any other preprocessing transformer in scikit-learn. You create the object, call fit to learn the principal components from the data, and then call transform to apply the rotation. By default PCA keeps every component, so it only rotates and shifts the data without reducing its width. To reduce dimensionality, you pass n_components when you construct the object. Setting it to 2 keeps the first two principal components, which is what makes a two-dimensional scatter plot possible.

python
Output (expected)
(569, 30)
(569, 2)
Notes on the code
  • X is the raw feature table with 569 samples and 30 features; y, not shown here, holds the class labels
  • The scaler is fitted once and then used to transform the data
  • pca.fit receives only the scaled matrix; the labels are not passed in
  • n_components=2 is the argument that reduces the width from 30 to 2
Raw feature table569 by 30Scaled features569 by 30pca.fitlearns rotation, shapeunchangedpca.transform569 by 2Two-column arraycomponent 1 and component 2StandardScalerX onlyrotation appliedn_components=2
How does the array shape change from 569 by 30 after scaling to 569 by 2 after transformation, and which step changes it?
Worked example

Following one dataset from table to plot

A Breast Cancer style table has 569 samples and 30 features, with a class label for each sample. Trace the array shape at each stage of the PCA visualization workflow.

  1. 1
    Start

    The raw feature table has shape 569 by 30. The labels are a separate vector with one entry per sample.

  2. 2
    Scale

    StandardScaler is fitted and then transforms the table. The shape stays 569 by 30, but each feature now has unit variance.

  3. 3
    Fit

    pca.fit receives only the scaled 569 by 30 matrix and learns the rotation from feature correlations. Nothing about the shape changes at this step.

  4. 4
    Transform

    pca.transform applies the rotation and keeps the first two components. The number of rows stays 569 because every sample still exists, while the columns drop from 30 to 2.

  5. 5
    Plot

    The first component goes on the horizontal axis and the second on the vertical axis. Each point is colored by its class label, which is the first point where y is used.

Result

The shape changes only at the transform step, from 569 by 30 to 569 by 2. The labels first affect the picture at the plotting step.

Where Class Labels Enter the Workflow

Notice the argument list of fit. It receives only the scaled feature matrix. The class target is not passed in, and that absence is the key to the unsupervised behavior. The labels are used at exactly one point: the plotting stage. There, the first principal component is placed on one axis, the second on the other, and each point is colored according to its known class. Colors are a presentation choice layered on top of a projection that was already complete before the labels were used.

Raw feature table569 by 30StandardScalerfit then transformScaled matrix Xno labelspca.fit(X)sees X onlypca.transform(X)569 by 2Scatter plotpoints colored by classClass labels yused only for coloraxescolors points
At which step does the label vector y get used, and which steps only see the scaled feature matrix X?

How PCA Chooses Its New Axes

PCA is an unsupervised method. It does not use class information when it finds the rotation. Instead, it examines the correlations among the features. The original feature axes describe one measurement each, while the principal component axes are new directions in the same space, chosen according to how the features vary together. The direction of each new axis is determined by those correlations among the scaled features, not by which points belong to which class.

Feature 1 axisone original measurementPrincipal component 1horizontal axis in plotFeature 2 axisone original measurementPrincipal component 2vertical axis in plotrotation from correlationsrotation from correlations
How do the original feature axes relate to the principal component axes, and what determines the direction of each new axis?

Reading the Two-Component Scatter Plot

Once the two components are computed, the plot places the first component on the horizontal axis and the second on the vertical axis, with each point colored by its class. In the source example the two classes separate fairly well in this two-dimensional view. That observation suggests that even a linear classifier, which would learn a straight dividing line in this space, could perform reasonably well at telling the classes apart. The word suggests is important. A projection that looks separable is evidence, not proof of how a classifier will perform.

The same plot also shows spread. In the source example the malignant points are more dispersed than the benign points, which matches what the per-feature histograms suggested earlier. This link is useful: the histograms looked at features one at a time, and the PCA plot combines them into two summary directions. When the pipeline is working correctly, the two views should tell a consistent story.

Mistakes Beginners Make

  • Common mistake

    Assuming PCA chose its axes to separate the classes

    Why it fails

    PCA is unsupervised. The fit call receives only the scaled features, so the rotation comes from feature correlations.

    Do this instead

    Treat the class separation in the plot as a result to check, and remember that the labels were only used to color points after the projection existed.

  • Common mistake

    Skipping the scaling step or applying it after PCA

    Why it fails

    The source treats scaling as necessary for PCA to work effectively, and scaling belongs before any rotation is learned.

    Do this instead

    Fit the StandardScaler, transform the data, and then pass the scaled matrix to pca.fit.

  • Common mistake

    Forgetting that the default PCA keeps every component

    Why it fails

    By default PCA only rotates and shifts the data without reducing its width, so the array still has 30 columns.

    Do this instead

    Pass n_components=2 when constructing PCA to get a two-column array for plotting.

  • Common mistake

    Expecting the number of rows to change after transform

  • Common mistake

    Reading a clean separation as proof of classifier performance

    Why it fails

    A two-dimensional projection that looks separable is evidence that a linear classifier might do well, not a guarantee of how it will perform.

    Do this instead

    Use the plot as a hypothesis to test with a real classifier and held-out evaluation.

Finding the Source of a Surprising Plot

When a PCA plot looks wrong, the workflow itself is the debugging map. Each stage has a shape and a meaning. Ask at which stage the shape or meaning first stopped matching what you expected. Check loading first, so that the matrix has the expected 569 rows and 30 feature columns. Check scaling next, so that the features are on a comparable scale and the scaler was fitted before it transformed. Check the fit call, which should receive only the scaled matrix. Check the transform output, which should have two columns. Finally, check the plotting step, where labels should only change colors, not positions.

MEDIUM

A colleague says the PCA plot shows the classes separating because PCA was told the labels. Using the workflow, explain which step you would inspect first, and what you would check at that step to decide whether the colleague's claim is right.

Hints
  • Ask what arguments are passed to pca.fit.
  • Ask at which point in the workflow the labels are first used.
  • Check whether the plotting code uses the labels for colors only.

Key Takeaways

  • PCA is unsupervised: pca.fit receives only the scaled feature matrix and finds its rotation from correlations among the features, not from class labels.
  • Class labels enter the workflow at the plotting stage, where they color points that were already projected.
  • Scaling with StandardScaler comes before PCA, and the source treats it as necessary for PCA to work effectively.
  • Setting n_components=2 reduces a 569 by 30 scaled matrix to a 569 by 2 array that can be drawn as a single scatter plot.
  • A two-component scatter plot can suggest class separability, but it hides information in the other components and is not proof of classifier performance.

Related concepts

More concepts starting with H