From raw metrics to PCA, on a fake cluster¶
Companion to the post My Cluster Has 48 Panels and One Story. The post runs PCA on three months of real metrics from my lab. This notebook follows the same path on a fake cluster, so you can run every step with nothing but NumPy, pandas and matplotlib:
| Step | What happens | Post section |
|---|---|---|
| 1 | Build the raw table the collector produces | Where the 48 columns come from |
| 2 | Turn it into one standardised matrix | Where the 48 columns come from |
| 3 | Count how many columns say the same thing | Why I could not just look at the panels |
| 4 | The PCA recipe, tested on a planted answer | The part that clicked |
| 5 | PCA on the fake cluster: scree, weights, daily cycle | The first component is the day |
| 6 | Keep fewer columns | What it is for, and what it costs |
| 7 | Two ways it goes wrong | What it costs, what tripped me up |
The fake cluster has the same shape as the real one - 12 services, 4 metrics each, a sample every five minutes - but 28 days instead of 91, so it runs in seconds. The numbers will not match the post; the method is the same. Run the cells top to bottom.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
rng = np.random.default_rng(0) # fixed seed: you get the same numbers as me
BLUE, GREEN, AMBER, SLATE = "#3b82f6", "#10b981", "#f59e0b", "#64748b"
plt.rcParams.update({
"figure.figsize": (8.5, 3.6), "figure.dpi": 110, "savefig.bbox": "tight",
"axes.spines.top": False, "axes.spines.right": False, "axes.grid": True,
"grid.color": "#e2e8f0", "grid.linewidth": 0.8, "axes.axisbelow": True,
"axes.titlesize": 13, "axes.titleweight": "bold", "axes.titlelocation": "left",
"axes.labelcolor": "#334155", "xtick.color": "#475569", "ytick.color": "#475569",
"font.size": 10.5,
})
1. The raw table¶
The collector writes long format: one row per time, service, pod, metric, value. The fake version
has the same awkward features the real one has, each of which the next section has to handle:
- timestamps that do not land on the five-minute mark (the real ones sit at
:03,:08...) - several pods per service, and one pod replaced halfway through, as a deploy would do
- a
restarts_totalcounter that is almost always zero - a few rows with an empty service name
- a few duplicate samples, and a few missing ones
- one service whose CPU is near zero and then spikes hard
SERVICES = [f"svc{i:02d}" for i in range(12)]
START = pd.Timestamp("2026-01-05", tz="UTC")
STEPS = 28 * 288 # 288 five-minute steps per day
grid = START + pd.to_timedelta(np.arange(STEPS) * 5, unit="min")
hour = np.asarray(grid.hour + grid.minute / 60)
# One shared daily traffic curve: quiet around 02:00, busy around 14:00, a dip at lunchtime.
traffic = 0.6 + 0.4 * np.sin((hour - 8) / 24 * 2 * np.pi) - 0.08 * np.exp(-(((hour - 12) / 0.7) ** 2))
frames = []
for s, svc in enumerate(SERVICES):
load = traffic * rng.uniform(0.5, 2.0) * (1 + 0.15 * rng.standard_normal(STEPS))
cpu = 0.01 * load + 0.001 * rng.standard_normal(STEPS)
net_in = 5e4 * load + 2e3 * rng.standard_normal(STEPS)
net_out = 0.9 * net_in + 1e3 * rng.standard_normal(STEPS)
memory = 2e8 + np.cumsum(2e5 * rng.standard_normal(STEPS)) # a slow drift, unrelated to traffic
if svc == "svc03": # the spiky one
cpu = 0.0005 + np.where(rng.random(STEPS) < 0.002, 0.2, 0.0) + 0.0002 * rng.random(STEPS)
series = {"cpu_cores": cpu, "memory_working_set_bytes": memory,
"network_receive_bytes_per_sec": net_in, "network_transmit_bytes_per_sec": net_out}
# Two pods share the work; halfway through, pod "a" is replaced by pod "c" (a deploy).
for pod, share, lo, hi in [(f"{svc}-a", 0.6, 0, STEPS // 2), (f"{svc}-c", 0.6, STEPS // 2, STEPS),
(f"{svc}-b", 0.4, 0, STEPS)]:
for metric, v in series.items():
frames.append(pd.DataFrame({"ts": grid[lo:hi], "service": svc, "pod": pod,
"metric": metric, "value": v[lo:hi] * share}))
restarts = np.zeros(STEPS)
if s in (2, 7): # two services restart a couple of times
restarts[rng.choice(STEPS, 2)] = 1
frames.append(pd.DataFrame({"ts": grid, "service": svc, "pod": f"{svc}-b",
"metric": "restarts_total", "value": np.cumsum(restarts)}))
long = pd.concat(frames, ignore_index=True)
# The awkward parts, on purpose.
long["ts"] += pd.to_timedelta(180 + rng.uniform(0, 60, len(long)), unit="s") # sampled at :03, not :00
long.loc[rng.random(len(long)) < 0.0005, "service"] = "" # unlabelled series
long = pd.concat([long, long.sample(frac=0.003, random_state=1)]) # duplicate samples
bucket = long["ts"].dt.floor("5min") # missing samples: whole
holes = pd.MultiIndex.from_arrays([rng.choice(grid, 80), rng.choice(SERVICES, 80), # (time, service, metric)
rng.choice(long["metric"].unique(), 80)]) # buckets, every pod at once
long = long[~pd.MultiIndex.from_arrays([bucket, long["service"], long["metric"]]).isin(holes)]
long = long.sort_values("ts").reset_index(drop=True)
print(long.shape)
long.head(6)
(873379, 5)
| ts | service | pod | metric | value | |
|---|---|---|---|---|---|
| 0 | 2026-01-05 00:03:00.531730549+00:00 | svc04 | svc04-b | network_transmit_bytes_per_sec | 8.555902e+03 |
| 1 | 2026-01-05 00:03:00.720825902+00:00 | svc10 | svc10-b | network_receive_bytes_per_sec | 8.524476e+03 |
| 2 | 2026-01-05 00:03:01.108433800+00:00 | svc02 | svc02-b | restarts_total | 0.000000e+00 |
| 3 | 2026-01-05 00:03:01.138074087+00:00 | svc09 | svc09-a | network_transmit_bytes_per_sec | 5.488184e+03 |
| 4 | 2026-01-05 00:03:03.215938187+00:00 | svc11 | svc11-a | network_receive_bytes_per_sec | 1.108488e+04 |
| 5 | 2026-01-05 00:03:03.953014674+00:00 | svc11 | svc11-a | memory_working_set_bytes | 1.199270e+08 |
2. One matrix for everything¶
PCA wants a table where each row is one moment and each column is one thing measured. Getting there from the long table takes five decisions, each of which changes what PCA can find. This is the same function, in the same order, as the one I run on the real data:
- Drop the empty service - unlabelled series are not a service.
- Drop
restarts_total- almost always zero with rare spikes, so after scaling it would dominate a component for the wrong reason. Restarts are events: better used as labels than as features. - Floor
tsto five minutes - rows only line up on a shared clock. - Average duplicates, then add up the pods - pods are replaced on every deploy; services persist.
- Pivot, drop incomplete rows, standardise - in that order. Filling gaps invents values, and the mean and standard deviation must be measured on the rows that are left.
def build_matrix(long: pd.DataFrame, standardise: bool = True) -> pd.DataFrame:
"""Long-format metrics in; wide (time x service-metric) matrix out, standardised by default."""
long = long[long["service"] != ""] # 1. drop the empty service
long = long[long["metric"] != "restarts_total"] # 2. drop restarts
long = long.assign(ts=long["ts"].dt.floor("5min")) # 3. align to the five-minute clock
# 4. The mean merges duplicate samples from one pod in one bucket; the sum then adds the pods up.
per_pod = long.groupby(["ts", "service", "pod", "metric"], as_index=False)["value"].mean()
per_svc = per_pod.groupby(["ts", "service", "metric"], as_index=False)["value"].sum()
# 5. Pivot: one row per time, one column per (service, metric).
wide = per_svc.pivot(index="ts", columns=["service", "metric"], values="value")
wide.columns = [f"{s}:{m}" for s, m in wide.columns]
missing = wide.isna().any(axis=1)
print(f"dropping {missing.sum()} of {len(wide)} rows with a gap")
wide = wide[~missing] # drop first ...
return (wide - wide.mean()) / wide.std() if standardise else wide # ... then standardise
X = build_matrix(long)
print(X.shape)
X.iloc[:4, :4].round(2)
dropping 65 of 8064 rows with a gap (7999, 48)
| svc00:cpu_cores | svc00:memory_working_set_bytes | svc00:network_receive_bytes_per_sec | svc00:network_transmit_bytes_per_sec | |
|---|---|---|---|---|
| ts | ||||
| 2026-01-05 00:00:00+00:00 | -1.52 | -0.11 | -1.23 | -1.21 |
| 2026-01-05 00:05:00+00:00 | -1.30 | -0.10 | -0.89 | -0.88 |
| 2026-01-05 00:10:00+00:00 | -1.13 | -0.18 | -1.16 | -1.15 |
| 2026-01-05 00:15:00+00:00 | -0.87 | -0.21 | -1.14 | -1.14 |
Every column now has mean 0 and standard deviation 1, so a column measured in bytes cannot outvote one
measured in cores. X.shape is (rows, 48): 12 services times 4 metrics.
3. How many columns say the same thing?¶
Before any PCA, ask the question PCA will answer. Because X is standardised, XᵀX / (n - 1) is the
correlation matrix: every pair of columns, scored from -1 (opposite) to +1 (identical). Count the pairs
above 0.95.
corr = X.T @ X / (len(X) - 1)
upper = np.triu_indices_from(corr, k=1) # each pair once, no diagonal
pairs = pd.Series(corr.to_numpy()[upper],
index=pd.MultiIndex.from_arrays([corr.index[upper[0]], corr.columns[upper[1]]]))
print(f"{(pairs > 0.95).sum()} of {len(pairs)} pairs of columns have a correlation above 0.95")
pairs.sort_values(ascending=False).head(5).round(3)
24 of 1128 pairs of columns have a correlation above 0.95
svc05:network_receive_bytes_per_sec svc05:network_transmit_bytes_per_sec 0.998 svc00:network_receive_bytes_per_sec svc00:network_transmit_bytes_per_sec 0.998 svc04:network_receive_bytes_per_sec svc04:network_transmit_bytes_per_sec 0.998 svc06:network_receive_bytes_per_sec svc06:network_transmit_bytes_per_sec 0.998 svc10:network_receive_bytes_per_sec svc10:network_transmit_bytes_per_sec 0.997 dtype: float64
fig, ax = plt.subplots(figsize=(6.2, 5.2))
im = ax.imshow(corr, cmap="RdBu_r", vmin=-1, vmax=1)
ax.grid(False)
ax.set_xticks(np.arange(1.5, 48, 4), [c.split(":")[0] for c in corr.columns[1::4]], rotation=90, fontsize=7)
ax.set_yticks(np.arange(1.5, 48, 4), [c.split(":")[0] for c in corr.index[1::4]], fontsize=7)
ax.set_title("Correlation between all 48 columns")
fig.colorbar(im, ax=ax, shrink=0.8, label="correlation")
plt.show()
Each service is a block of four columns. The big red squares are CPU and network moving together (traffic). The memory columns - the thin pale rows and columns inside each block - share almost nothing with anything. The blocks do not need 48 numbers to describe them; PCA finds how few they do need.
4. The recipe, tested on a planted answer¶
Four lines. C is the covariance matrix: how much each pair of columns varies together. Its
eigenvectors are the directions the data spreads along, and each eigenvalue is the variance
along its eigenvector.
First a test where we know the answer: two columns that are one hidden signal t plus a little noise
each. If PCA cannot find a signal we planted, we should not trust it on anything else.
def pca(X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
C = X.T @ X / (len(X) - 1) # covariance (X must already be standardised)
vals, vecs = np.linalg.eigh(C) # eigh: the version for symmetric matrices
order = np.argsort(vals)[::-1] # eigh returns smallest first; we want largest first
return vals[order], vecs[:, order]
t = rng.standard_normal(2000)
P = np.column_stack([t + 0.3 * rng.standard_normal(2000), t + 0.3 * rng.standard_normal(2000)])
P = (P - P.mean(axis=0)) / P.std(axis=0, ddof=1)
vals, vecs = pca(P)
print("share of variance:", (vals / vals.sum()).round(3)) # expect about [0.96, 0.04]
print("PC1 weights:", vecs[:, 0].round(3)) # expect +/-[0.707, 0.707]
share of variance: [0.959 0.041] PC1 weights: [-0.707 -0.707]
fig, ax = plt.subplots(figsize=(4.6, 4.6))
ax.scatter(P[:, 0], P[:, 1], s=6, color=SLATE, alpha=0.25)
for k, (colour, name) in enumerate([(BLUE, "PC1"), (AMBER, "PC2")]):
d = vecs[:, k] * 3 * np.sqrt(vals[k])
ax.annotate("", xy=d, xytext=-d, arrowprops=dict(arrowstyle="->", color=colour, lw=2.5))
ax.text(*(d * 1.12), name, color=colour, fontweight="bold", ha="center")
ax.set_aspect("equal"); ax.set_xlabel("column A"); ax.set_ylabel("column B")
ax.set_title("PC1 follows the long axis of the cloud")
plt.show()
0.707 is 1/sqrt(2): equal weight on both columns, scaled so the vector has length 1. If you see
-0.707 instead, that is also right - an eigenvector can point either way.
5. PCA on the fake cluster¶
Same function, now on all 48 columns. A scree plot shows how much of the total variance each component carries; one tall bar means one shared signal.
vals, vecs = pca(X.to_numpy())
share = vals / vals.sum()
cum = share.cumsum()
k95 = int(np.searchsorted(cum, 0.95) + 1)
print(f"PC1 carries {share[0]:.1%}; {k95} components reach 95%")
fig, ax = plt.subplots()
ax.bar(np.arange(1, 49), share, color=BLUE, alpha=0.55)
ax.bar(1, share[0], color=BLUE)
ax.plot(np.arange(1, 49), cum, color=GREEN, lw=2, ls=":")
ax.scatter([k95], [cum[k95 - 1]], color=GREEN, zorder=3)
ax.annotate(f"{k95} components reach 95%", (k95, cum[k95 - 1]), (k95 + 4, 0.8), color="#334155")
ax.set_xlabel("principal component (largest first)"); ax.set_ylabel("share of variance")
ax.set_title("One shared signal dominates")
plt.show()
PC1 carries 62.0%; 20 components reach 95%
What is PC1 made of?¶
The weights (an eigenvector's entries) say which columns make up a component. The sign of an eigenvector is arbitrary, so flip it until most weights are positive - then positive reads as "busier than average".
pc1 = vecs[:, 0] * np.sign(vecs[:, 0].sum())
weights = pd.Series(pc1, index=X.columns)
by_metric = weights.groupby(lambda c: c.split(":")[1]).mean().round(3)
print(by_metric)
colour = {"cpu_cores": BLUE, "memory_working_set_bytes": AMBER,
"network_receive_bytes_per_sec": GREEN, "network_transmit_bytes_per_sec": GREEN}
fig, ax = plt.subplots(figsize=(8.5, 3))
ax.bar(range(48), weights.to_numpy(), color=[colour[c.split(":")[1]] for c in weights.index])
ax.set_xticks(np.arange(1.5, 48, 4), [c.split(":")[0] for c in weights.index[1::4]], rotation=90, fontsize=7)
ax.set_title("PC1 weights: blue CPU, green network, amber memory"); ax.set_ylabel("weight")
plt.show()
cpu_cores 0.150 memory_working_set_bytes 0.000 network_receive_bytes_per_sec 0.172 network_transmit_bytes_per_sec 0.171 dtype: float64
When is it active?¶
A score is the dot product of one moment's 48 values with PC1's 48 weights: how far along PC1 that moment sits. Average the scores by hour of day.
scores = pd.Series(X.to_numpy() @ pc1, index=X.index)
by_hour = scores.groupby(scores.index.hour).mean()
fig, ax = plt.subplots()
ax.plot(by_hour.index, by_hour.to_numpy(), color=BLUE, lw=2.5, marker="o", ms=4)
ax.axhline(0, color=SLATE, lw=1)
ax.set_xlabel("hour of day (UTC)"); ax.set_ylabel("mean PC1 score")
ax.set_title(f"PC1 is the daily traffic cycle: quietest {by_hour.idxmin():02d}:00, busiest {by_hour.idxmax():02d}:00")
plt.show()
That is the planted-answer test again, at full scale: the daily curve was put in at the top of this notebook, and PCA recovered it without being told.
6. Fewer columns¶
Keeping the first k components is one matrix multiply. The result has k columns instead of 48 and
still holds 95% of the variance.
Z = X.to_numpy() @ vecs[:, :k95]
print(X.shape, "->", Z.shape)
(7999, 48) -> (7999, 20)
raw = build_matrix(long, standardise=False)
raw = raw - raw.mean() # centred, but NOT scaled
vals_raw, vecs_raw = pca(raw.to_numpy())
top = pd.Series(np.abs(vecs_raw[:, 0]), index=raw.columns).sort_values().tail(8)
print(f"PC1 now carries {vals_raw[0] / vals_raw.sum():.1%} of the variance")
fig, ax = plt.subplots(figsize=(8.5, 3.2))
ax.barh(top.index, top.to_numpy(), color=[AMBER if "memory" in c else BLUE for c in top.index])
ax.set_title("Without standardising, PC1 is memory - a fact about bytes, not about the cluster")
ax.set_xlabel("size of weight in PC1")
plt.show()
dropping 65 of 8064 rows with a gap PC1 now carries 40.8% of the variance
One service that spikes¶
A column that sits near zero and then spikes hard has a standard deviation many times its mean, and
spikes like that can pull a component towards them. svc03 was built to do this.
spikiness = (raw.std() / raw.mean()).sort_values().tail(6) # raw units: std divided by mean
fig, ax = plt.subplots(figsize=(8.5, 2.8))
ax.barh(spikiness.index, spikiness.to_numpy(), color=[AMBER if "svc03" in c else SLATE for c in spikiness.index])
ax.set_title("Standard deviation divided by mean: one column spikes far more than the rest")
plt.show()
Try it yourself¶
- Make memory follow traffic too (
memory = 2e8 + 1e7 * load). What happens to PC1's share? - Add a second, weekly signal to half the services. Does it show up as PC2?
- Raise the noise on
load. At what point does PC1 stop standing out?