Sign in

Multivariate analysis

Multivariate exploratory analysis

Ways to look at many numeric columns at once: PCA and its variance shares, multicollinearity checks (VIF), and 2-D projections with t-SNE and UMAP.

Overview

A table with twenty numeric columns is a cloud of points in twenty dimensions, which nobody can look at. Often the cloud is flatter than it seems, because columns move together. Principal component analysis (PCA) finds the directions along which the cloud is widest and tells you how much of the total spread each one holds. If two directions hold most of it, a flat picture is honest. The variance inflation factor (VIF) asks a related question: can one column be predicted from the others? If so, a linear model cannot tell them apart. When the structure is curved, t-SNE and UMAP make a 2-D picture that keeps near neighbours near, at the cost of distorting large distances. The t-SNE and UMAP here are small teaching versions for a few hundred points.

A short history

Karl Pearson described principal component analysis in 1901 and Harold Hotelling developed it independently in 1933. Variance inflation factors came from regression diagnostics in the 1960s and 1970s as a way to quantify multicollinearity. Laurens van der Maaten and Geoffrey Hinton introduced t-SNE in 2008 for visualising high dimensional data in two dimensions, and Leland McInnes, John Healy and James Melville published UMAP in 2018 as a faster method that keeps more of the large scale structure.

How it works

  1. Centre every column and, when standardize is true, scale it to unit variance so that columns in large units do not dominate.
  2. Run pca: a singular value decomposition of the prepared table gives the directions (components), the projected data (scores) and the variance along each direction.
  3. Read the explained variance ratios, and use n_components_for to find how many components reach a chosen share.
  4. Check multicollinearity with vif, one value per column, and with condition_number for the table as a whole.
  5. For a non-linear picture run tsne: it turns distances into neighbour probabilities and moves 2-D points until their probabilities match.
  6. Or run umap: it builds a weighted graph of each point's nearest neighbours and lays the graph out in 2-D.
  7. Score any projection with trustworthiness, which penalises points that appear as neighbours in the picture but were not neighbours in the data.

Watch out for

  • Distances between far-apart groups and the sizes of groups in t-SNE and UMAP pictures are not meaningful, because both methods only try to preserve near neighbours.
  • Without standardising, PCA is driven by whichever column has the largest numbers, since variance depends on units.
  • t-SNE and UMAP depend on their settings and the random seed. Structure that appears at one perplexity and vanishes at another is probably not real.
  • The t-SNE and UMAP here compute every pairwise distance and omit the speed-ups of the reference libraries, so they suit a few hundred points only.
  • A high VIF makes individual coefficients unstable but does not harm predictions, so it matters when you interpret a model, less when you only forecast.

Use cases

When to use it

PCA to see how many dimensions matter and to make a first picture, VIF before fitting or interpreting a linear model, and t-SNE or UMAP to look for cluster structure that a linear projection hides.

In industry

Genomics
Single cell RNA studies project thousands of gene expression values per cell to two dimensions with t-SNE or UMAP to reveal cell types.
Econometrics and credit
Analysts compute variance inflation factors before a regression to find predictors, such as income and spending, that carry nearly the same information.
Manufacturing
Process engineers apply PCA to hundreds of correlated sensor readings and monitor the first few components for drift.

Choosing it: what must hold

  • Several numeric columns measured on the same rows, with missing values handled first.
  • Features put on comparable scales, since PCA and distance based projections are dominated by large valued columns.
  • More rows than columns for stable VIF values, and enough rows for a projection to show structure.
  • Care in reading t-SNE and UMAP plots: distances between clusters and cluster sizes are not reliable.

When to choose something else

IfUse instead
You only need to compare variables two at a timeCorrelation
Columns are categorical or mixedAssociation analysis, or multiple correspondence analysis
You want reduced features for a model, not only a look at the dataPCA fitted as a preprocessing step, or feature selection

Math foundations

  1. Singular value decomposition

    Z=U S V⊤Z = U \, S \, V^{\top}

    The prepared table ZZ factored into three parts. The columns of VV are the principal directions, the diagonal of SS holds the singular values, and the scores are ZVZV.

  2. Explained variance ratio

    λk=sk2n−1,ρk=λk∑jλj\lambda_k = \frac{s_k^{2}}{n - 1}, \qquad \rho_k = \frac{\lambda_k}{\sum_{j} \lambda_j}

    The variance of the data along direction kk, and its share of the total. The shares add to 1, and a few large ones mean the data are nearly flat.

  3. Variance inflation factor

    VIFj=11−Rj2\mathrm{VIF}_j = \frac{1}{1 - R_j^{2}}

    Rj2R_j^{2} is how well column jj is predicted by all the other columns. A value of 1 means no overlap. Above about 5 to 10 the column is largely a combination of the others.

  4. Condition number

    κ=smax⁡smin⁡\kappa = \frac{s_{\max}}{s_{\min}}

    The ratio of the largest to the smallest singular value of the standardised table. Near 1 for unrelated columns. Above about 30 signals serious multicollinearity.

  5. t-SNE similarities in the picture

    qij=(1+∥yi−yj∥2)−1∑k≠l(1+∥yk−yl∥2)−1q_{ij} = \frac{\big(1 + \lVert y_i - y_j \rVert^{2}\big)^{-1}}{\sum_{k \ne l} \big(1 + \lVert y_k - y_l \rVert^{2}\big)^{-1}}

    How strongly points ii and jj count as neighbours in the 2-D picture. The heavy-tailed form lets points that are moderately far apart in the data sit further apart in the picture.

  6. t-SNE objective

    C=∑i≠jpij ln⁡pijqijC = \sum_{i \ne j} p_{ij} \, \ln \frac{p_{ij}}{q_{ij}}

    The Kullback-Leibler divergence between neighbour probabilities in the data (pp) and in the picture (qq). Gradient descent moves the points yy to make it small. Pairs with large pijp_{ij} dominate, so near neighbours are kept.

  7. Trustworthiness

    T(k)=1−2nk(2n−3k−1)∑i=1n∑j∈Uk(i)(r(i,j)−k)T(k) = 1 - \frac{2}{n k (2n - 3k - 1)} \sum_{i=1}^{n} \sum_{j \in U_k(i)} \big(r(i, j) - k\big)

    For each point, Uk(i)U_k(i) holds its false neighbours: among the kk nearest in the picture but not in the data. Each is penalised by how far down the original ranking it was. A score of 1 means no false neighbours.

Symbols

ZZ
the centred (and standardised) table, n rows by d columns
U,S,VU, S, V
the three factors of the decomposition
sks_k
the k-th singular value
λk,ρk\lambda_k, \rho_k
variance along the k-th direction and its share of the total
nn
number of rows (observations)
Rj2R_j^{2}
share of column j's variance explained by regressing it on the other columns
κ\kappa
the condition number
yiy_i
position of point i in the 2-D picture
pij,qijp_{ij}, q_{ij}
neighbour probability of points i and j in the data and in the picture
kk
neighbourhood size used by the trust score
r(i,j)r(i, j)
rank of point j among the neighbours of point i in the original data
Uk(i)U_k(i)
points among the k nearest to i in the picture but not in the data

Worked by hand

A table with n=11n = 11 rows and three columns has singular values 6, 4 and 2 after preparation. Separately, one column is predicted by the others with R2=0.9R^{2} = 0.9.

λ=3610,  1610,  410=3.6,  1.6,  0.4\lambda = \frac{36}{10}, \; \frac{16}{10}, \; \frac{4}{10} = 3.6, \; 1.6, \; 0.4
ρ=3.65.6,  1.65.6,  0.45.6=0.643,  0.286,  0.071\rho = \frac{3.6}{5.6}, \; \frac{1.6}{5.6}, \; \frac{0.4}{5.6} = 0.643, \; 0.286, \; 0.071
ρ1+ρ2=0.929≥0.9\rho_1 + \rho_2 = 0.929 \ge 0.9
κ=62=3,VIF=11−0.9=10\kappa = \frac{6}{2} = 3, \qquad \mathrm{VIF} = \frac{1}{1 - 0.9} = 10

Two components hold 92.9 percent of the variance, so n_components_for with a threshold of 0.9 returns 2. A VIF of 10 means the coefficient variance of that column is ten times what it would be with unrelated columns.

Visual example

Loading the example.

Try this

  • Raise the copy slider toward 0.99: the third component empties, every VIF climbs and the condition number takes off.
  • Set the copy slider to 0 and the link between x1 and x2 to 0: the three shares come close to a third each.
  • Choose each column in turn and compare its VIF with the direction of its line in the picture.

Code sample

import numpy as np
from impl import MultivariateAnalysis
from config import MultivariateAnalysisConfig

rng = np.random.default_rng(0)
centres = rng.normal(0, 6, size=(3, 10))
x = np.vstack([c + rng.normal(size=(30, 10)) for c in centres])     # 90 points, 10 columns, 3 groups

m = MultivariateAnalysis(MultivariateAnalysisConfig(n_components=2, perplexity=15.0))
p = m.pca(x)
print(p["explained_variance_ratio"][:3], m.n_components_for(x, 0.9))
print(MultivariateAnalysis.vif(x))              # well above 1: the group centres make the columns move together
y_tsne = m.tsne(x)                              # shape (90, 2)
y_umap = m.umap(x)                              # shape (90, 2)
print(m.trustworthiness(x, y_tsne), m.trustworthiness(x, y_umap), m.trustworthiness(x, p["scores"]))
Read the implementation (299 lines)
"""Multivariate analysis: PCA, multicollinearity checks, and small t-SNE and UMAP projections.

NumPy only. PCA and the collinearity checks (VIF, condition number) are exact linear algebra and scale to large
tables. The t-SNE and UMAP here are small, exact-neighbour versions for a few hundred points: every pairwise
distance is computed and the optimisation is a plain NumPy loop, with none of the tree or sampling tricks the
library versions use for large data. `trustworthiness` measures how well any projection keeps neighbourhoods.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import MultivariateAnalysisConfig
except ImportError:  # run from the template's own folder
    from config import MultivariateAnalysisConfig


def _squared_distances(x: np.ndarray) -> np.ndarray:
    """Pairwise squared Euclidean distances. x: (n, d). Returns (n, n) with an exact zero diagonal."""
    sq = (x * x).sum(axis=1)
    d = np.maximum(sq[:, None] + sq[None, :] - 2.0 * x @ x.T, 0.0)
    np.fill_diagonal(d, 0.0)
    return d


def fit_umap_curve(min_dist: float, spread: float = 1.0) -> tuple[float, float]:
    """Fit (a, b) so that 1 / (1 + a * x^(2b)) matches UMAP's target curve for the given min_dist.

    The target is 1 for x <= min_dist and exp(-(x - min_dist) / spread) beyond. Least squares over a grid that
    is refined around its best point four times.
    """
    x = np.linspace(0.0, 3.0 * spread, 300)[1:]
    target = np.where(x <= min_dist, 1.0, np.exp(-(x - min_dist) / spread))
    a_lo, a_hi, b_lo, b_hi = 0.01, 10.0, 0.3, 3.0
    for _ in range(4):
        a_grid = np.linspace(a_lo, a_hi, 60)
        b_grid = np.linspace(b_lo, b_hi, 60)
        curve = 1.0 / (1.0 + a_grid[:, None, None] * x[None, None, :] ** (2.0 * b_grid[None, :, None]))
        error = ((curve - target) ** 2).sum(axis=2)
        i, j = np.unravel_index(int(np.argmin(error)), error.shape)
        a_step, b_step = a_grid[1] - a_grid[0], b_grid[1] - b_grid[0]
        a_lo, a_hi = max(a_grid[i] - 2 * a_step, 1e-4), a_grid[i] + 2 * a_step
        b_lo, b_hi = max(b_grid[j] - 2 * b_step, 1e-4), b_grid[j] + 2 * b_step
    return float(a_grid[i]), float(b_grid[j])


class MultivariateAnalysis:
    """Linear and non-linear views of a table x of shape (n, d): n observations of d numeric variables."""

    def __init__(self, config: MultivariateAnalysisConfig | None = None) -> None:
        self.config = config or MultivariateAnalysisConfig()
        self.kl_history_: list[float] = []  # KL divergence of the last t-SNE run, one value per step

    def _prepare(self, x) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Centre (and scale when config.standardize). Returns (prepared x, mean (d,), scale (d,))."""
        x = np.asarray(x, dtype=float)
        if x.ndim != 2 or x.shape[0] < 2:
            raise ValueError(f"x must be 2-D with at least two rows, got shape {x.shape}")
        if not np.isfinite(x).all():
            raise ValueError("x holds NaN or infinite values; drop or fill them first")
        mean = x.mean(axis=0)
        scale = np.ones(x.shape[1])
        if self.config.standardize:
            scale = x.std(axis=0, ddof=1)
            scale[scale == 0] = 1.0  # a constant column stays at zero instead of dividing by zero
        return (x - mean) / scale, mean, scale

    # ---- PCA -----------------------------------------------------------------------------------------------
    def pca(self, x) -> dict:
        """Principal component analysis by singular value decomposition.

        x: (n, d). Returns a dict with
          components (k, d): unit-length directions, rows ordered by variance explained, k = config.n_components;
          scores (n, k): the data projected on those directions;
          explained_variance (m,): variance along every direction, m = min(n - 1, d) at most;
          explained_variance_ratio (m,): the same as shares of the total (they sum to 1);
          mean (d,), scale (d,): what was subtracted and divided out before the decomposition.
        """
        z, mean, scale = self._prepare(x)
        _, singular, vt = np.linalg.svd(z, full_matrices=False)
        # fix the sign of each direction (largest entry positive) so results are reproducible
        signs = np.sign(vt[np.arange(vt.shape[0]), np.abs(vt).argmax(axis=1)])
        signs[signs == 0] = 1.0
        vt = vt * signs[:, None]
        variance = singular**2 / (z.shape[0] - 1)
        total = variance.sum()
        k = min(self.config.n_components, vt.shape[0])
        return {
            "components": vt[:k],
            "scores": z @ vt[:k].T,
            "explained_variance": variance,
            "explained_variance_ratio": variance / total if total > 0 else np.zeros_like(variance),
            "mean": mean,
            "scale": scale,
        }

    def n_components_for(self, x, threshold: float = 0.95) -> int:
        """Smallest number of principal components whose variance shares add up to at least `threshold`."""
        if not 0.0 < threshold <= 1.0:
            raise ValueError(f"threshold must be in (0, 1], got {threshold}")
        cumulative = np.cumsum(self.pca(x)["explained_variance_ratio"])
        return int(np.searchsorted(cumulative, threshold - 1e-12) + 1)

    def reconstruction_error(self, x, k: int) -> float:
        """Mean squared error of rebuilding the prepared data from its first k principal components."""
        z, _, _ = self._prepare(x)
        _, _, vt = np.linalg.svd(z, full_matrices=False)
        rebuilt = z @ vt[:k].T @ vt[:k]
        return float(np.mean((z - rebuilt) ** 2))

    # ---- multicollinearity ---------------------------------------------------------------------------------
    @staticmethod
    def vif(x) -> np.ndarray:
        """Variance inflation factor of every column. x: (n, d). Returns (d,).

        VIF_j = 1 / (1 - R_j^2), where R_j^2 comes from regressing column j on all the others; it equals the
        j-th diagonal entry of the inverse correlation matrix. 1 means no collinearity; above about 5 to 10 the
        column is largely a combination of the others; inf means it is exactly one.
        """
        x = np.asarray(x, dtype=float)
        if x.ndim != 2 or x.shape[0] <= x.shape[1]:
            raise ValueError("x must be 2-D with more rows than columns")
        if (x.std(axis=0) == 0).any():
            raise ValueError("a constant column has no VIF; remove it first")
        corr = np.corrcoef(x, rowvar=False).reshape(x.shape[1], x.shape[1])
        if np.linalg.cond(corr) > 1e12:
            return np.full(x.shape[1], np.inf)
        return np.maximum(np.diag(np.linalg.inv(corr)), 1.0)

    @staticmethod
    def condition_number(x) -> float:
        """Ratio of the largest to the smallest singular value of the standardised table.

        Near 1 for uncorrelated columns; above about 30 signals serious multicollinearity.
        """
        x = np.asarray(x, dtype=float)
        std = x.std(axis=0, ddof=1)
        if (std == 0).any():
            raise ValueError("a constant column makes the condition number meaningless; remove it first")
        singular = np.linalg.svd((x - x.mean(axis=0)) / std, compute_uv=False)
        return float(singular[0] / singular[-1]) if singular[-1] > 0 else math.inf

    # ---- t-SNE ---------------------------------------------------------------------------------------------
    @staticmethod
    def _tsne_affinities(d2: np.ndarray, perplexity: float) -> np.ndarray:
        """Symmetric input affinities P (n, n), summing to 1, with each row tuned to the given perplexity."""
        n = d2.shape[0]
        target = math.log(perplexity)
        p = np.zeros((n, n))
        for i in range(n):
            others = np.arange(n) != i
            d = d2[i, others] - d2[i, others].min()
            beta, lo, hi = 1.0, 0.0, math.inf
            for _ in range(64):  # binary search on the precision beta = 1 / (2 sigma^2)
                row = np.exp(-d * beta)
                row /= row.sum()
                entropy = -float(np.sum(row[row > 0] * np.log(row[row > 0])))
                if abs(entropy - target) < 1e-5:
                    break
                if entropy > target:
                    lo, beta = beta, beta * 2.0 if hi == math.inf else 0.5 * (beta + hi)
                else:
                    hi, beta = beta, 0.5 * (beta + lo)
            p[i, others] = row
        return np.maximum((p + p.T) / (2.0 * n), 1e-12)

    def tsne(self, x) -> np.ndarray:
        """t-distributed stochastic neighbour embedding (exact gradient, O(n^2) per step).

        x: (n, d) with n up to a few hundred. Returns the embedding, shape (n, config.n_components).
        Gradient descent with momentum and per-coordinate gains as in the original paper; the input affinities
        are multiplied by 4 for the first third of the steps (early exaggeration). The KL divergence after
        every step is kept in self.kl_history_.
        """
        z, _, _ = self._prepare(x)
        n = z.shape[0]
        if self.config.perplexity >= n - 1:
            raise ValueError(f"perplexity ({self.config.perplexity}) must be below n - 1 ({n - 1})")
        rng = np.random.default_rng(self.config.seed)
        p = self._tsne_affinities(_squared_distances(z), self.config.perplexity)
        y = rng.normal(0.0, 1e-4, size=(n, self.config.n_components))
        velocity = np.zeros_like(y)
        gains = np.ones_like(y)
        exaggerate_until = self.config.n_iter // 3
        self.kl_history_ = []
        for step in range(self.config.n_iter):
            weight = 1.0 / (1.0 + _squared_distances(y))  # Student t kernel
            np.fill_diagonal(weight, 0.0)
            q = np.maximum(weight / weight.sum(), 1e-12)
            p_used = p * 4.0 if step < exaggerate_until else p
            pull = (p_used - q) * weight
            gradient = 4.0 * (np.diag(pull.sum(axis=1)) - pull) @ y
            same_direction = (gradient > 0) == (velocity > 0)
            gains = np.maximum(np.where(same_direction, gains * 0.8, gains + 0.2), 0.01)
            momentum = 0.5 if step < exaggerate_until else 0.8
            velocity = momentum * velocity - self.config.learning_rate * gains * gradient
            y = y + velocity
            y -= y.mean(axis=0)
            self.kl_history_.append(float(np.sum(p * np.log(p / q))))
        return y

    # ---- UMAP ----------------------------------------------------------------------------------------------
    def _umap_graph(self, distances: np.ndarray) -> np.ndarray:
        """Fuzzy neighbour graph: symmetric weights in [0, 1], shape (n, n), from exact k nearest neighbours."""
        n = distances.shape[0]
        k = self.config.n_neighbors
        target = math.log2(k)
        graph = np.zeros((n, n))
        for i in range(n):
            neighbours = np.argsort(distances[i])[1:k + 1]  # position 0 is the point itself
            d = distances[i, neighbours]
            rho = d[d > 0].min() if (d > 0).any() else 0.0  # distance to the nearest neighbour
            lo, hi, sigma = 0.0, math.inf, 1.0
            for _ in range(64):  # binary search: the weights of point i must sum to log2(k)
                total = float(np.exp(-np.maximum(d - rho, 0.0) / sigma).sum())
                if abs(total - target) < 1e-5:
                    break
                if total > target:
                    hi, sigma = sigma, 0.5 * (lo + sigma)
                else:
                    lo, sigma = sigma, sigma * 2.0 if hi == math.inf else 0.5 * (sigma + hi)
            graph[i, neighbours] = np.exp(-np.maximum(d - rho, 0.0) / sigma)
        return graph + graph.T - graph * graph.T  # fuzzy union of the two directed views

    def umap(self, x) -> np.ndarray:
        """Uniform manifold approximation and projection, small exact version.

        x: (n, d) with n up to a few hundred. Returns the embedding, shape (n, config.n_components).
        Steps: exact k-nearest-neighbour graph with UMAP's smooth local scaling and fuzzy union; start from the
        PCA projection; then config.n_iter epochs in which every graph edge (sampled in proportion to its
        weight) pulls its ends together and five random points per edge are pushed away, with UMAP's
        attraction and repulsion gradients. The moves of one epoch are averaged per point and applied
        together, where the reference implementation applies them edge by edge.
        """
        z, _, _ = self._prepare(x)
        n = z.shape[0]
        if self.config.n_neighbors >= n:
            raise ValueError(f"n_neighbors ({self.config.n_neighbors}) must be below n ({n})")
        rng = np.random.default_rng(self.config.seed)
        graph = self._umap_graph(np.sqrt(_squared_distances(z)))
        head, tail = np.nonzero(graph)
        weight = graph[head, tail] / graph.max()
        a, b = fit_umap_curve(self.config.min_dist)
        dims = self.config.n_components
        _, _, vt = np.linalg.svd(z, full_matrices=False)
        y = z @ vt[:dims].T
        if y.shape[1] < dims:  # fewer input columns than output dimensions
            y = np.column_stack([y, rng.normal(0.0, 1e-4, size=(n, dims - y.shape[1]))])
        y = 10.0 * y / max(np.abs(y).max(), 1e-12)
        n_negative = 5
        for epoch in range(self.config.n_iter):
            alpha = 1.0 - epoch / self.config.n_iter
            active = rng.random(head.size) < weight
            h, t = head[active], tail[active]
            if h.size == 0:
                continue
            move = np.zeros_like(y)
            count = np.zeros(n)
            diff = y[h] - y[t]
            d2 = np.maximum((diff * diff).sum(axis=1), 1e-12)
            attract = -2.0 * a * b * d2 ** (b - 1.0) / (1.0 + a * d2**b)
            np.add.at(move, h, np.clip(attract[:, None] * diff, -4.0, 4.0))
            np.add.at(count, h, 1.0)
            other = rng.integers(0, n, size=(h.size, n_negative))
            diff = y[h][:, None, :] - y[other]
            d2 = (diff * diff).sum(axis=2)
            repel = 2.0 * b / ((0.001 + d2) * (1.0 + a * d2**b))
            repel[other == h[:, None]] = 0.0  # a point does not repel itself
            np.add.at(move, h, np.clip(repel[:, :, None] * diff, -4.0, 4.0).sum(axis=1))
            y = y + alpha * move / np.maximum(count, 1.0)[:, None]
        return y - y.mean(axis=0)

    # ---- checking a projection -----------------------------------------------------------------------------
    def trustworthiness(self, x, embedding, k: int | None = None) -> float:
        """How far the k nearest neighbours in a projection are also near in the original data, from 0 to 1.

        x: (n, d) original data. embedding: (n, m) its projection. k: neighbourhood size (default
        config.n_neighbors); needs k < n / 2. A value of 1 means no point has a neighbour in the projection that
        was not among its k nearest originally; values drop as the projection invents false neighbours.
        """
        z, _, _ = self._prepare(x)
        e = np.asarray(embedding, dtype=float)
        n = z.shape[0]
        k = self.config.n_neighbors if k is None else k
        if e.shape[0] != n:
            raise ValueError("x and embedding must have the same number of rows")
        if not 1 <= k < n / 2:
            raise ValueError(f"k must satisfy 1 <= k < n / 2, got k = {k} with n = {n}")
        original = _squared_distances(z)
        np.fill_diagonal(original, -1.0)  # each point ranks first for itself
        rank = np.argsort(np.argsort(original, axis=1), axis=1)  # rank[i, j]: j is the rank-th nearest to i
        projected = _squared_distances(e)
        np.fill_diagonal(projected, -1.0)
        neighbours = np.argsort(projected, axis=1)[:, 1:k + 1]
        ranks = np.take_along_axis(rank, neighbours, axis=1)
        penalty = float(np.maximum(ranks - k, 0).sum())
        return 1.0 - 2.0 / (n * k * (2.0 * n - 3.0 * k - 1.0)) * penalty
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
12, run with python3 -m unittest -v

Practice

Build 90 points in 10 columns from three group centres, as in the template's README. Call pca and n_components_for(x, 0.9), then MultivariateAnalysis.vif(x). Compute tsne and umap projections and compare trustworthiness for both and for the PCA scores. Change perplexity from 15 to 5 and to 40 and see whether the three groups stay apart.

Check on learning

  1. One column is in metres with values in the thousands, another is a ratio between 0 and 1. What does PCA find without standardising, and is that a property of the data?
    A way to think about it

    Compare the two variances. Then change metres to kilometres and ask whether the first component should change.

  2. In a t-SNE picture cluster A is twice as wide as cluster B and far from it. Which of these facts can you trust?
    A way to think about it

    The objective rewards keeping near neighbours near. Ask what it says about the spread within a cluster or the gap between clusters.

  3. Two features have a VIF of 50. The model predicts well, but the two coefficients have opposite signs and huge sizes. What is going on, and what are your options?
    A way to think about it

    If the columns are nearly the same, only their sum is pinned down by the data. Think about dropping one, combining them, or shrinking coefficients.

  4. The first two principal components hold 35 percent of the variance. What does a 2-D PCA scatter plot of this data hide, and how could you check?
    A way to think about it

    Most of the spread lies in directions you are not seeing. Look at reconstruction_error and at the trust score of the projection.

  5. A projection has a trustworthiness of 0.99 for k=5k = 5 and 0.80 for k=40k = 40. What does that tell you about what the picture preserves?
    A way to think about it

    Small kk tests the very nearest neighbours, large kk tests wider neighbourhoods. Relate that to local and global structure.