Tag: Safety

  • ML0172 Hierarchical Clustering

    Explain agglomerative clustering: linkage choices (single/complete/average/Ward), the dendrogram, and where to cut it. Why is it O(n^2) memory?

    Three-panel scenario card. Panel one, the data: 3,000 customer profiles with 8 standardized features, a goal of 3 to 6 segments for marketing campaigns, and no fixed k known up front. Panel two, pilot runs and constraints: a single-linkage cut at k equal to 4 gave cluster sizes 2,991, 6, 2 and 1; a Ward run has six highest merge heights 52.0, 38.5, 31.0, 12.4, 10.9 and 9.7; next quarter the job must run on 100,000 customers on one 32 GB machine. Panel three lists the open decisions: which linkage, where to cut the dendrogram, and whether 100,000 points fit in 32 GB of RAM.

    The Problem: A retail team wants 3 to 6 customer segments from 3,000 profiles with 8 standardized features, but a single-linkage pilot cut at k = 4 returned clusters of 2,991, 6, 2 and 1 customers, while a Ward run shows top merge heights of 52.0, 38.5, 31.0, 12.4, 10.9 and 9.7. Next quarter the same job must run on 100,000 customers on a 32 GB machine, and nobody has decided the linkage, the cut, or whether it will fit.

    Answer

    Agglomerative clustering starts with every point as its own cluster and repeatedly merges the two closest clusters until one remains. Each merge and its height are recorded in a dendrogram, a binary tree with n-1 joins. The linkage defines “closest”: single uses the nearest cross pair, complete the farthest, average the mean over all cross pairs, and Ward the increase in within-cluster sum of squares. A flat clustering comes from cutting the tree horizontally, ideally inside a large gap between consecutive merge heights. The standard algorithm stores all n(n-1)/2 pairwise cluster distances and refreshes them after every merge with the Lance-Williams update. That matrix is the source of the O(n^2) memory, and at n = 100{,}000 it holds about 5 billion float64 values, or 40 GB.

    (1) Single Linkage: Distance between the two nearest members, which makes the hierarchy equivalent to the minimum spanning tree. It recovers elongated, non-convex shapes but chains clusters together through a few bridging points.
    (2) Complete Linkage: Distance between the two farthest members, so every cluster formed below height h has diameter at most h. Clusters come out compact, but one outlier inflates a diameter and large groups tend to be split.
    (3) Average Linkage: Mean of all |A|\,|B| cross distances, also called UPGMA. It sits between the two extremes, dilutes single outliers, and works with any dissimilarity such as cosine or correlation.
    (4) Ward Linkage: Merges the pair whose union adds the least within-cluster sum of squares, the same objective k-means minimizes. It yields compact clusters of similar size and only makes sense with Euclidean distance.
    (5) Reading The Dendrogram: Only heights carry meaning, since the left-right order is one of 2^{n-1} equivalent flips. Cut at a fixed height, at the level that leaves k branches, or inside the largest gap between merge heights.
    (6) Why Quadratic Memory: After merging i and j, the Lance-Williams update needs the old distances from every other cluster to both, so the whole distance matrix must stay live. The nearest-neighbor chain algorithm brings time down to O(n^2) from the naive O(n^3), but memory stays quadratic for complete and average linkage.

    Mathematical Formulation:
    d_{\mathrm{single}}(A,B) = \min_{a \in A,\, b \in B} d(a,b)
    d_{\mathrm{complete}}(A,B) = \max_{a \in A,\, b \in B} d(a,b)
    d_{\mathrm{avg}}(A,B) = \frac{1}{|A|\,|B|} \sum_{a \in A} \sum_{b \in B} d(a,b)
    \Delta_{\mathrm{Ward}}(A,B) = \frac{|A|\,|B|}{|A| + |B|} \, \|\mu_A - \mu_B\|^2
    d_{k,(ij)} = \alpha_i d_{ki} + \alpha_j d_{kj} + \beta d_{ij} + \gamma \delta_k
    \delta_k = |d_{ki} - d_{kj}|
    M = 8 \cdot \frac{n(n-1)}{2}\ \text{bytes}

    Where:

    • A and B are two current clusters with members a and b, |A| is a cluster size, and d is the base dissimilarity. Single, complete and average linkage accept any dissimilarity.
    • \mu_A is the centroid of A, and \Delta_{\mathrm{Ward}} is the exact rise in total within-cluster SSE when A and B merge. It requires Euclidean geometry, and SciPy reports the merge height as \sqrt{2\Delta}.
    • d_{ki}, d_{kj} and d_{ij} are pre-merge distances between an untouched cluster k and the just-merged clusters i and j, and d_{k,(ij)} is the updated distance to their union.
    • \alpha_i, \alpha_j, \beta, \gamma select the linkage. Single uses \alpha = \frac{1}{2}, \beta = 0, \gamma = -\frac{1}{2} (a min), complete flips to \gamma = +\frac{1}{2} (a max), and average uses \alpha_i = \frac{n_i}{n_i + n_j} with \beta = \gamma = 0.
    • Ward uses \alpha_i = \frac{n_i + n_k}{n_i + n_j + n_k}, \beta = -\frac{n_k}{n_i + n_j + n_k} and \gamma = 0 on squared Euclidean distances, where n_i, n_j, n_k are cluster sizes.
    • M is the size of the condensed float64 distance matrix for n points: 36 MB at n = 3{,}000, 40 GB at n = 100{,}000, and double that for a full square matrix.

    Worked Example:
    On a line, take clusters A = \{0, 2\}, B = \{4, 9\} and C = \{12.5\}. The cross distances between A and B are 4, 9, 2 and 7, so single gives 2, complete gives 9 and average gives 5.5. Between B and C they are 8.5 and 3.5, so single gives 3.5, complete gives 8.5 and average gives 6.0. Single and average therefore merge A with B, while complete merges B with C because 8.5 beats 9. Ward compares SSE increases: \Delta(A,B) = 1 \times 5.5^2 = 30.25 and \Delta(B,C) = \frac{2}{3} \times 6^2 = 24, so Ward also picks B \cup C. Same three clusters, two different trees after one step.

    Four scatter panels of the same 315 two-dimensional points, made of a large blob, a smaller blob joined to it by a thin bridge of 12 points, a curved arc above them, and three isolated points. Each panel colors the k equals 3 clustering from one linkage: single, complete, average and Ward, with the resulting cluster sizes printed in each panel title.

    Figure 1: The same 315 points cut at k = 3 under each linkage, with cluster sizes in each panel title. Single linkage follows nearest-neighbor chains, so the 12-point bridge and the isolated points decide its partition. Ward prices every merge by added variance and favors compact groups of similar spread, and complete and average land between these extremes.

    In practice the choice follows from two questions: which dissimilarity do you trust, and what cluster shape do you expect? Ward is the default for standardized numeric features where k-means-like segments are wanted. Average linkage is the default for non-Euclidean similarities such as correlation between gene-expression profiles, and single linkage is reserved for clean data with genuinely elongated structure.

    PropertyWardAverageCompleteSingle
    Merge criterionSmallest rise in within-cluster SSEMean of all cross-pair distancesFarthest cross pairNearest cross pair
    Cluster shapeCompact, similar size and varianceModerately compact, tolerates size differencesCompact with bounded diameterArbitrary, elongated chains
    Outliers and noiseAbsorbed into the nearest compact groupDiluted by averagingInflate diameters and split large groupsBecome singletons, and bridges chain clusters
    DissimilarityEuclidean onlyAnyAnyAny
    Best exact algorithmO(n²) time; O(nd) memory from stored centroidsNN-chain, O(n²) time and O(n²) memoryNN-chain, O(n²) time and O(n²) memoryMST or SLINK, O(n²) time and O(n) memory
    Reach for it whenYou want k-means-like segments plus a hierarchyThe similarity is cosine or correlationEvery cluster must stay within a maximum spreadData are clean and shapes are non-convex

    Login to view more content
  • ML0169 Kalman Filter & Sensor Fusion

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0156 Stratified Sampling & Quota Design

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • DL0256 Chatbot Arena ELO Gaming

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0138 Statistical Test Selection

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0135 OLS Diagnostics & Gauss-Markov

    What makes OLS the best linear unbiased estimator? Explain the Gauss-Markov theorem, heteroscedasticity and robust standard errors, and omitted-variable bias, and say which diagnostics tell you whether a regression’s coefficients and t-statistics can be trusted.

    Line-art scene: an inputs box with daily stock returns y and an order-flow signal x1 feeds an OLS fit box, which produces a regression printout reading slope 0.42, t equals 3.1, R squared equals 0.04; arrows from the printout lead to three question boxes asking whether the slope is biased by a factor left out of the model, whether t equals 3.1 can be trusted if noise is larger in volatile regimes, and whether R squared of 0.04 means the signal is worthless

    The Problem: A regression of returns on a trading signal prints a significant slope and a tiny R^2. Before any capital moves, three questions decide whether the coefficient, its t-statistic, and its fit statistic can be believed.

    Answer

    The Gauss-Markov theorem says that ordinary least squares has the smallest variance among all linear unbiased estimators once four conditions hold, which is exactly what BLUE means. The conditions are linearity in the parameters, a full-rank regressor matrix, errors with zero conditional mean (strict exogeneity), and homoscedastic, uncorrelated errors. Exogeneity alone delivers unbiasedness, while the error-variance condition delivers efficiency and the validity of the textbook covariance \sigma^2(X^\top X)^{-1}. Heteroscedasticity therefore leaves the coefficients unbiased but makes the classical standard errors and t-statistics wrong, which Huber-White robust standard errors repair. An omitted variable correlated with an included regressor breaks exogeneity instead, so the coefficient itself is biased and no standard-error correction can rescue it. Normality is not among the conditions and only matters for exact small-sample t and F tests.

    (1) Best Within A Narrow Class: OLS beats only linear unbiased estimators. A biased estimator such as ridge can have lower mean squared error, and under heteroscedasticity GLS beats OLS.
    (2) Heteroscedasticity Hurts Inference, Not The Estimate: With \mathrm{Var}(\varepsilon_i \mid X) = \sigma_i^2 the slope stays unbiased and consistent, but s^2(X^\top X)^{-1} is wrong. It typically understates uncertainty when the error variance rises with leverage.
    (3) Sandwich Standard Errors: White’s estimator replaces \sigma^2 I with the squared residuals. Use HC3 in small samples, and cluster-robust or Newey-West HAC errors when errors correlate within groups or over time.
    (4) Omitted-Variable Bias: Leaving out x_2 shifts the slope on x_1 by \beta_2 \delta_1, where \delta_1 is the slope from regressing x_2 on x_1. The sign of the bias follows the signs of \beta_2 and the covariance.
    (5) R-Squared Is Not A Validity Check: R^2 never falls when a regressor is added, and neither it nor adjusted R^2 says anything about bias or correct standard errors. A return forecast with R^2 = 0.01 can be valuable, while two trending series can show a spurious R^2 = 0.9.
    (6) Diagnose Through Residuals: Residual-versus-fitted plots, Breusch-Pagan tests, Q-Q plots, Durbin-Watson statistics, and leverage with Cook’s distance each target one specific assumption.

    Three-column ladder. The center column lists the Gauss-Markov assumptions top to bottom: A1 linear in beta and A2 full column rank, A3 strict exogeneity E of epsilon given X equals zero, A4 spherical errors with variance sigma squared I, A5 normal errors. Solid arrows to the right lead to cumulative properties: beta-hat exists and is unique, beta-hat is unbiased, beta-hat is BLUE and the classical standard error is valid, exact t and F tests for small n, with downward arrows labeled plus A3, plus A4, plus A5. Dashed red arrows to the left lead to failure boxes: perfect collinearity makes beta-hat unidentified; omitted variables, measurement error, or simultaneity make beta-hat biased and robust standard errors cannot fix it; heteroscedasticity or autocorrelation leave beta-hat unbiased but the standard error wrong, fixed by HC or HAC errors or GLS; fat tails make t and F only approximate

    Figure 1: Each Gauss-Markov assumption buys one property and each violation costs one. Breaking strict exogeneity damages the point estimate itself, while breaking spherical errors damages only the reported uncertainty, which is why the two failures need completely different fixes.

    Reading the ladder from top to bottom shows why answers that treat the assumptions as one block go wrong. A failure of A3 moves the center of the sampling distribution, so the slope is aimed at the wrong number no matter how much data you collect. A failure of A4 leaves the center in place but changes its width, so the slope is right on average while its reported t-statistic is not. A careful analyst therefore checks the specification before trusting the coefficient and checks the error structure before trusting the t-statistic. The proof of the theorem is short enough to reproduce at a whiteboard.

    Mathematical Formulation:
    y = X\beta + \varepsilon
    \hat\beta = (X^\top X)^{-1} X^\top y
    \mathrm{Var}(\hat\beta \mid X) = \sigma^2 (X^\top X)^{-1}
    \tilde\beta = \left[(X^\top X)^{-1} X^\top + D\right] y
    \mathrm{Var}(\tilde\beta \mid X) = \mathrm{Var}(\hat\beta \mid X) + \sigma^2 D D^\top
    \hat V_{\mathrm{HC}} = (X^\top X)^{-1} X^\top \hat\Omega X (X^\top X)^{-1}

    Where:

    • y is the n \times 1 response, X the n \times k regressor matrix including the intercept column, \beta the true coefficients, and \varepsilon the error vector.
    • \hat\beta is the OLS estimator and \sigma^2 the common error variance assumed by A4; the classical covariance is valid only when \mathrm{Var}(\varepsilon \mid X) = \sigma^2 I.
    • \tilde\beta is any other linear estimator, written as OLS plus an arbitrary k \times n matrix D. Unbiasedness for every \beta forces DX = 0, which kills the cross terms in the variance.
    • D D^\top is positive semidefinite, so every linear combination of \tilde\beta has variance at least as large as the same combination of \hat\beta. That inequality is the Gauss-Markov theorem.
    • \hat V_{\mathrm{HC}} is the sandwich covariance with \hat\Omega = \mathrm{diag}(e_1^2, \ldots, e_n^2) and residuals e_i = y_i - x_i^\top \hat\beta (HC0). HC3 replaces e_i^2 with e_i^2/(1-h_{ii})^2, where h_{ii} is the leverage of observation i.

    Worked Example:
    Suppose returns follow y = 1.0\,x_1 + 0.5\,x_2 + u, with a signal x_1 and a market factor x_2 where \mathrm{Var}(x_1) = 1 and \mathrm{Cov}(x_1, x_2) = 0.6. An analyst regresses y on x_1 alone.

    \mathrm{plim}\ \hat\beta_1^{\mathrm{short}} = \beta_1 + \beta_2 \delta_1
    \delta_1 = \mathrm{Cov}(x_1, x_2) / \mathrm{Var}(x_1) = 0.6
    \hat\beta_1^{\mathrm{short}} \approx 1.0 + 0.5 \times 0.6 = 1.3

    The short regression reports 1.3 instead of 1.0, a 30% overstatement of the signal that comes entirely from its correlation with the market factor. In sample the identity \hat\beta_1^{\mathrm{short}} = \hat\beta_1^{\mathrm{long}} + \hat\beta_2^{\mathrm{long}} \hat\delta_1 holds exactly, not just in the limit. Adding x_2 recovers 1.0, at the price of a standard error inflated by the variance inflation factor 1/(1 - 0.6^2) \approx 1.56. Robust standard errors on the short regression would simply draw a tight interval around 1.3, confidently centered on the wrong value.


    Login to view more content
  • ML0128 Multiple Comparisons & FDR

    Your experiment dashboard shows 200 metrics and 3 are ‘significant’. How do you separate real effects from false discoveries: FWER, FDR, and Benjamini-Hochberg?

    Line-art experiment dashboard: a frame holding a grid of 200 small metric tiles comparing treatment against control, with three tiles highlighted and linked to cards reading checkout conversion p = 0.00008, session length p = 0.011, and support tickets p = 0.038, under a header saying these were flagged with p under 0.05

    The Problem: One experiment readout with 200 metric tiles comparing treatment against control. Three tiles cross the p \leq 0.05 cutoff, with p-values 0.00008, 0.011, and 0.038.

    Answer

    With 200 metrics each tested at \alpha = 0.05, pure noise is expected to produce 10 significant results, so 3 hits is not evidence that anything moved. The family-wise error rate (FWER) is the probability of even one false positive across the family. With 200 independent null metrics it reaches 1 - 0.95^{200} \approx 0.99996. Bonferroni and Holm cap FWER at \alpha by demanding roughly p \leq 0.05/200 = 0.00025, which suits a launch claim but destroys power on a broad scan. The false discovery rate (FDR) bounds the expected share of false calls among the metrics you flag, and the Benjamini-Hochberg (BH) step-up procedure controls it at level q with far more power. In practice you split the 200 metrics into pre-registered families by decision role and give each family the error rate that matches what a wrong call would cost.

    (1) Count Before You Celebrate: The expected number of false positives under the global null is m\alpha = 10, so the count of hits says little. The size of the smallest p-values says a lot.
    (2) FWER vs FDR: FWER is P(V \geq 1) and treats any single false call as a failure. FDR is the expected false discovery proportion V/R, which tolerates a known fraction of false calls among discoveries.
    (3) Bonferroni and Holm: Bonferroni tests each metric at \alpha/m and is valid under any dependence. Holm’s step-down gives the same guarantee with uniformly more power, so plain Bonferroni is never the better choice.
    (4) Benjamini-Hochberg Step-Up: Sort the p-values, find the largest rank k with p_{(k)} \leq kq/m, and reject every rank up to it, even ranks that miss their own threshold. It is proven under independence and positive dependence (PRDS), and the Benjamini-Yekutieli variant covers arbitrary dependence at a cost of \ln m.
    (5) Families by Decision Role: Success metrics that support a launch get FWER control, guardrails get non-inferiority tests sized for power, and exploratory metrics and segments get BH because their hits only seed a confirmatory test.

    Mathematical Formulation:
    \mathrm{FWER} = P(V \geq 1)
    \mathrm{FDR} = \mathbb{E}\left[\frac{V}{\max(R, 1)}\right]
    P(V \geq 1) = 1 - (1 - \alpha)^{m}
    p_{i} \leq \frac{\alpha}{m}
    p_{(k)} \leq \frac{\alpha}{m - k + 1}
    k^{*} = \max\left\{k : p_{(k)} \leq \frac{k}{m}\,q\right\}
    c(m) = \sum_{i=1}^{m} \frac{1}{i}
    q_{\mathrm{BY}} = \frac{q}{c(m)}

    Where:

    • V is the number of true null metrics you reject (false discoveries) and R the total number rejected. The \max(R, 1) defines the false discovery proportion as 0 when nothing is rejected.
    • m is the number of tests in the family and \alpha the per-test or family-wise level. The third line is the FWER of m independent true nulls tested without correction: 0.64 at m = 20 and 0.99996 at m = 200.
    • p_{i} is the raw p-value of metric i, and the fourth line is the Bonferroni rule.
    • p_{(k)} is the k-th smallest p-value. Holm checks its threshold for k = 1, 2, \ldots, stops at the first failure, and rejects every rank before it.
    • q is the target FDR level and k^{*} the largest rank under the BH line kq/m. BH rejects H_{(1)}, \ldots, H_{(k^{*})}, scanning from the top down, which is why it is called step-up.
    • c(m) is the harmonic number, about \ln m + 0.577, so c(200) \approx 5.88. Running BH at q_{\mathrm{BY}} gives Benjamini-Yekutieli, valid under any dependence.

    Worked Example: Take a 10-metric family with sorted p-values 0.001, 0.012, 0.014, 0.019, 0.040, 0.09, 0.21, 0.36, 0.55, and 0.81, and run BH at q = 0.05. The BH threshold for rank k is 0.005k. The BH-adjusted p-value is p_{(k)} m / k, made monotone by taking the running minimum from the bottom rank upward.

    Rank kSorted pBH threshold kq/mBH-adjusted pDecision at q = 0.05
    10.0010.0050.010Reject
    20.0120.0100.0467Reject (misses its own threshold, rescued by rank 4)
    30.0140.0150.0467Reject
    40.0190.0200.0475Reject (largest passing rank, k* = 4)
    50.0400.0250.080Keep (raw p under 0.05, not a discovery)
    60.0900.0300.150Keep
    70.2100.0350.300Keep
    80.3600.0400.450Keep
    90.5500.0450.611Keep
    100.8100.0500.810Keep

    Five metrics have a raw p-value under 0.05, but the procedures disagree sharply. Bonferroni uses 0.05/10 = 0.005 and rejects only rank 1. Holm also stops at rank 2 because 0.012 > 0.05/9 \approx 0.0056. BH rejects four, and rank 2 is rejected despite failing its own threshold, because rank 4 passes. That rescue is the step-up property. Back on the 200-metric dashboard, the rank-2 BH threshold is 2 \times 0.05/200 = 0.0005, so 0.011 and 0.038 both fail. Only checkout conversion survives, with a BH-adjusted p of 0.00008 \times 200 = 0.016. Bonferroni reaches the same verdict here, which shows that BH gains power only when many small p-values exist to lift the line.

    The more important decision happens before any correction runs: which metrics belong to which family. A single BH pass over all 200 metrics mixes a launch claim, harm detection, and exploration into one error budget. The primary metric is tested first at full \alpha as a gatekeeper. Secondary success metrics get Holm only if the primary wins. Guardrails are non-inferiority checks where missed harm is the costly error. The exploratory long tail and segment slices get BH at a looser q, because a false lead there costs a follow-up experiment rather than a bad launch.

    Left-to-right pipeline: 200 metrics from one experiment feed a decision box that splits them into families by decision role fixed before unblinding; four family boxes follow (primary metric tested first at alpha 0.05, 9 secondary metrics with Holm at FWER 0.05, 20 guardrails as non-inferiority tests powered jointly, 170 exploratory metrics and segments with BH at q 0.10), each leading to an outcome box: launch claim, supporting claims, block launch if any guardrail fails, and hypotheses for a fresh confirmatory test

    Figure 1: The same 200 p-values get different treatment depending on the decision each family drives. FWER control guards launch claims, non-inferiority with power planning guards against missed harm, and BH keeps the exploratory tail useful without letting it ship anything.


    Login to view more content
  • ML0104 Distributions & CLT for Interviews

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0132 Chatbot Personalization Memory

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0131 Coding-Agent Execution Sandbox

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.