Eighteen sensors, three real signals

A bottling line at a soft drinks plant in Nashik streams eighteen channels every thirty seconds: six motor speeds, six filler temperatures, four accelerometer readings, ambient humidity, and the gap between the label and the bottle seam. Eighteen columns. Three things actually moving. The line either runs fast or slow, the filler either runs hot or cool, and the frame either shakes or it does not.

Principal component analysis is the method that recovers those underlying directions from the columns you happened to measure. It finds the axis along which your data varies most, calls that the first component, then finds the axis orthogonal to it carrying the most variance that is left, and repeats until it runs out of dimensions. You keep the first few and throw the rest away. What you get back is a smaller set of columns, uncorrelated with one another, ordered by how much of the original spread they account for.

Here is the plant’s data, built from three hidden factors so you can check whether PCA finds them.

import numpy as np, pandas as pd

rng = np.random.default_rng(42)
n = 4000
line_speed = rng.normal(0, 1, n)
fill_temp  = rng.normal(0, 1, n)
vibration  = rng.normal(0, 1, n)

cols = {}
for i in range(6):
    cols[f"motor_rpm_{i+1}"] = 1450 + 60 * line_speed + rng.normal(0, 8, n)
for i in range(6):
    cols[f"temp_c_{i+1}"] = 21 + 3.5 * fill_temp + 0.4 * line_speed + rng.normal(0, 0.6, n)
for i in range(4):
    cols[f"accel_mm_s_{i+1}"] = 3.0 + 0.6 * vibration + rng.normal(0, 0.15, n)
cols["ambient_humidity"] = 48 + rng.normal(0, 6, n)
cols["label_gap_mm"] = 0.5 + rng.normal(0, 0.12, n)

sensors = pd.DataFrame(cols)
print(sensors.shape)
# (4000, 18)
print(sensors[["motor_rpm_1", "temp_c_1", "accel_mm_s_1"]].std().round(2).to_dict())
# {'motor_rpm_1': 60.37, 'temp_c_1': 3.61, 'accel_mm_s_1': 0.62}

Look at those three standard deviations. Motor speed swings by sixty, temperature by three and a half, vibration by half a unit. That difference decides everything about what happens next.

How principal component analysis finds its axes

Mathematically, PCA is an eigen-decomposition of the covariance matrix, or equivalently a singular value decomposition of the centred data matrix. In words: the covariance matrix records how every pair of columns moves together, and its eigenvectors are the directions in which that joint movement lines up. Each eigenvector is a principal component. Its eigenvalue is the variance along it. If the vectors and matrices behind this are hazy, that chapter is the prerequisite.

Variance is measured in squared units of whatever you fed in, so PCA chases whichever column has the largest numbers. Standardise first. Always. Scaling and normalisation is not an optional refinement here, it is the difference between a meaningful answer and a reading of your unit choices.

from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(sensors)
pca = PCA(random_state=0).fit(X)

ratio = pca.explained_variance_ratio_
print(np.round(ratio[:6], 4))
# [0.3709 0.2836 0.2121 0.0571 0.0539 0.0034]
print(np.round(np.cumsum(ratio)[:6], 4))
# [0.3709 0.6546 0.8666 0.9237 0.9777 0.981 ]
print(PCA(n_components=0.95, random_state=0).fit(X).n_components_)
# 5

Three components carry 86.7 per cent of the variance, which is the right answer: three hidden factors went in. Components four and five add 5.7 and 5.4 per cent, and they are the humidity sensor and the label gap, the two columns that were pure independent noise by construction. So the popular rule of keeping 95 per cent of variance forces you to retain five components, two of which encode nothing useful. Variance is not the same thing as usefulness, and no threshold will tell the difference. Pick your cut from the scree pattern, where the ratios fall off a cliff, rather than from a round number.

Reading the loadings, and why scaling comes first

The components_ array holds the recipe for each component: one weight per original column. Reading those weights is how you work out what a component means.

load = pd.DataFrame(pca.components_[:3].T, index=sensors.columns,
                    columns=["PC1", "PC2", "PC3"]).round(2)
print(load.loc[["motor_rpm_1", "temp_c_1", "accel_mm_s_1",
                "ambient_humidity", "label_gap_mm"]])
#                    PC1   PC2   PC3
# motor_rpm_1       0.29 -0.28  0.03
# temp_c_1          0.28  0.29 -0.01
# accel_mm_s_1     -0.02  0.03  0.50
# ambient_humidity -0.00  0.00 -0.01
# label_gap_mm      0.01  0.00  0.02

raw = PCA(random_state=0).fit(sensors.values)
print(np.round(raw.explained_variance_ratio_[:3], 4))
# [0.9802 0.0034 0.0031]
print(sensors.columns[np.abs(raw.components_[0]).argmax()])
# motor_rpm_4

PC3 is vibration, cleanly: a loading of 0.50 on the accelerometers and essentially zero elsewhere. PC1 and PC2 are not a clean split of speed and temperature. Both load on motors and on temperatures, with the signs differing. That is expected, because the temperature columns were built with a small dependency on line speed, so the two factors are not orthogonal in the data and PCA can only return orthogonal axes. Components rotate information rather than isolating causes. Do not promise a plant engineer that PC2 is “the filler”.

The second half of that block is the scaling argument made concrete. Skip the scaler and the first component explains 98 per cent of the variance on its own, loading hardest on motor_rpm_4. PCA simply found the column measured in the biggest numbers. The decomposition is still correct, and still useless.

Does compression cost you accuracy

The honest test is whether a downstream model notices. Reject rate on this line runs around 27 per cent, driven by temperature and vibration together.

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

logit = -1.2 + 0.9 * fill_temp + 0.8 * vibration + 0.5 * fill_temp * vibration
reject = rng.binomial(1, 1 / (1 + np.exp(-logit)))
print(round(reject.mean(), 3))      # 0.275

for k in [None, 3, 5, 10]:
    steps = [StandardScaler()]
    if k:
        steps.append(PCA(n_components=k, random_state=0))
    steps.append(LogisticRegression(max_iter=1000, random_state=0))
    s = cross_val_score(make_pipeline(*steps), sensors, reject,
                        cv=5, scoring="roc_auc")
    print(k, round(s.mean(), 4), round(s.std(), 4))
# None 0.7841 0.0221
# 3 0.7851 0.0211
# 5 0.7852 0.021
# 10 0.7843 0.0228
Inputs Mean AUC Std across folds
All 18 sensors 0.7841 0.0221
3 components 0.7851 0.0211
5 components 0.7852 0.0210
10 components 0.7843 0.0228

Nothing happened. The spread between best and worst is 0.0011, against a fold-to-fold standard deviation of about 0.021. Anyone reporting that gap as an improvement is reading noise. What did change is the input width: three columns instead of eighteen, for the same ranking quality. That is the real case for PCA, and it is a case about cost, collinearity and storage rather than accuracy.

Note also that the model keeps the fitted PCA inside the pipeline. Fitting the decomposition on the full dataset and then splitting is a textbook route to data leakage, because the training folds would have seen the test rows’ variance structure.

Where PCA is the wrong tool

Three cases where I would not reach for it. One-hot encoded categoricals, where variance across a sparse binary block is close to meaningless. Any situation where a stakeholder has to act on individual features, since “reduce PC2 by 0.4” is not an instruction anyone can follow, and feature selection keeps the original columns. And data lying on a curved manifold, where the structure is not a rotation away and a linear method cannot find it. The scikit-learn decomposition documentation covers kernel PCA and the randomised solver for wide matrices.

Frequently Asked Questions

How many principal components should I keep?

Plot explained_variance_ratio_ and look for the elbow where the ratios drop sharply. On the sensor data that elbow sits at three. Fixed thresholds like 95 per cent are convenient but blind: here that rule retains two components built from pure noise channels.

Does PCA improve model accuracy?

Usually not. In the worked example it moved AUC by 0.0011, well inside fold noise. It reduces input width, removes collinearity and speeds up training. Treat accuracy gains as a pleasant surprise rather than the reason to use it.

Should I scale data before PCA?

Yes, unless every column is already in the same unit and on a comparable scale. Unscaled, the sensor data handed 98 per cent of its variance to one component, which only reflected motor speed being measured in the largest numbers.

Key Takeaways

  • Standardise before fitting PCA, because the method chases raw variance and will otherwise just rank your units of measurement.
  • Read explained_variance_ratio_ for the elbow rather than applying a fixed 95 per cent rule, which retained two noise-only components here.
  • Inspect components_ to interpret each axis, and accept that correlated factors will smear across several components instead of separating cleanly.
  • Expect compression, not accuracy: three components matched eighteen raw sensors to within 0.0011 AUC.
  • Fit the decomposition inside a pipeline so the transform never sees validation rows before it is scored.