Rescuing a Rare-Event Image Flagger That Predicts Only "Safe"
Machine LearningModel answerLast updated
A logistic regression flagger for rare harmful uploads shows high accuracy but no detections, sparse ID features, and uneven regional quality. Lay out a plan to diagnose and repair it.
Scenario
Your team is building a trust-and-safety classifier that decides whether an uploaded image breaks content policy. The training set holds 1 million labeled images. The label is_violation is 1 for a violation and 0 for a safe image, and only 0.5% of images are violations.
The first version is a logistic regression trained on:
- raw pixel intensities, and
- a few metadata fields, such as
upload_locationanddevice_id.
Observed problems
- Reported accuracy is 99.5%, yet the model flags no violating images.
device_idhas thousands of distinct values, so the encoded feature matrix is extremely sparse.- Stakeholders report that quality is clearly worse for uploads from certain regions.
What to deliver
Describe a complete plan to diagnose and improve the model. Cover:
- How you would resolve the zero-recall behavior and which evaluation metrics you would adopt instead of accuracy.
- How you would treat high-cardinality categorical features such as
device_id. - How you would investigate and reduce the performance gap across regions, including how you would tell a proxy-feature effect from a genuine data problem.
- How you would scale and transform the features so that logistic regression trains stably and converges.
Explain your reasoning and trade-offs, and say what you would check first.
Hints
Hint 1
Compute what a model that always answers 'safe' would score on accuracy, then think about a metric that does not depend on a threshold (for example, average precision) to find out whether the model ranks positives well at all.
Hint 2
A device seen three times with one violation should not be trusted as a 33% risk. Think about shrinkage toward the global rate, computing encodings without using a row's own label, and whether the feature is just a stand-in for region.
Hint 3
Before mitigating the regional gap, slice the evaluation by region with confidence intervals, then retrain without the suspect features and with content-only features to separate proxy effects from data coverage or label-quality issues.
Hint 4
Raw pixels are a poor input for a linear model: they are highly correlated and carry no semantic structure. Consider pretrained image embeddings, scaling fitted on training data only, regularization, and an appropriate solver.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overall approach
The four symptoms come from different layers, so I would handle them in this order: (1) is the problem the metric or the model, (2) fix the input representation, (3) examine fairness by slice, (4) lock down calibration and monitoring.
1. Zero recall and the right metrics
Why accuracy looks great. A constant "safe" prediction scores 99.5% when 0.5% of items are violations. The model has collapsed to the base rate, and accuracy carries no information here.
Separate ranking from thresholding. Compute PR-AUC (average precision) on a held-out set.
- If it is near 0.005, the model has learned no signal. Thresholds and weights will not help, and the features are the problem (see section 4).
- If it is well above 0.005, the ranking is useful and the default 0.5 cutoff is simply too high for a rare class.
Metrics to report.
- PR-AUC as the main offline number. ROC-AUC is misleading at roughly 199:1 imbalance, because the false-positive rate stays tiny even when reviewers drown in false alarms.
- Recall at a fixed precision, or precision@k with k equal to daily human-review capacity. This ties directly to operations.
- F-beta with beta > 1 if a single number is needed and misses cost more than false flags.
Fixes.
- Threshold tuning on a validation set to hit the precision or recall target. Logistic regression's ranking is unchanged by the threshold, so this is often enough.
- Class weights. Weighting positives by about 199 balances total class weight and moves the intercept away from "always negative". Re-check convergence afterward, since weights rescale the loss.
- Negative downsampling (for example, keep 10% of negatives) for faster training. Probabilities must then be corrected, or recalibrated on an untouched validation set.
Validation. Use stratified or, better, time-based splits. With only about 5,000 positives overall, report bootstrap confidence intervals.
2. High-cardinality categoricals
One-hot device_id yields thousands of columns, most with zero or one positive. Coefficients overfit or diverge, and unseen devices get nothing.
In rough order of preference:
- Question the feature. An ID can memorize repeat offenders (legitimate) but can also leak or proxy for region.
- Frequency bucketing. Keep the top N values, map the rest to
OTHER, and reserveUNKNOWNfor unseen IDs. - Smoothed target encoding,
enc = (n * mean_cat + m * mean_global) / (n + m). Smoothing matters: 1 violation in 3 uploads would otherwise encode as 33% against a 0.5% base rate. Compute it out-of-fold or from strictly earlier data to avoid leakage. - Hashing trick for fixed width and unseen-value handling, accepting collisions.
- Behavioral aggregates instead of IDs: device age, upload count, historical violation rate, all computed point-in-time.
- Embeddings if you move to a neural model.
Always combine these with L2 or L1 regularization.
3. Regional disparity
Measure first. For each region report sample size, positives count, base rate, PR-AUC, precision and recall at the global threshold, and calibration, with confidence intervals. A region with 40 positives can look bad by chance.
Find the cause.
- Covariate shift: different devices, image styles, embedded languages, or cultural content.
- Label issues: inconsistent annotation or different base rates. Audit by re-labeling a sample.
- Under-representation: too few training examples from the region.
- Proxy features:
upload_locationanddevice_idmay encode region.
Proxy vs. genuine data problem.
- Ablation: retrain without location, device, and correlated fields. If the gap shrinks, a proxy was driving it.
- Content-only model: if the gap persists with image features alone, suspect base rates, label quality, or coverage.
- Proxy strength: measure how well each feature predicts region (for example, mutual information).
- Matched comparison: compare errors on content-similar images across regions.
Mitigations. Targeted data collection and labeling, region-aware reweighting, removing or regularizing proxy features, and per-slice monitoring. Per-region thresholds are possible, but equalizing recall versus equalizing precision are different fairness goals, so this needs product and legal agreement.
4. Scaling, transformation, convergence
The biggest modeling flaw is raw pixels in a linear model. Pixels are not translation-invariant, neighbors are highly collinear (ill-conditioned optimization), and a linear boundary in pixel space cannot capture semantics.
- Replace pixels with pretrained vision embeddings (CNN or ViT, roughly 512-2048 dimensions) and fit logistic regression on those plus metadata. If pixels are unavoidable, scale to [0, 1] and apply PCA.
- Dense features: standardize, fitting the scaler on training data only.
- Sparse features: use MaxAbs scaling, never mean-centering, which destroys sparsity.
- Regularization: L2 prevents divergence under quasi-separation from rare one-hot categories. Tune C on PR-AUC.
- Solver: lbfgs for dense, saga or liblinear for large sparse data. Increase
max_iterand treat convergence warnings as failures.
Common mistakes
- Celebrating accuracy or ROC-AUC on a 0.5% problem.
- Target-encoding on the full training set (leakage).
- Fitting scalers or encoders before the train/validation split.
- Applying class weights or downsampling and forgetting that probabilities are now miscalibrated.
- Equalizing metrics across regions without checking whether the cause is label quality.
Priority summary
- Compute PR-AUC to determine whether signal exists.
- Swap pixels for embeddings, add regularization and scaling.
- Encode device information safely, or replace it with behavioral features.
- Tune the threshold and weights to the review budget, and recalibrate.
- Slice by region, run ablations, and add monitoring.