Session-Based Account Risk Scoring with Bayesian Updates
Arrays & HashingAuto-graded · 2 test casesLast updated
Tests probabilistic modeling with the Binomial distribution, Bayes' theorem, two-stage classification pipelines, and F1-optimal threshold selection in a risk-scoring context.
Session-Based Account Risk Scoring with Bayesian Updates
A trust and safety team monitors user accounts by observing behavior across independent sessions. Your task is to build a complete probabilistic model of their detection pipeline and answer a series of questions about its performance.
Setup
Each account generates n = 5 independent sessions in a given observation window. In each session, a suspicious event occurs with probability:
- p_R = 0.5 if the account is a risk account (bad actor)
- p_L = 0.05 if the account is legitimate
The prior probability that any given account is a risk account is π = 0.03 (3%).
Let X be the count of suspicious sessions for a given account. Then:
- X | risk ~ Binomial(5, 0.5)
- X | legitimate ~ Binomial(5, 0.05)
An account is flagged whenever X ≥ k for some threshold k.
Part A — Detection rates at k = 2
Using the Binomial distribution, compute:
- TPR = P(flag | risk account) = P(X ≥ 2 | p = 0.5)
- FPR = P(flag | legitimate account) = P(X ≥ 2 | p = 0.05)
Part B — Posterior probabilities via Bayes' theorem
Still using k = 2, apply Bayes' theorem to compute:
- PPV = P(risk | flagged)
- NPV = P(legitimate | not flagged)
Part C — Adding a human review stage
Flagged accounts are sent to a human reviewer who operates independently of the automated rule (conditional on the true account type). The reviewer has:
- Sensitivity = 0.90 (correctly identifies a risk account 90% of the time)
- Specificity = 0.98 (correctly clears a legitimate account 98% of the time)
An account is actioned only when both the rule flags it and the reviewer calls it a risk account. Compute the combined pipeline's TPR, FPR, and revised PPV.
Part D — Absolute counts for a large population
For a population of 1,000,000 accounts processed through the full two-stage pipeline from Part C, compute the expected number of:
- True positives (risk accounts that are actioned)
- False positives (legitimate accounts that are actioned)
- True negatives (legitimate accounts that are not actioned)
- False negatives (risk accounts that are not actioned)
Part E — Threshold selection by F1 score (rule only, no reviewer)
Without the human review stage, evaluate k ∈ {1, 2, 3, 4, 5} and compute the F1 score at the prior π = 0.03 for each. Then repeat for π = 0.10. Report the optimal k under each prior.
The F1 score should be computed from population-level expected counts:
F1 = 2·TP / (2·TP + FP + FN)
where TP = π · TPR, FP = (1 − π) · FPR, FN = π · (1 − TPR).
Part F — Error taxonomy
Identify which errors in Parts A–E correspond to Type I errors and which correspond to Type II errors, using H₀ = "the account is legitimate."
Output format
Return a single dictionary with exactly these keys:
{
"binomial_formulas": {
"tail": <string describing the tail-sum formula>,
"tpr_k2": <string describing how TPR at k=2 is computed>,
"fpr_k2": <string describing how FPR at k=2 is computed>
},
"part_a": {"tpr": <float>, "fpr": <float>},
"part_b": {"ppv": <float>, "npv": <float>},
"part_c": {"overall_tpr": <float>, "overall_fpr": <float>, "revised_ppv": <float>},
"part_d": {
"true_positives": <float>,
"false_positives": <float>,
"true_negatives": <float>,
"false_negatives": <float>
},
"part_e": {
"f1_by_k_at_3_percent": {1: <float>, 2: <float>, 3: <float>, 4: <float>, 5: <float>},
"optimal_k_at_3_percent": <int>,
"f1_by_k_at_10_percent": {1: <float>, 2: <float>, 3: <float>, 4: <float>, 5: <float>},
"optimal_k_at_10_percent": <int>
},
"part_f": {
"type_i": <string>,
"type_ii": <string>
}
}
The f1_by_k_* dictionaries use integer keys (not strings).
Constraints
- n = 5 sessions per account (fixed)
- p_R = 0.5, p_L = 0.05 (fixed session-level probabilities)
- Prior π = 0.03 for all parts except the π = 0.10 scenario in Part E
- Reviewer sensitivity = 0.90, specificity = 0.98 (Parts C and D only)
- Population size = 1,000,000 (Part D only)
- Threshold k ranges over {1, 2, 3, 4, 5} in Part E
- The reviewer's errors are conditionally independent of the rule's errors given the true account type
- All floating-point results should be computed without manual rounding; return full-precision Python floats
- The
binomial_formulasstrings must match the exact wording shown in the sample output
Examples
Example 1
Input: account_risk_scoring_metrics()
Output: {'binomial_formulas': {'tail': 'P(X >= k) = sum_{j=k}^{5} C(5,j) p^j (1-p)^(5-j)', 'tpr_k2': 'P(X >= 2 | fake), with p=0.5', 'fpr_k2': 'P(X >= 2 | authentic), with p=0.05'}, 'part_a': {'tpr': 0.8125, 'fpr': 0.0225925}, 'part_b': {'ppv': 0.5265747420188821, 'npv': 0.994101982386632}, 'part_c': {'overall_tpr': 0.7312500000000001, 'overall_fpr': 0.00045185000000000044, 'revised_ppv': 0.9804121145284919}, 'part_d': {'true_positives': 21937.500000000004, 'false_positives': 438.2945000000004, 'true_negatives': 969561.7054999999, 'false_negatives': 8062.499999999998}, 'part_e': {'f1_by_k_at_3_percent': {'1': 0.20871111494521163, '2': 0.6390113478584436, '3': 0.6504293307854571, '4': 0.3155317340782687, '5': 0.060605466794921306}, 'optimal_k_at_3_percent': 3, 'f1_by_k_at_10_percent': {'1': 0.48380392238567776, '2': 0.8061185639183812, '3': 0.6620661346137693, '4': 0.31571768945166157, '5': 0.060605895317255194}, 'optimal_k_at_10_percent': 2}, 'part_f': {'type_i': 'False positive: an authentic account is flagged/actioned as fake.', 'type_ii': 'False negative: a fake account is not flagged/actioned.'}}
Hints
Hint 1
Start by computing the full Binomial PMF for both p = 0.5 and p = 0.05 once. Every TPR and FPR value is a tail sum of those PMFs, and you will need them in both Part A and Part E.
Hint 2
For the two-stage pipeline in Part C, the key insight is that the combined rates multiply: overall_TPR = rule_TPR × reviewer_sensitivity, and overall_FPR = rule_FPR × (1 − reviewer_specificity). This follows from the conditional independence assumption stated in the problem.
Hint 3
When comparing optimal k values between π = 0.03 and π = 0.10 in Part E, notice that F1 depends on both precision and recall. A higher base rate means false positives become relatively less costly compared to false negatives, which shifts the optimal threshold toward a looser (smaller k) cutoff.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The whole problem is built on two primitives: the Binomial tail sum and Bayes' theorem. Once you have those, every part is a composition of simple arithmetic.
Binomial tail sum
For a fixed number of sessions n = 5 and a session-level probability p, the probability of observing at least k suspicious sessions is:
P(X >= k) = sum_{j=k}^{5} C(5, j) * p^j * (1-p)^(5-j)
Compute this once for p = 0.5 (risk accounts) and once for p = 0.05 (legitimate accounts). Every TPR and FPR value in the problem is a tail sum of one of these two distributions.
Part A
For k = 2:
- TPR = P(X >= 2 | p = 0.5) = 1 − P(X=0) − P(X=1) = 1 − 1/32 − 5/32 = 0.8125
- FPR = P(X >= 2 | p = 0.05) ≈ 0.02259
Part B
Apply Bayes' theorem directly. The joint probability of being a risk account and being flagged is π × TPR. Divide by the total flagging probability (marginalizing over both account types) to get PPV. Mirror the calculation for the unflagged side to get NPV.
- PPV ≈ 0.527 — only about half of flagged accounts are actually risky, because the 97% legitimate majority generates a large absolute number of false alarms even at a 2.3% FPR.
- NPV ≈ 0.994
Part C
Because the reviewer's errors are conditionally independent of the rule's errors given the true account type, the two-stage "AND" rates simply multiply:
- combined TPR = rule TPR × reviewer sensitivity = 0.8125 × 0.90 ≈ 0.731
- combined FPR = rule FPR × (1 − reviewer specificity) = 0.02259 × 0.02 ≈ 0.000452
Re-applying Bayes with these new rates gives a revised PPV of about 0.980. Precision nearly doubles at the cost of a modest recall drop — the expected behavior of a serial AND pipeline.
Part D
Multiply the population of 1,000,000 by the class sizes and the combined pipeline rates:
| Actioned | Not actioned | |
|---|---|---|
| Risk (30,000) | TP ≈ 21,938 | FN ≈ 8,063 |
| Legitimate (970,000) | FP ≈ 438 | TN ≈ 969,562 |
Part E
F1 is computed from expected population fractions — no need for actual counts:
F1(k) = 2·π·TPR(k) / (2·π·TPR(k) + (1−π)·FPR(k) + π·(1−TPR(k)))
At π = 0.03, k = 3 wins narrowly (F1 ≈ 0.650 vs 0.639 for k = 2). The gain from tightening the threshold just enough to slash FPR outweighs the recall loss. At π = 0.10, the optimum shifts to k = 2 because the larger risk population makes each missed true positive more costly relative to the false alarms gained by loosening the threshold.
Part F
With H₀ = "account is legitimate":
- Type I error = false positive (a legitimate account is actioned). Rate = FPR.
- Type II error = false negative (a risk account escapes detection). Rate = 1 − TPR.
Note: PPV and NPV are posterior quantities that depend on the base rate. They are not the same as α and β and should not be conflated with Type I / Type II error rates.
Correctness and complexity
The solution is a closed-form calculation with no iteration beyond the k = 1 to 5 loop and the j = 0 to 5 inner sum. Time complexity is O(1) (fixed small constants). Space complexity is O(1) for the same reason.
from math import comb
from typing import Dict
def account_risk_scoring_metrics() -> Dict[str, object]:
# Fixed parameters
n = 5
prior_risk = 0.03
p_risk = 0.5
p_legit = 0.05
reviewer_sensitivity = 0.90
reviewer_specificity = 0.98
# Binomial tail sum: P(X >= k) for a given session probability p
def binomial_tail(p, k):
return sum(comb(n, j) * p**j * (1 - p)**(n - j) for j in range(k, n + 1))
# F1 at a given threshold k and prevalence, using rule only (no reviewer)
def f1_for_prior(k, prevalence):
tpr = binomial_tail(p_risk, k)
fpr = binomial_tail(p_legit, k)
tp = prevalence * tpr
fp = (1 - prevalence) * fpr
fn = prevalence * (1 - tpr)
return 2 * tp / (2 * tp + fp + fn)
# --- Part A: TPR and FPR at k = 2 ---
tpr = binomial_tail(p_risk, 2)
fpr = binomial_tail(p_legit, 2)
# --- Part B: PPV and NPV via Bayes' theorem ---
ppv = prior_risk * tpr / (prior_risk * tpr + (1 - prior_risk) * fpr)
npv = (1 - prior_risk) * (1 - fpr) / (
(1 - prior_risk) * (1 - fpr) + prior_risk * (1 - tpr)
)
# --- Part C: Two-stage pipeline (rule AND reviewer) ---
overall_tpr = tpr * reviewer_sensitivity
overall_fpr = fpr * (1 - reviewer_specificity)
revised_ppv = prior_risk * overall_tpr / (
prior_risk * overall_tpr + (1 - prior_risk) * overall_fpr
)
# --- Part D: Expected counts in a population of 1,000,000 ---
population = 1_000_000
tp_count = population * prior_risk * overall_tpr
fp_count = population * (1 - prior_risk) * overall_fpr
tn_count = population * (1 - prior_risk) * (1 - overall_fpr)
fn_count = population * prior_risk * (1 - overall_tpr)
# --- Part E: Optimal k by F1 at two different priors ---
f1_by_k_3_percent = {k: f1_for_prior(k, 0.03) for k in range(1, 6)}
f1_by_k_10_percent = {k: f1_for_prior(k, 0.10) for k in range(1, 6)}
return {
"binomial_formulas": {
"tail": "P(X >= k) = sum_{j=k}^{5} C(5,j) p^j (1-p)^(5-j)",
"tpr_k2": "P(X >= 2 | fake), with p=0.5",
"fpr_k2": "P(X >= 2 | authentic), with p=0.05"
},
"part_a": {"tpr": tpr, "fpr": fpr},
"part_b": {"ppv": ppv, "npv": npv},
"part_c": {
"overall_tpr": overall_tpr,
"overall_fpr": overall_fpr,
"revised_ppv": revised_ppv
},
"part_d": {
"true_positives": tp_count,
"false_positives": fp_count,
"true_negatives": tn_count,
"false_negatives": fn_count
},
"part_e": {
"f1_by_k_at_3_percent": f1_by_k_3_percent,
"optimal_k_at_3_percent": max(f1_by_k_3_percent, key=f1_by_k_3_percent.get),
"f1_by_k_at_10_percent": f1_by_k_10_percent,
"optimal_k_at_10_percent": max(f1_by_k_10_percent, key=f1_by_k_10_percent.get)
},
"part_f": {
"type_i": "False positive: an authentic account is flagged/actioned as fake.",
"type_ii": "False negative: a fake account is not flagged/actioned."
}
}