URL Safety Classifier with Imbalanced Data
Machine LearningModel answerLast updated
Design and evaluate a classifier to identify malicious URLs given limited labeled examples and severe class imbalance.
You need to build a classifier that identifies malicious URLs. You have access to 1,000 labeled URLs (marked as either malicious or safe), plus a larger collection of unlabeled URLs. Malicious links are uncommon in your dataset.
Your task is to:
- Design a feature set for URL classification
- Train a logistic regression model and explain your approach to handling class imbalance
- Define an evaluation strategy appropriate for imbalanced data, including:
- Cross-validation approach
- Appropriate metrics and why standard accuracy is insufficient
- Model calibration assessment
- Select an operating threshold when blocking a safe URL costs 1 unit but allowing a malicious URL through costs 50 units
- Address potential pitfalls including data leakage, distribution shift between labeled and production data, and planning for deployment validation
Explain your reasoning at each step, including what questions you would ask stakeholders and what tradeoffs you're making.
Hints
Hint 1
With potentially only 10-100 malicious examples, feature dimensionality and validation strategy need careful consideration
Hint 2
Class imbalance affects which metrics are meaningful - consider what happens if you predict every URL as safe
Hint 3
The cost asymmetry should directly inform your decision threshold, not just your training procedure
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: URL Safety Classifier
Initial Clarification
Before building anything, I need to understand the problem constraints:
Data characteristics:
- What's the malicious rate in our labeled set versus real traffic? Labeled data often overrepresents positives (perhaps 5% malicious) while production might see 0.1%.
- How were labels obtained? Manual review, blocklists, user reports? This affects leakage risk.
Business context:
- What action follows a malicious prediction? Immediate block, warning page, or human review queue?
- Are the costs (50:1) firm, or should we validate them with historical incident data?
- What latency constraints exist? Can we fetch page content or make DNS queries, or must we work from URL strings only?
These answers fundamentally shape the solution.
Feature Engineering
With perhaps only 20-80 malicious examples, I'll keep features compact to avoid overfitting:
URL structure features:
- Length metrics: total characters, path depth, subdomain count
- Character composition: digit ratio, special character counts (hyphens, underscores, @-signs)
- Entropy of hostname (random strings suggest generated domains)
- Presence of IP address instead of domain name
- Suspicious keywords in path (
login,verify,account,update)
Domain properties:
- TLD category (common vs obscure)
- Punycode/IDN homograph detection
- Edit distance to popular brand domains (typosquatting detection)
- Domain age from WHOIS (if latency permits)
- HTTPS availability
Network reputation (if feasible):
- Autonomous system reputation
- Hosting provider category
- DNS time-to-live values
Preprocessing:
- Log-transform and standardize continuous features
- Use L2 regularization with logistic regression to prevent overfitting
- Keep total features under 50 given our sample size
Handling Class Imbalance
Training approach:
I'll train logistic regression without aggressive resampling or class weights initially. Here's why:
- Undersampling discards precious negative examples we need for generalization
- Oversampling (SMOTE) creates synthetic URLs that may not reflect real attack patterns
- Heavy class weights primarily shift the intercept and harm calibration
Instead, I'll address imbalance through threshold selection after training a calibrated model. If needed, light class weights (e.g., sqrt of the imbalance ratio) can help without severe miscalibration.
Evaluation Strategy
Cross-validation:
Use stratified 5-fold cross-validation with repeated splits (10 repetitions). Stratification ensures each fold contains malicious examples. Repetition provides confidence intervals since individual splits are noisy with few positives.
Critical: Group by registered domain (eTLD+1) during splitting. Phishing campaigns generate many URLs on one domain—random splitting would let the model memorize domains rather than learn patterns.
Why accuracy fails:
At 1% prevalence, predicting "safe" for everything achieves 99% accuracy while catching nothing. Accuracy is dominated by the majority class and ignores our asymmetric costs.
Appropriate metrics:
-
ROC-AUC: Measures ranking quality independent of threshold. However, under extreme imbalance it can appear excellent (0.95+) even when precision is poor, since false positive rate divides by the massive negative count.
-
Precision-Recall AUC: More informative for imbalanced data. Its random baseline equals prevalence, making poor performance obvious. Reports precision directly—what fraction of flags are real threats.
-
Operating point metrics: Precision at specific recall levels (e.g., 80% recall), or recall at fixed false positive rates.
Key: Adjust metrics for production prevalence. If trained at 5% malicious but production sees 0.1%, recalculate precision using:
precision_prod = (TPR × π_prod) / (TPR × π_prod + FPR × (1 - π_prod))
Calibration assessment:
Plot reliability diagrams on out-of-fold predictions. Bin predicted probabilities (5-10 bins given limited positives) and compare predicted versus observed malicious rates. Report Brier score and log-loss.
Good calibration is essential because our threshold decision assumes probabilities reflect true likelihoods. If calibration is poor, apply Platt scaling on held-out data.
Threshold Selection
With asymmetric costs (FN_cost = 50, FP_cost = 1), the optimal threshold minimizes expected loss.
For a calibrated probability p, flag when:
p × 50 > (1 - p) × 1
Solving: threshold = 1/(1+50) ≈ 0.0196
This means we flag URLs with just 2% predicted malicious probability—the high cost of missed threats justifies many false alarms.
Empirical validation:
Sweep thresholds on validation predictions and compute:
Total_cost(t) = 50 × FalseNegatives(t) + 1 × FalsePositives(t)
weighted to production prevalence. This empirical minimum should match the analytical threshold if calibration is good.
Also consider operational constraints: if human review can handle only N items daily, select the threshold that stays within capacity while minimizing cost.
Addressing Data Leakage
Domain memorization: Phishing kits generate hundreds of URLs per domain. Use grouped cross-validation by domain, not random splitting.
Feature leakage: If labels came from a blocklist, don't use "domain on blocklist" as a feature—that's the label itself. Similarly, reputation scores computed after labeling may reflect the labels.
Temporal leakage: Domain age and reputation should be computed as of label time, not present day. Use a time-based holdout (train on older, validate on newer) as a final check.
Preprocessing leakage: Fit all transformations (scaling, encoding) inside CV folds using pipelines.
Sanity checks: Suspiciously high AUC (>0.99) suggests leakage. Inspect top-weighted features. Run a permutation test (shuffle labels)—AUC should drop to ~0.5.
Distribution Shift and Deployment
Detecting labeled-vs-production shift:
Use adversarial validation: train a classifier to distinguish labeled URLs from production URLs. If AUC is far from 0.5, the distributions differ. Inspect which features differ most—these might break in production.
Using unlabeled data:
Semi-supervised approaches can help but require care:
- Pseudo-labeling: predict on unlabeled data with high confidence, add to training. Risk: amplifies model biases.
- Active learning: select uncertain or diverse examples from unlabeled pool for human labeling.
Deployment validation:
-
Shadow mode: Run the model alongside the existing system without taking action. Compare decisions and track disagreements.
-
Canary deployment: Route a small percentage (1-5%) of traffic through the new model. Monitor downstream metrics (user reports, security incidents).
-
Gradual rollout: Increase traffic percentage while monitoring.
Ongoing monitoring:
- Track prediction distribution drift (mean score, score histogram)
- Monitor precision through sampled manual review
- Alert on feature distribution changes (e.g., sudden TLD shift)
- Track operating metrics: block rate, false positive reports, missed malicious URLs (from incident reports)
- Retrain regularly with new labels, especially recent production examples
Common Mistakes to Avoid
- Using accuracy as the primary metric
- Random CV splits instead of grouped/stratified
- Not adjusting for production prevalence when computing metrics
- Applying class weights without recalibration
- Training on all data then evaluating (no true holdout)
- Ignoring the unlabeled pool entirely
- Setting threshold by maximizing F1 instead of minimizing actual cost
- Not validating calibration before using probability-based thresholds
Summary
This problem tests judgment under data scarcity. The core insight: with ~50 positive examples, every decision—from feature count to validation scheme to threshold selection—must account for limited signal. Success requires moving beyond default ML practices to principled handling of imbalance, careful leakage prevention, and explicit modeling of deployment risks and business costs.