LearnCoding

PCA via SVD with a sign convention

MediumPCA, Linear algebra, NumPy

Problem

Centre X, then return (components, explained_variance_ratio). components holds the top n_components principal directions as rows. Fix each component’s sign so that its entry with the largest absolute value is positive (first such entry on ties). Ratios are relative to the total variance over all directions.

Signature

def pca(X, n_components: int) -> tuple[np.ndarray, np.ndarray]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> close(pca([[1.0, 1.0],[2.0, 2.0],[3.0, 3.0]], 1), ([[0.707107, 0.707107]], [1.0]))
True

>>> close(pca([[2.0, 0.0],[-2.0, 0.0],[0.0, 1.0],[0.0, -1.0]], 2), ([[1.0, 0.0],[0.0, 1.0]], [0.8, 0.2]))
True

Solve it in your own editor; nothing on this page runs code.

Hints

Centre the data first, then SVD (or eigendecompose the covariance).

Take the top n_components directions as rows; explained variance ratio = squared singular values / total variance.

Fix the sign so the entry with largest absolute value is positive (first entry on ties).

Reference solution

import numpy as np

def pca(X, n_components):
    X = np.asarray(X, float)
    Xc = X - X.mean(axis=0)
    U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
    comps = Vt[:n_components].copy()
    for i in range(len(comps)):
        j = np.argmax(np.abs(comps[i]))
        if comps[i, j] < 0:
            comps[i] = -comps[i]
    var = S ** 2
    ratio = var[:n_components] / var.sum()
    return comps, ratio

What a strong solution covers

  • Centres the data.
  • Uses SVD (or the covariance eigen-decomposition) correctly; sorted variances.
  • Sign normalisation.
  • Discusses standardisation and choosing components by cumulative ratio.

Common mistakes

  • forgetting to centre
  • returning components as columns versus rows inconsistently.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.