Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

Label Design and Windows

Reference for ml-problem-framing-advisor · 122 lines

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20265 references2 scripts

The three windows

text
 history start                 cutoff = prediction time
      |--------- observation window ---------|-- gap --|------ outcome window ------|
      features use only this                  optional   the label is computed here
  • Observation window: data the features may use. Often several sub-windows (last 7, 30, 90 days).
  • Gap (blackout): time between prediction and the start of the outcome window. Use it when the action takes time (call scheduling, shipping) or when data arrives late (yesterday's events land today).
  • Outcome window: where the label is measured. Its length is the horizon.

Choosing the horizon

ConsiderationPushes the horizon
Time needed to act (schedule a call, ship stock)longer: horizon > time to act + gap
Label delay you can tolerate before evaluatingshorter
Event frequency (enough positives per window)longer for rare events
Business cycle (monthly billing, seasonal demand)align to the cycle
Signal decay (features predict the near future better)shorter

Try two or three horizons and compare positives per window, offline metric and business usefulness. A 7-day churn label may have 1% positives and high precision; a 90-day label 12% positives and weaker signal.

Censoring

A row is right-censored when its outcome window has not fully elapsed. Treating it as negative biases the label toward 0 for the most recent rows.

Options:

  1. Drop scoring dates whose window has not ended (score_date <= today - horizon). Simple, loses fresh data.
  2. Use survival analysis with (duration, event) labels.
  3. For monitoring, compute a partial-window metric and compare like with like.

Label delay and training freshness

Training data ends at today - horizon - label_delay. With a 90-day chargeback delay and a 30-day horizon, the newest trainable row is four months old. Mitigations: a faster proxy label for monitoring (analyst labels in 2 days), weighting recent rows, or nowcasting the label.

Multi-snapshot datasets

Scoring weekly means the training table should also be weekly snapshots: one row per entity per scoring date.

  • Pros: matches deployment, multiplies positives, captures changing features.
  • Cons: rows of one entity are correlated (group by entity in CV), long-lived entities dominate (weight by 1 / snapshots per entity if needed), and churners appear as negatives in early snapshots, which is correct.
python
import pandas as pd

def build_snapshots(customers, events, cancels, score_dates, horizon_days=30):
    """One row per (customer, score_date); features from events strictly before score_date."""
    rows = []
    for d in score_dates:
        active = customers[(customers.start_date <= d) & ((customers.end_date.isna()) | (customers.end_date > d))]
        past = events[events.ts < d]
        feats = (past[past.ts >= d - pd.Timedelta(days=90)]
                 .groupby("customer_id").agg(events_90d=("ts", "size"), last_event=("ts", "max")))
        snap = active[["customer_id"]].merge(feats, on="customer_id", how="left")
        snap["days_since_event"] = (d - snap.pop("last_event")).dt.days
        snap["score_date"] = d
        end = d + pd.Timedelta(days=horizon_days)
        churned = cancels[(cancels.cancel_date > d) & (cancels.cancel_date <= end)].customer_id
        snap["label"] = snap.customer_id.isin(churned).astype(int)
        rows.append(snap)
    return pd.concat(rows, ignore_index=True)

Proxy labels

The thing you care about is often not observable (or too slow), so you train on a proxy:

GoalProxyWhere they disagree
Customer valueclicksclickbait gets clicks, not value
Fraudchargebacksfriendly fraud; fraud on declined transactions never charges back
Good hireinterview scoreinterviewer bias
Patient healthbilling codescoding practice varies by hospital
Satisfactionsurvey responsenon-response bias
Defectcustomer complaintsilent failures

For each proxy write down: when it diverges from the goal, how big the gap is, and which guardrail metric catches the divergence.

Label noise

Human labels, delayed labels and heuristics are noisy. Estimate noise with a double-labelled sample (agreement rate, Cohen's kappa). Noise above ~10% caps achievable accuracy; prefer models and losses robust to it, and clean the most-confident disagreements first.

Label SQL patterns

Event within a window after a snapshot

sql
CASE WHEN EXISTS (
  SELECT 1 FROM events e
  WHERE e.entity_id = s.entity_id AND e.type = 'cancel'
    AND e.ts > s.score_ts AND e.ts <= s.score_ts + INTERVAL '30 days'
) THEN 1 ELSE 0 END AS label

Quantity over a forward window

sql
COALESCE((SELECT SUM(o.amount) FROM orders o
          WHERE o.customer_id = s.customer_id
            AND o.ts > s.score_ts AND o.ts <= s.score_ts + INTERVAL '90 days'), 0) AS spend_next_90d

Survival label

sql
LEAST(COALESCE(c.cancel_date, CURRENT_DATE), CURRENT_DATE) - s.start_date AS duration_days,
CASE WHEN c.cancel_date IS NOT NULL THEN 1 ELSE 0 END                      AS event

Eligibility filter (always): active at the snapshot, not already labelled positive, in the population you will score in production.

More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.