---
title: PCA via SVD with a sign convention
url: https://gurkanozkan.ai/learn/coding/mle-pca-via-svd-with-a-sign-convention-20/
markdown: https://gurkanozkan.ai/learn/coding/mle-pca-via-svd-with-a-sign-convention-20.md
kind: coding
difficulty: Medium
topics:
  - PCA
  - Linear algebra
  - NumPy
json: https://gurkanozkan.ai/api/learn/coding/mle-pca-via-svd-with-a-sign-convention-20.json
robots: noindex
---

# PCA via SVD with a sign convention

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

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

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Centre the data first, then SVD (or eigendecompose the covariance).
2. Take the top n_components directions as rows; explained variance ratio = squared singular values / total variance.
3. Fix the sign so the entry with largest absolute value is positive (first entry on ties).

## Reference solution

```python
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.*
