Probability Distributions, Sampling Bias, and Correlation
Medium · Machine Learning · Data Scientist · Online Assessment
Prompt
Answer each of the following three foundational probability and statistics scenarios clearly, stating any modeling assumptions you rely on:
- Count Process Shift: An automated payment-monitoring pipeline historically averages
2flagged alerts per hour across one-hour observation windows. After a platform change, you inspect the empirical probability mass function (PMF) of hourly alert counts and find that the fraction of zero-alert hours has dropped sharply below the theoreticalPoisson(2)baseline. What does this tell you about the underlying arrival mechanism, and which model parameter may have shifted? - Training Cohort Selection Bias: A B2B subscription software company wants to predict account cancellation. To assemble a labeled dataset, the team samples currently active customer accounts that have maintained at least
12months of continuous tenure, then deploys the resulting classifier to score newly onboarded sign-ups. Name the statistical bias created by this cohort filter and explain how it distorts model behavior on brand-new accounts. - Zero Covariance and Affine Transformations: Let
XandYbe real-valued random variables:- Does
Cov(X, Y) = 0guarantee thatXandYare statistically independent? Justify your conclusion or construct a concrete counterexample. - Suppose
Xis transformed intoX_new = aX + b, wherea < 0is a strictly negative constant andbis any real number. How does the Pearson correlation coefficientrho(X_new, Y)relate torho(X, Y)?
- Does
Scope & Expectations
- Connect the theoretical
Poissonzero-count probability and mean-equals-variance property to concrete reasons zero-count windows vanish (distinguishing true arrival-rate growth from underdispersion, positive floors, or dropped zero records). - Diagnose how tenure-based sample truncation alters training labels, feature distributions, calibration, and offline validation metrics relative to a Day-1 cohort.
- Contrast linear co-movement (
Cov(X, Y)) with full distributional independence, and show algebraically how location shifts (b) and negative scaling (a < 0) act on the numerator and denominator of Pearson correlation.
Step-by-step walkthrough
Part 1a: What a theoretical Poisson(2) process predicts
A Poisson process models discrete events (such as monitoring alerts) arriving one at a time, independently of one another, at a steady average rate
λper unit time. Its probability mass function (PMF)—the formula giving the exact probability of observingkalerts in a one-hour window—is:P(K = k) = e^(-λ) * λ^k / k! for k = 0, 1, 2, ... Key Poisson identity: Mean(K) = Variance(K) = λPlugging in the historical rate
λ = 2alerts per hour (e^(-2) ≈ 0.1353):Alerts in 1 hour (k): 0 1 2 3 4 5 6+ Theoretical P(K = k): 0.1353 0.2707 0.2707 0.1804 0.0902 0.0361 0.0166Under a genuine
Poisson(2)process, roughly 13.5% of hours (0.1353) record zero alerts—about 13 to 14 quiet hours in every 100 hours monitored (the chance of seeing zero quiet hours across 50 independent hours is(1 - 0.1353)^50 ≈ 0.0007, well under 0.1%). Because a Poisson model has only a single parameter (λ), seeing far fewer zeros than 13.5% means eitherλitself rose, or hourly counts no longer follow a pure Poisson process.Part 1b: Why zero-alert hours vanished—and which parameter shifted
Compare the new empirical distribution against
Poisson(2)by inspecting both the sample mean and the dispersion index (Variance / Mean, which equals1.0for any true Poisson process):Poisson(2) baseline: k=0 [#######] k=1 [##############] k=2..3 [#######################] (mean=2, var=2) Case A (higher λ = 4): k=0 [#] k=1 [####] k=3..5 [########################] (mean=4, var=4) Case B (underdispersed): k=0 [ ] k=1 [########] k=2..3 [########################] (mean=2, var=0.4)- Case A — The arrival rate parameter
λincreased (process remains Poisson): BecauseP(K = 0) = e^(-λ)decays exponentially, higher traffic shrinks zero-count hours rapidly (λ = 4givesP(0) = 1.83%;λ = 5givesP(0) = 0.67%). You confirm this if the sample mean also rose (say from2.0to~4.0) whileVariance ≈ Mean. - Case B — Underdispersion or zero-truncation (mean stays near 2, regularity/floor parameter changed): Underdispersion means
Variance < Mean—hourly counts cluster much more tightly around2than independent random arrivals allow:- Positive floor or zero-truncation: A new synthetic hourly health-check injects
1guaranteed alert every hour (K = 1 + Poisson(1)hasMean = 2,Variance = 1, andP(0) = 0), or an ingestion pipeline drops rows whenever the hourly count is0(zero-truncated Poisson). - Rate-smoothed intake or logging ceiling: If upstream batching paces alerts out evenly instead of letting them arrive independently, generalized count models such as Conway–Maxwell–Poisson
CMP(λ, ν)show an increased dispersion parameterν > 1. Likewise, if a throttling rule caps logged alerts at3per hour (a ceiling), an observed mean of2.0masks a higher underlying rate (λ ≈ 2.35), pullingP(0)down toe^(-2.35) ≈ 9.6%and variance down to1.02.
- Positive floor or zero-truncation: A new synthetic hourly health-check injects
Crucial trap to rule out: Day-versus-night traffic swings averaging
2alerts/hour cannot shrinkP(0). Mixing halfλ = 0.5overnight hours and halfλ = 3.5peak hours keeps the overall mean at(0.5 + 3.5) / 2 = 2.0, yetP(0) = 0.5 * e^(-0.5) + 0.5 * e^(-3.5) ≈ 0.318(31.8% > 13.5%)! Rate variation creates overdispersion (Variance > Mean) and extra zeros, the exact opposite of what appeared here.# Quick diagnostic on 20 observed hourly counts: check BOTH mean and variance / mean counts = [2, 2, 3, 1, 2, 2, 3, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 1, 2, 2] n = len(counts) sample_mean = sum(counts) / n sample_var = sum((c - sample_mean) ** 2 for c in counts) / (n - 1) dispersion_index = sample_var / sample_mean print(f"mean={sample_mean:.2f}, var={sample_var:.2f}, var/mean={dispersion_index:.2f}") # mean=2.00, var=0.42, var/mean=0.21 -> mean stayed 2.00, strong underdispersion (Case B)!- Case A — The arrival rate parameter
Part 2a: Why restricting to 12-month subscribers creates survivorship bias
Training exclusively on accounts that remained active for at least
12months introduces survivorship bias—a form of selection bias in which examples enter the dataset only after surviving a threshold directly tied to the target outcome (known in survival analysis as left truncation).8,000 New Customer Sign-Ups (Target Population at Day 0) | +---> 2,400 cancel during Months 0..12 ---> [EXCLUDED! Never reach 12-month tenure] | +---> 5,600 survive past Month 12 ---> [TRAINING SET: seasoned accounts only!]Excluding everyone who canceled prior to Month 12 distorts the learning problem in three ways:
- Erased early-cancellation labels: Every account that abandoned the platform during initial setup or within its first 11 months is completely absent from training.
- Truncated feature support:
tenure_monthsis strictly>= 12in training, and early-adoption signals (such as"completed_sso_setup"or"invited_team_members") are nearly 100%Trueamong 12-month veterans, masking how strongly those signals separate sticky new customers from early dropouts. - Mismatched cancellation drivers: First-quarter cancellations typically stem from integration friction, missing features, or trial expiration, whereas second-year cancellations reflect budget cuts or vendor consolidation. The classifier learns only late-stage behavior.
Part 2b: Quantifying how the biased classifier fails on newly onboarded accounts
Trace the cohort numbers above: suppose out of
8,000new sign-ups,1,600cancel in Quarter 1 (20%quarterly cancellation rate), another800cancel across Quarters 2–4, and among the5,600accounts reaching Month 12, only4%cancel in any subsequent quarter.Population True Quarterly Cancel Rate What the Model Predicts ------------------------------ -------------------------- --------------------------------------- 12-month survivors (training) 4% ~4% on average (calibrated on veterans) Brand-new sign-ups (production) 20% ~4% (5x under-prediction!)Deploying this model on new sign-ups produces four concrete failures:
- Severe probability miscalibration (systematic under-prediction): Because the classifier learned a
4%baseline risk instead of20%, expected revenue-at-risk forecasts and customer-success staffing plans are underestimated by roughly5×. - Missed high-risk newcomers (low recall): If customer-success outreach fires only when
predicted_cancel_prob > 12%, almost no newly onboarded accounts clear that bar, letting the majority of the1,600first-quarter cancellations slip away unassisted. - Out-of-domain extrapolation: Feeding
tenure_months = 1into a model trained solely ontenure_months >= 12forces linear or neural models to extrapolate far below their training range and pushes tree ensembles to route Day-1 accounts into thetenure == 12split. - Illusory offline validation scores: A standard random 80/20 train/test split taken from the same 12-month survivor snapshot repeats the exact same truncation in the test fold, making offline AUC and calibration curves look deceptively healthy before launch. (Whenever raw historical logs exist, rebuild the dataset from point-in-time cohort snapshots starting at Day 1.)
- Severe probability miscalibration (systematic under-prediction): Because the classifier learned a
Part 3a: Why zero covariance does not guarantee independence
Covariance (
Cov(X, Y) = E[(X - E[X])(Y - E[Y])] = E[XY] - E[X]E[Y]) captures only linear association—whetherYtilts systematically upward or downward along a straight line asXgrows. Statistical independence is a far stricter requirement: observingXprovides zero information of any kind aboutY(P(X = x, Y = y) = P(X = x) * P(Y = y)for every(x, y)).A transparent counterexample lets
Xtake values{-2, 0, +2}with equal probability1/3each, and setsY = X^2:Y 4 | *(-2, 4) *(+2, 4) Best-fit straight line is horizontal (slope = 0), | so negative and positive X tilts cancel in Cov(X, Y)! 0 | *(0, 0) Yet knowing X pins down Y with 100% certainty. +-------------------------------- X -2 0 +2Check both facts directly:
1. Compute Cov(X, Y): E[X] = (-2)*(1/3) + 0*(1/3) + 2*(1/3) = 0 E[XY] = E[X^3] = (-8)*(1/3) + 0*(1/3) + 8*(1/3) = 0 Cov(X, Y) = E[XY] - E[X]*E[Y] = 0 - 0 * (8/3) = 0 2. Disprove independence (check X = 0, Y = 0): Actual joint probability: P(X = 0 and Y = 0) = P(X = 0) = 1/3 Product of marginal probs: P(X = 0) * P(Y = 0) = (1/3) * (1/3) = 1/9 Since 1/3 != 1/9, X and Y are NOT independent!import numpy as np # Equally likely outcomes (-2, 4), (0, 0), (+2, 4) x = np.array([-2.0, 0.0, 2.0]) y = x ** 2 population_cov = float(np.mean(x * y) - np.mean(x) * np.mean(y)) print(population_cov) # 0.0, even though y = x^2 is 100% deterministic!Remember which implication does hold (whenever variances are finite): independence always implies
Cov(X, Y) = 0, and the reverse holds when(X, Y)follow a jointly normal (bivariate Gaussian) distribution.Part 3b: How `X_new = aX + b` (with `a < 0`) changes Pearson correlation
The Pearson correlation coefficient
rho(X, Y)divides covariance by the product of both standard deviations (sd), producing a scale-free measure in[-1, +1]:rho(X, Y) = Cov(X, Y) / (sd(X) * sd(Y))Propagate
X_new = aX + bthrough the numerator and denominator step by step:1. Additive shift `b` cancels out in mean-centered deviations: E[aX + b] = a * E[X] + b (aX + b) - E[aX + b] = (aX + b) - (a * E[X] + b) = a * (X - E[X]) 2. Numerator (covariance scales by `a`, keeping `a`'s negative sign): Cov(aX + b, Y) = E[ a * (X - E[X]) * (Y - E[Y]) ] = a * Cov(X, Y) 3. Denominator (standard deviation is non-negative, so it scales by |a|, NOT `a`!): Var(aX + b) = E[ (a * (X - E[X]))^2 ] = a^2 * Var(X) sd(aX + b) = sqrt(a^2 * Var(X)) = |a| * sd(X) 4. Combine numerator and denominator: rho(aX + b, Y) = (a * Cov(X, Y)) / (|a| * sd(X) * sd(Y)) = (a / |a|) * rho(X, Y)Since
a < 0,|a| = -aanda / |a| = -1. Consequentlyrho(X_new, Y) = -rho(X, Y): the absolute strength is unchanged, the sign reverses, andbhas zero impact.Verify numerically on
X = [1, 2, 4, 5],Y = [2, 3, 7, 8], andX_new = -3X + 12 = [9, 6, 0, -3]:import numpy as np x = np.array([1.0, 2.0, 4.0, 5.0]) y = np.array([2.0, 3.0, 7.0, 8.0]) x_new = -3.0 * x + 12.0 rho_orig = float(np.corrcoef(x, y)[0, 1]) rho_transformed = float(np.corrcoef(x_new, y)[0, 1]) print(round(rho_orig, 4), round(rho_transformed, 4)) # 0.9923 -0.9923
Intuition & how it works
All three scenarios test one core data-science discipline: recognizing what structural detail a single summary statistic or query filter silently discards. A single Poisson rate λ locks the average and the spread together (Mean = Variance = λ), a veteran-only account query erases everyone who canceled early, and covariance projects a two-dimensional relationship onto a single straight-line tilt.
Surface-level intuition misfires whenever you read the headline number without inspecting the distribution or cohort behind it: assuming fewer quiet hours must reflect heavier traffic rather than artificially regular arrivals, trusting high holdout scores on a 12-month-tenure dataset that omitted every first-year cancellation, or treating Cov(X, Y) = 0 as proof that X tells you nothing about Y when Y follows a symmetric U-curve.
Trace each idea on a compact concrete example:
1. Missing Poisson zeros (Part 1): Poisson(2) predicts e^(-2) ≈ 13.5% zero-alert hours. If an hourly synthetic probe adds 1 guaranteed alert onto Poisson(1) (K = 1 + Poisson(1)), the mean stays 2.0, yet P(K = 0) drops to 0% and variance falls from 2.0 to 1.0 (underdispersion).
2. Survivorship bias (Part 2): Out of 100 new accounts, if 30 cancel before Month 12 and only 3 of the 70 veterans cancel in the next quarter, training solely on Month-12 survivors teaches a 3 / 70 ≈ 4.3% baseline rate instead of the steep early-cohort risk.
3. Covariance & affine scaling (Part 3): Across (-2, 4), (0, 0), (+2, 4), negative and positive slopes cancel (Cov = 0) even though Y = X^2; meanwhile mapping X to X_new = -3X + 12 reflects the point cloud horizontally and shifts its center, preserving linear tightness while flipping +rho to -rho.
Key points
- Poisson(2) baseline and diagnosing missing zeros: Under
Poisson(λ),P(K = 0) = e^(-λ)(13.53%atλ = 2) andMean = Variance = λ. A sharp drop in zero-count windows means either the arrival rateλgrew (sample mean rose above2withVariance / Mean ≈ 1) or counts became underdispersed / zero-truncated (sample mean stayed near2withVariance / Mean < 1, driven by a positive floor like synthetic checks, dropped zero-count records, rate-smoothed batching, or a logging ceiling). - Rate swings across hours produce more zeros, never fewer: By Jensen's inequality (averaging a convex curve such as
e^(-λ)across varying rates lands abovee^(-mean(λ))), mixing quiet (λ = 0.5) and busy (λ = 3.5) hours with mean2.0liftsP(0)from13.5%to31.8%. - Part 2 introduces survivorship bias (left truncation): Requiring
tenure >= 12 monthsconditions inclusion on surviving the entire first year, stripping out early-cancellation labels, hidingtenure < 12feature behavior, and severely under-predicting risk on new cohorts even when survivor-only test splits look strong. Cov(X, Y) = 0rules out linear tilt, not nonlinear dependence: Symmetric pairings such asXuniform on{-2, 0, +2}withY = X^2giveCov(X, Y) = 0whileYis 100% determined byX. Zero correlation implies independence reliably when(X, Y)are jointly normal (bivariate Gaussian).rho(aX + b, Y) = sign(a) * rho(X, Y)for anya != 0: Addingbshifts observations and mean equally (canceling inX - E[X]), whereas multiplying bya < 0multipliesCovbyaandsd(X)by|a| = -a, leavinga / |a| = -1sorhoflips sign with identical magnitude.
Common mistakes
- Concluding
λrose in Part 1 without checking whether the sample mean actually increased. If the hourly average remained2.0while zeros disappeared,λdid not jump to4—the independent, unbounded Poisson assumptions broke down. - Attributing missing zeros to peak-vs.-off-peak traffic variation. Changing arrival rates induce overdispersion (
Variance > Mean) and increaseP(K = 0). - Calling Part 2 "class imbalance" and reaching for SMOTE / oversampling. Duplicating Month-13 cancellations only clones veteran cancellation patterns; it cannot reconstruct first-month onboarding drop-offs absent from the table.
- Claiming separate normal marginals plus
Cov(X, Y) = 0guarantee independence.(X, Y)must be jointly normal—ifX ~ N(0, 1)andSis a fair±1coin flip,Y = S * Xis marginallyN(0, 1)withCov(X, Y) = 0, yet|Y| = |X|. - Dropping the absolute value in
sd(aX + b) = |a| * sd(X). Writingsd(aX + b) = a * sd(X)cancelsa / a = +1and misses the sign reversal fora < 0; writingrho_new = a * rhoviolates-1 <= rho <= 1.
Follow-up questions
- When count data exhibits variance far exceeding its mean, why does standard Poisson regression break down and which alternative regression models address it? Variance exceeding the mean is overdispersion, and fitting ordinary Poisson regression underestimates parameter standard errors and inflates false-positive significance because the Poisson likelihood forces
Var(Y | X) = μ. Replace it with Negative Binomial regression, which models each unit's Poisson rate with a Gamma prior around meanμ, introducing a quadratic variance termVar(Y | X) = μ + α * μ^2(α > 0) that absorbs burstiness or unobserved customer heterogeneity. Depending on the mechanism, Quasi-Poisson preserves the Poisson mean equation while scaling variance byφ * μto correct confidence intervals, whereas Zero-Inflated Poisson or Negative Binomial (ZIP / ZINB) fits best when excess variance stems from a structural spike atk = 0. - Suppose historical records for accounts that canceled early were purged—what practical steps can reduce the resulting survivorship bias for new-cohort scoring? First, immediately begin recording point-in-time daily or weekly snapshots for every new sign-up alongside fast early proxy labels (such as 14-day or 30-day inactivity) so an unbiased early-tenure training set builds up rapidly. Second, in the interim, score
tenure < 12 monthsaccounts with a separate rule set or anomaly-detection baseline derived from the preserved early-month activity logs of current veterans (flagging newcomers whose Week-1 usage trails far behind healthy veterans' Week-1 trajectories) instead of passingtenure = 1into the veteran model. Third, if finance reports still retain the aggregate early-cancellation base rate (sayπ_new = 20%vs.π_train = 4%), apply a prior-odds recalibration—multiplying predicted oddsp / (1 - p)by(0.20 / 0.80) / (0.04 / 0.96) = 6.0—as a temporary calibration adjustment while noting its assumption that conditional feature patterns match across tenures. - How is the ordinary least squares slope when regressing Y on X algebraically linked to the Pearson correlation coefficient? In ordinary least squares (OLS) simple linear regression (choosing intercept
β_0and slopeβ_1inŶ = β_0 + β_1 * Xto minimize squared vertical residualsΣ(y_i - β_0 - β_1 * x_i)^2), setting the partial derivatives with respect toβ_0andβ_1to zero givesβ_0 = mean(Y) - β_1 * mean(X)andβ_1 = Cov(X, Y) / Var(X). BecauseVar(X) = sd(X)^2andrho(X, Y) = Cov(X, Y) / (sd(X) * sd(Y)), substitutingCov(X, Y) = rho(X, Y) * sd(X) * sd(Y)cancels onesd(X)factor and yieldsβ_1 = rho(X, Y) * (sd(Y) / sd(X)). In plain words, each1-standard-deviation increase inXpredicts arho-standard-deviation shift inY(onX = [1, 2, 4, 5], Y = [2, 3, 7, 8],rho = 0.9923andsd(Y) / sd(X) = 1.6125, givingβ_1 = 0.9923 * 1.6125 = 1.6), andrho^2equals the regression'sR^2.
Follow-up questions
- When count data exhibits variance far exceeding its mean, why does standard Poisson regression break down and which alternative regression models address it?
- Suppose historical records for accounts that canceled early were purged—what practical steps can reduce the resulting survivorship bias for new-cohort scoring?
- How is the ordinary least squares slope when regressing Y on X algebraically linked to the Pearson correlation coefficient?
Similar questions
- Minimum Cost to Combine Numbers
- First-Player Win Odds in Alternating Coin Flips
- Valid Letter Decodings for Numeric Strings
- End-to-End Analytics and Visualization Workflow
- Approximating Black-Scholes Greeks and Hedged PnL
- Forward Contracts vs. Options Fundamentals
More Morgan Stanley interview questions
- Approximating Black-Scholes Greeks and Hedged PnL Medium
- Crude Oil Tail-Risk Modeling and Probability Puzzles Medium
- Minimum Cost to Combine Numbers Medium Pro
- First-Player Win Odds in Alternating Coin Flips Easy Pro
- Valid Letter Decodings for Numeric Strings Medium Pro
- End-to-End Analytics and Visualization Workflow Medium Pro
- Presenting a Risk Modeling Project in a Recruiter Screen Medium Pro
- Forward Contracts vs. Options Fundamentals Easy Pro
- Factorial and Integer Squares Medium Pro
- Financial Technology Onsite Prompts: Motivation, Integrity, and Industry Shifts Medium Pro