MATH 4310 · Computational Bioinformatics

PCA in Practice

Lesson 16 · 2027-03-22 · Week 11

Core question

Does a separation in a PCA plot reflect biology or how the samples were measured?

Which matrix describes the experiment?

Suppose treated samples lie on one side of a PCA plot and controls on the other. That could reflect a shared RNA response to treatment. It could also reflect the experiment: one set of samples may have more sequenced reads, or may have been processed differently. PCA finds the largest variation in the numbers it receives; deciding what produced that variation requires the count table and the sample records.1

In an RNA-sequencing experiment, RNA is sampled, copied into DNA, sequenced in fragments, and the reads are matched to genes. The count \(C_{ij}\) records reads assigned to gene \(j\) in sample \(i\). We retain samples as rows and genes as columns. Lesson 15 held a transformed matrix fixed to study the PCA optimization; here we ask which representation makes the samples comparable and how to interpret the resulting coordinates.

The aim is to learn whether treated samples share a coordinated expression pattern that controls lack. To judge where a separation comes from, we keep a second table of metadata, records describing each sample: its identity, its condition, and its processing batch, a group of samples handled together on the same day or instrument. A shared processing difference can shift many genes at once and create large variance that has nothing to do with the treatment, so these records let us relate a PCA direction to a possible biological or technical cause.1

Write \(C\in\mathbb Z_{\geq0}^{n\times p}\) for counts from \(n\geq2\) samples and \(p\) genes. For a synthetic example, keep metadata separate from the numeric counts:

sample condition sequencing run
s1 control 1
s2 control 2
s3 treated 1
s4 treated 2
sample gene 1 gene 2 gene 3 total assigned reads
s1 10 20 70 100
s2 20 40 140 200
s3 20 20 60 100
s4 40 40 120 200

Within each condition, run 2 has exactly twice as many assigned reads in this synthetic example. A PCA plot can separate these samples sharply even though that difference reflects sequencing depth. To investigate treatment-associated expression, we need a representation that compares gene abundances at comparable depths.

Sequencing depth, relative abundance, and logarithms

Let \(L_i=\sum_j C_{ij}>0\) be the total assigned count for sample \(i\). If a sampled read belongs to gene \(j\) with probability \(\rho_{ij}\), where \(\sum_j\rho_{ij}=1\), its mean count at fixed depth is \[ \mathbb E[C_{ij}\mid L_i]=L_i\rho_{ij}. \] Here \(\rho_{ij}\) is the fraction of sampled reads expected to belong to that gene. Doubling the number of reads doubles the expected count without changing that fraction.1 A simple normalization is counts per million: \[ R_{ij}=10^6\frac{C_{ij}}{L_i}. \] Each row sums to one million. In the table, s1 and s2 both become \((100000,200000,700000)\), while s3 and s4 become \((200000,200000,600000)\). The representation removes their depth difference and keeps their different composition.

This representation measures composition: the share of reads assigned to each gene. If every RNA abundance doubles, those shares remain the same. If one highly abundant gene increases, other shares can decrease even when their absolute abundances are unchanged. Interpreting relative changes as absolute changes therefore requires additional information. Other normalization methods use assumptions about a stable reference set or the majority of genes.1 Compute row totals before filtering genes, so removing a column does not silently redefine the reference total.

Counts also span a wide range. On the original scale, changing a value from 1000 to 2000 contributes a much larger squared difference than changing it from 10 to 20. For this illustration, choose \[ X_{ij}=\log_2(1+R_{ij}). \] For large \(R_{ij}\), doubling it adds approximately one to \(X_{ij}\) and halving it subtracts one, so multiplicative differences become approximately additive and a rise and a fall by the same factor become symmetric about zero change. A twofold change in an abundant gene and a twofold change in a less abundant gene then make comparable contributions. The offset of one count per million makes zeros finite; near zero, it also strongly affects the difference being measured.

Algorithm Compare PCA of raw counts and log-CPM

Input: a matrix \(C\) of raw assigned-read counts, where \(C_{ij}\) is the count for sample \(i\) and gene \(j\). The \(n\ge 2\) rows have positive totals and distinct sample IDs \(s_i\), with one metadata record per ID. The \(p\) columns are genes. Let \(J\subseteq\{1,\ldots,p\}\) be the nonempty set of gene columns to retain in their original order. Here \(J=\{1,2,3\}\).

Output: sample scores \(T\), gene loadings \(V\), and component variances for both representations, with the metadata aligned to the score rows.

  1. For each sample row \(i=1,\ldots,n\):
    1. \(m_i\leftarrow\) the metadata record with sample ID \(s_i\). Pair \(m_i\) with score row \(i\) in both fits. // match IDs
    2. \(L_i\leftarrow\sum_{j=1}^{p}C_{ij}\), using all genes before filtering. // library size before filtering
  2. For each \(i=1,\ldots,n\) and each retained gene \(j\in J\):
    1. \(Y^{\mathrm{raw}}_{ij}\leftarrow C_{ij}\) and \(R_{ij}\leftarrow 10^6 C_{ij}/L_i\). // convert counts to CPM
    2. \(X_{ij}\leftarrow\log_2(1+R_{ij})\). // add one, then take log
  3. For each matrix \(Y\) in \((Y^{\mathrm{raw}},X)\): // fit each representation
    1. For each \(j\in J\), set \(\bar Y_j\leftarrow\frac1n\sum_{i=1}^{n}Y_{ij}\). // average across samples
    2. For each \(i=1,\ldots,n\) and \(j\in J\), set \(Z_{ij}\leftarrow Y_{ij}-\bar Y_j\). // center each gene
    3. From the reduced SVD of \(Z\), take the singular values \(d_k\) and loading matrix \(V\). // get loadings
    4. For each loading column \(v_k\), find its first entry of largest magnitude. If that entry is negative, \(v_k\leftarrow -v_k\). // set loading signs
    5. \(T\leftarrow ZV\) and \(\lambda_k\leftarrow d_k^2/(n-1)\) for each singular value \(d_k\). // scores and variances
    6. Store \(T\), \(V\), and the \(\lambda_k\) as the fit for \(Y\).
  4. Return both fits and the aligned metadata rows \((m_1,\ldots,m_n)\).
Python Compare PCA of counts and log-CPM
import numpy as np

def pca_summary(X: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Return scores, loadings, and component variances for centered columns."""
    Z = X - X.mean(axis=0)
    _, singular_values, vt = np.linalg.svd(Z, full_matrices=False)
    loadings = vt.T
    for k in range(loadings.shape[1]):
        largest = np.argmax(np.abs(loadings[:, k]))
        if loadings[largest, k] < 0:
            loadings[:, k] *= -1
    scores = Z @ loadings
    variances = singular_values ** 2 / (X.shape[0] - 1)
    return scores, loadings, variances


sample_ids = ["s1", "s2", "s3", "s4"]
metadata_by_id = {
    "s1": {"condition": "control", "sequencing_run": 1},
    "s2": {"condition": "control", "sequencing_run": 2},
    "s3": {"condition": "treated", "sequencing_run": 1},
    "s4": {"condition": "treated", "sequencing_run": 2},
}
aligned_metadata = [metadata_by_id[sample_id] for sample_id in sample_ids]
counts = np.array([
    [10, 20, 70],
    [20, 40, 140],
    [20, 20, 60],
    [40, 40, 120],
], dtype=float)
totals = counts.sum(axis=1)
# Select columns only after computing the full sample totals.
gene_indices = [0, 1, 2]
retained_counts = counts[:, gene_indices]
relative_counts = 1_000_000 * retained_counts / totals[:, None]
X = np.log2(1 + relative_counts)
print("log-CPM values:\n", np.round(X, 3))
raw_scores, _, raw_variances = pca_summary(retained_counts)
normalized_scores, _, normalized_variances = pca_summary(X)
print("raw explained fractions:", np.round(raw_variances / raw_variances.sum(), 3))
print("log-CPM fractions:",
      np.round(normalized_variances / normalized_variances.sum(), 3))

Raw PC1 explains 93.3% of the spread and separates the two sequencing depths. The log-CPM rows for s1 and s2 both round to \((16.610,17.610,19.417)\), and the rows for s3 and s4 both round to \((17.610,17.610,19.195)\). Log-CPM PCA has one nonzero component, accounting for 100% of its spread. That remaining contrast is a difference in composition between the conditions. The exact coincidences arise from the table’s noiseless ratios; real replicates vary. These PCA percentages describe different input matrices, so a larger percentage does not validate a representation.

Left panel shows four samples in two columns: s1 and s3 at low raw PC1, s2 and s4 at high raw PC1. Right panel shows coincident controls at negative PC1 and coincident treated samples at positive PC1, with PC2 zero.

Figure 16.1. The same count table summarized by PCA before and after depth normalization and a logarithm. Blue circles denote controls and orange triangles treated samples. Raw PC1 separates sequencing depths; the normalized representation retains the condition-associated composition difference.

Scaling changes the optimization problem

For \(n\geq2\) samples and \(p\) retained genes, recall the centered matrix \(Z_{ij}=X_{ij}-\bar x_j\) and covariance \(S=Z^\top Z/(n-1)\). Unscaled PCA chooses a unit loading \(v\in\mathbb R^p\) to maximize \[ \frac{\|Zv\|^2}{n-1}=v^\top Sv =\sum_{j=1}^p S_{jj}\,v_j^2+\sum_{j\ne k}S_{jk}\,v_jv_k . \] The first sum weights each gene’s variance by its squared loading. If gene \(j\) is recorded in units \(c\) times larger, its column of \(Z\) is multiplied by \(c\), so \(S_{jj}\) grows by \(c^2\) and each covariance \(S_{jk}\) by \(c\). The objective then gains most by loading on that gene, although no sample’s standing on any gene has changed.

For each gene with nonzero sample standard deviation, \[ \sigma_j=\sqrt{\frac{1}{n-1}\sum_i Z_{ij}^2}, \qquad W_{ij}=\frac{Z_{ij}}{\sigma_j}. \] Each column of \(W\) has variance one. Constant genes have \(\sigma_j=0\) and must be omitted before division. Standardization makes each retained gene contribute equal marginal variance; it does not make their measurements equally reliable.

The change can be read directly from a sample distance. After standardization, \[ \|w_i-w_k\|^2=\sum_j\frac{(X_{ij}-X_{kj})^2}{\sigma_j^2}. \] Each difference is measured in units of that gene’s standard deviation. A change of one standard deviation contributes one to the squared distance, whatever the original units. Thus scaling changes the weighting of gene differences and the directions PCA prefers. It can expose a coordinated pattern or amplify unreliable low-count measurements. Filtering should have a stated measurement-based purpose, such as excluding genes with too little coverage; choosing genes because they already separate the plotted conditions makes that separation partly a selection artifact.

The four-sample matrix of Lesson 15 shows how much this choice can change the answer.

Example 16.1 Rescaling one gene of the four-sample matrix

Use the same supplied transformed values: \[ X=\begin{pmatrix}4&7&5\\5&6&3\\7&10&3\\8&9&5\end{pmatrix}, \qquad Z=\begin{pmatrix}-2&-1&1\\-1&-2&-1\\1&2&-1\\2&1&1\end{pmatrix}. \] Its covariance is \[ S=\frac13\begin{pmatrix}10&8&0\\8&10&0\\0&0&4\end{pmatrix}. \] The first direction combines genes 1 and 2 equally, with variance 6 and explained fraction \(3/4\). Suppose we multiply gene 3 by ten. Its variance becomes \(400/3\); it now supplies PC1 and explains \(400/(400+20)=20/21\) of the total. We have changed no samples or correlations, but changed which variation the objective favors.

After standardizing all three genes, the covariance is instead \[ S_W=\begin{pmatrix}1&0.8&0\\0.8&1&0\\0&0&1\end{pmatrix}. \] Its eigenvalues are \(1.8,1,0.2\), so PC1 again combines genes 1 and 2 but now explains \(1.8/3=60\%\). Multiplying gene 3 by ten before standardizing gives the same \(W\), because its standard deviation also increases tenfold. Standardization removes that change of units, at the cost of replacing the original variance weighting.

Python Check explained fractions under three scalings
import numpy as np

example_X = np.array([[4, 7, 5], [5, 6, 3], [7, 10, 3], [8, 9, 5]], dtype=float)
example_Z = example_X - example_X.mean(axis=0)
rescaled_Z = example_Z * np.array([1, 1, 10])
W = example_Z / example_Z.std(axis=0, ddof=1)
rescaled_W = rescaled_Z / rescaled_Z.std(axis=0, ddof=1)
assert np.allclose(W, rescaled_W)
assert np.allclose(W.T @ W / 3, [[1, 0.8, 0], [0.8, 1, 0], [0, 0, 1]])
for representation in (example_Z, rescaled_Z, W):
    squared_singular = np.linalg.svd(representation, compute_uv=False) ** 2
    print(np.round(squared_singular / squared_singular.sum(), 3))

The explained fractions are \((0.750,0.167,0.083)\) in the original units, \((0.952,0.043,0.005)\) after multiplying gene 3 by ten, and \((0.600,0.333,0.067)\) after standardization. Figure 16.2 draws the change in the plane of genes 1 and 3, where the two genes are uncorrelated. In the original units gene 1 has the larger variance (\(10/3\) against \(4/3\)) and the best-fitting line lies along it; after gene 3 is multiplied by ten, its variance \(400/3\) dominates and the line swings a full right angle. A gene’s large contribution can therefore reflect the chosen units. Whether to preserve its original variance or give it equal weight is a scientific choice about which differences to summarize.

Left panel: points at minus2,1; minus1,minus1; 1,minus1; 2,1 projected onto the horizontal axis. Right panel: the same points with the vertical coordinate scaled to plus or minus 10, projected onto the vertical axis.

Figure 16.2. Centered genes 1 and 3 of the four-sample matrix, each projected onto its own first principal direction (red crosses), before and after gene 3 is multiplied by ten. The same four samples (in B, s1 and s4 at the top) give a horizontal PC1 in the original units and a vertical PC1 after rescaling: the units decide which gene PCA follows.

A dominant component can be a processing batch

To isolate a second issue, use a new synthetic matrix on an already transformed scale. Each batch includes one control and one treated sample:

sample batch sign \(b_i\) condition sign \(\tau_i\) gene 1 gene 2 gene 3
s1 −1 −1 (control) 7 7 9
s2 −1 +1 (treated) 7 7 11
s3 +1 −1 (control) 13 13 9
s4 +1 +1 (treated) 13 13 11

We planted an additive model \[ x_i=\mu+b_i a+\tau_i c, \qquad \mu=(10,10,10),\quad a=(3,3,0),\quad c=(0,0,1). \] Here \(a\) is the per-gene batch shift and \(c\) the per-gene condition shift; \(x_i\) and these profiles are row vectors. They are orthogonal, \(ac^\top=0\). The sample contrasts also satisfy \(\sum_i b_i=\sum_i \tau_i=0\) and \(\sum_i b_i\tau_i=0\). Thus centering gives \(z_i=b_i a+\tau_i c\), and the two effects do not mix in the cross-product matrix: \[ Z^\top Z=4a^\top a+4c^\top c =\begin{pmatrix}36&36&0\\36&36&0\\0&0&4\end{pmatrix}. \] The batch direction \((1,1,0)/\sqrt2\) has variance \(72/3=24\). The condition direction \((0,0,1)\) has variance \(4/3\). Consequently PC1 explains \(72/76=18/19\approx94.7\%\) and separates batches, while PC2 explains \(1/19\approx5.3\%\) and separates conditions. A rule retaining 90% of variance with one component would discard the planted biological contrast.

Calling pca_summary from the count example gives PC1 scores of \(-3\sqrt{2}\) for s1 and s2 and \(3\sqrt{2}\) for s3 and s4. PC2 scores are \(-1\) for controls and \(+1\) for treated samples. The function’s sign convention determines which side of each plot these groups occupy.

Python Compute scores for the planted batch and condition effects
batch_X = np.array([[7, 7, 9], [7, 7, 11], [13, 13, 9], [13, 13, 11]], dtype=float)
batch = np.array([-1, -1, 1, 1])
condition = np.array([-1, 1, -1, 1])
scores_before, loadings_before, variance_before = pca_summary(batch_X)
assert np.allclose(variance_before, [24, 4 / 3, 0])
assert np.allclose(scores_before[:, 0], 3 * np.sqrt(2) * batch)
assert np.allclose(scores_before[:, 1], condition)
np.round(scores_before[:, :2], 3)

The scores agree with the planted contrasts: the largest spread is technical by construction. In real data we do not know the planted effects. Plotting measured batch and condition metadata helps investigate what a component is associated with; loadings identify the genes involved, but neither association alone proves a cause.1

What batch adjustment assumes

In this balanced example, a batch’s mean is \(\mu+b_i a\) because its two condition signs cancel. Subtracting that mean and restoring the overall mean gives \[ x_i^{\mathrm{adj}}=x_i-\bar x_{\mathrm{batch}(i)}+\bar x =\mu+\tau_i c. \] It removes the known additive batch shift while preserving the condition contrast. The calculation relies on the balanced design and the additive model; the next section shows what happens without balance.

Algorithm Center known batches in the balanced example

Input: an \(n\times p\) matrix \(X\) with expression value \(X_{ij}\) for sample \(i\) and gene \(j\), and the known batch label \(b_i\) for row \(i\).

Output: the adjusted rows \(x_i^{\mathrm{adj}}\) and their PCA.

  1. For each gene \(j\), \(\bar X_j\leftarrow\frac1n\sum_{i=1}^{n}X_{ij}\). // mean over all samples
  2. For each distinct batch label \(b\):
    1. \(I_b\leftarrow\{i:b_i=b\}\). // find rows in this batch
    2. For each gene \(j\), set \(\bar X_j^{(b)}\leftarrow\frac1{|I_b|}\sum_{i\in I_b}X_{ij}\). // mean within this batch
    3. For each \(i\in I_b\) and gene \(j\), set \(X_{ij}^{\mathrm{adj}}\leftarrow X_{ij}-\bar X_j^{(b)}+\bar X_j\). // remove the batch offset
  3. Apply step 3 of “Compare PCA of raw counts and log-CPM” with the sole matrix \(Y=X^{\mathrm{adj}}\) and \(J=\{1,\ldots,p\}\). // fit PCA after adjustment
  4. Return \(X^{\mathrm{adj}}\) and its PCA scores, loadings, and component variances.
Python Subtract batch means and refit PCA
adjusted_X = batch_X.copy()
grand_mean = batch_X.mean(axis=0)
for group in np.unique(batch):
    selected = batch == group
    adjusted_X[selected] = batch_X[selected] - batch_X[selected].mean(axis=0) + grand_mean
scores_after, loadings_after, variance_after = pca_summary(adjusted_X)
expected_adjusted = np.column_stack([np.full(4, 10), np.full(4, 10), 10 + condition])
assert np.allclose(adjusted_X, expected_adjusted)
assert np.allclose(scores_after[:, 0], condition)
assert np.allclose(variance_after, [4 / 3, 0, 0])
adjusted_X

The first two adjusted gene values are \(10\) in every sample. Gene 3 is \(9\) in the controls and \(11\) in the treated samples, so the refitted PC1 scores are \(-1\) and \(+1\), respectively.

Before adjustment, four samples occupy two batch-separated columns with controls below treated samples. After adjustment, controls s1 and s3 coincide at minus1 and treated s2 and s4 coincide at plus1, all with PC2 zero.

Figure 16.3. PCA before and after batch-mean adjustment of the balanced additive example, using equal data-unit scales. Blue denotes control and orange treated; circles denote batch -1 and squares batch +1 before adjustment. PCA is refitted afterward. The larger technical contrast disappears while the smaller condition contrast remains.

The adjusted example has rank one, so PC2 scores are all zero and its loading direction is arbitrary. The disappearance of batch separation is expected here; in real data it does not by itself prove that biology was preserved.

When batch and condition coincide

Suppose all controls were processed in one batch and all treated samples in another. Then \(b_i=\tau_i\), and the model becomes \[ x_i=\mu+\tau_i(a+c). \] In the balanced experiment, comparing control and treatment within the same batch held processing fixed. That comparison is now missing. A treated sample differs from a control in both condition and batch, so the data reveal only their combined profile \(a+c\).

For example, if \(a+c=(3,3,1)\), both of these explanations produce the same measurements and the same PCA plot:

explanation batch profile \(a\) condition profile \(c\)
entirely technical \((3,3,1)\) \((0,0,0)\)
entirely biological \((0,0,0)\) \((3,3,1)\)

Theorem 16.1 Confounded effects cannot be separated from these measurements

In the model \(x_i=\mu+b_i a+\tau_i c\), if \(b_i=\tau_i\) for every sample, the batch and condition profiles are unidentifiable: distinct pairs \((a,c)\) give the same data.

Proof

For any row vector \(h\), set \(a'=a+h\) and \(c'=c-h\). Then \[ \mu+b_i a'+\tau_i c' =\mu+\tau_i(a+h+c-h) =\mu+\tau_i(a+c)=x_i. \] Thus even exact measurements cannot determine the two profiles separately.

Subtracting batch means in this design subtracts \(\mu+\tau_i(a+c)\), leaving only the restored grand mean. It removes the entire condition-associated contrast, including any true biological contribution. Leaving the contrast untouched can retain a technical contribution. Neither choice resolves the missing comparison.

Recording batch labels is essential, but labels cannot repair a missing comparison. Processing both conditions within each batch, with biological replication, supplies the comparison; adjustment in less balanced data then requires a model and enough design information to separate the effects.1

Key idea

PCA reports the largest variation in whatever matrix it receives. Preprocessing decides which differences count, and the experimental design decides whether technical and biological differences can be told apart; adjustment cannot supply a comparison the design never made.

Reading a PCA result as evidence

The reported component variances describe how the chosen matrix’s spread is distributed. A sharp drop can motivate a low-dimensional summary, but a variance cutoff is not a biological criterion: the batch example’s condition contrast occupies the smaller component.

Sample labels and metadata help ask whether an unusual score follows treatment, batch, sequencing depth, or another measured feature. Loadings show which genes contribute to that direction. Refit under scientifically plausible preprocessing choices to see which relationships persist; changing an analysis until the desired groups separate is not validation.1

The two central decisions precede the plot: which representation should define sample differences, and which experimental comparisons separate biology from processing. PCA summarizes the resulting variation through scores and loadings. The next lesson asks a different question, comparing biological conditions for one gene, with an effect size and a null model for sampling variation.

Exercises

Exercise 16.1. Two samples have absolute RNA abundances \((10,10,10)\) and \((10,10,30)\). Suppose reads sample these proportions. Calculate the expected relative abundances. Which genes look reduced after total-count normalization even though their absolute abundance did not change? What extra measurement could distinguish a global abundance change from a depth change?

Exercise 16.2. Reproduce the three explained-fraction vectors in the scaling example. Derive the standardized sample distance formula and explain what is gained and lost by giving every retained gene unit variance. What must happen to a constant gene?

Exercise 16.3. In the planted batch example, verify \(\sum_i b_i\tau_i=0\) and derive both score vectors by multiplying \(Z\) by their loading directions. Change the batch profile from \((3,3,0)\) to \((1/2,1/2,0)\). Which contrast becomes PC1? Does this change which effect is biologically meaningful?

Exercise 16.4. Give two different pairs of batch and condition profiles that produce the same fully confounded data. Explain why overlapping batches in an adjusted PCA plot does not prove that an adjustment preserved the condition effect. Propose a design change that supplies the missing comparison.

References 1 source
1.Holmes, S., and W. Huber. 2019. Modern Statistics for Modern Biology. Cambridge University Press. huber.embl.dehttps://www.huber.embl.de/msmb/↑ 1 2 3 4 5 6 7