60 Mins

Milestone 2: Validation Framework Setup

Stratified Validation & Threshold Calibration

Scenario Description: The Casford telemetry processing layer is now operational. However, our initial analysis indicates that critical structural anomalies comprise fewer than 5% of all streaming log entries. This severe class imbalance risks highly deceptive metric readings: a naive classifier predicting 'no anomaly' achieves 95% accuracy while failing to detect critical system failures. Your task in this Milestone is to build and run a production-ready, stratified cross-validation pipeline in the Casford Analytics Engine to evaluate models without telemetry leakage.

Mission Objectives: First, you must ingest simulated imbalanced Casford telemetry records. Second, set up a Stratified K-Fold partition (k=5) to ensure each evaluation fold preserves class distributions. Third, track and compile out-of-fold probability predictions. Fourth, construct a threshold-moving analysis that sweeps decision boundaries from 0.05 to 0.95, locating the optimal threshold that maximizes the F2-score to protect our physical assets.

Goals & Requirements: To pass this milestone, your validation system must: (a) Perform stratified splitting without data leakage; (b) Compute fold-by-fold validation performance metrics; (c) Compute out-of-fold probability predictions; and (d) Output the exact calibrated decision boundary that maximizes the macro/micro F2-score.

Practical Hints: • Make sure to set a fixed random state on both the StratifiedKFold object and the Random Forest estimator for test execution reproducibility. • Generate out-of-fold predictions using validation index mappings to prevent leaking training targets into validation checks. • Use the fbeta_score function from scikit-learn with the beta parameter set to 2.0 to prioritize capturing anomalies.

Operator Note: In physical anomaly monitoring, False Negatives (missing a structural fault) are significantly costlier than False Positives. An F2-score places twice the emphasis on Recall compared to Precision.
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import fbeta_score, precision_score, recall_score

# 1. Simulate Imbalanced Casford Telemetry Logs
np.random.seed(42)
n_samples = 1200
features = np.random.randn(n_samples, 6)
# ~6% anomalies (1) vs 94% normal status (0)
target = np.random.choice([0, 1], size=n_samples, p=[0.94, 0.06])

# 2. Configure Stratified K-Fold
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
oof_probs = np.zeros(n_samples)

print("--- Executing 5-Fold Stratified Validation Loop ---")
for fold, (train_idx, val_idx) in enumerate(skf.split(features, target)):
    X_train, X_val = features[train_idx], features[val_idx]
    y_train, y_val = target[train_idx], target[val_idx]
    
    # Model focused on high-imbalance class weights
    clf = RandomForestClassifier(n_estimators=100, class_weight='balanced', random_state=42)
    clf.fit(X_train, y_train)
    
    # Record validation probabilities
    oof_probs[val_idx] = clf.predict_proba(X_val)[:, 1]
    
    # Base evaluation at 0.50 threshold
    fold_preds = (oof_probs[val_idx] >= 0.5).astype(int)
    fold_f2 = fbeta_score(y_val, fold_preds, beta=2, zero_division=0)
    print(f"Fold {fold + 1} - Validation F2 Score (Thresh 0.5): {fold_f2:.4f}")

# 3. Optimize Decision Boundary via Threshold Sweep
thresholds = np.linspace(0.05, 0.95, 19)
best_threshold = 0.5
best_f2 = 0.0

for t in thresholds:
    preds = (oof_probs >= t).astype(int)
    score = fbeta_score(target, preds, beta=2, zero_division=0)
    if score > best_f2:
        best_f2 = score
        best_threshold = t

print("\n--- Calibration Results ---")
print(f"Optimal Calibration Decision Threshold: {best_threshold:.2f}")
print(f"Maximized Out-Of-Fold F2-Score: {best_f2:.4f}")
Lab Overview

Objectives & Tasks

Review the tasks below and follow the interactive instructions to complete this module.

Knowledge Check

Ready to test your understanding of Milestone 2: Validation Framework Setup?

Previous
6. Regression Metrics
Locked
Complete Challenge to Unlock
Back