Feature Engineering & Data Quality
Applied ML articles on forecasting, feature engineering, NLP, production ML, graph analytics, conformal prediction, label engineering, and decision-oriented modeling — from real projects at Sofrecom (Orange Wholesale), Tunisia Telecom, Kiota Intelligence, and Zindi.
Insights on feature engineering, data quality, leakage prevention, and building reliable model inputs. Browse all insights in this category, or view all insights.
"Not observed yet" is not a negative label
In time-dependent problems, "not observed yet" means unknown, not negative. Treating right-censored cases as negatives introduces bias.
Labels must reflect the event within the observation window; censored cases need censor-aware handling.
Result: Use explicit observation windows and censor-aware methods (or survival approaches) for time-to-event outcomes.
Negative examples should not get more timeline than positive ones
Labels define the event. Observation windows define the information. In event-based modeling, they must be aligned to decision time.
Giving negative examples more future information creates asymmetry and leakage.
Result: Define the label by the event and build features only from what was knowable at decision time.
Do not ask ML to learn what a formula already knows
There is an important distinction: using a formula as a feature is not the same as training a residual model.
Use domain knowledge as a benchmark. Then test whether ML adds useful correction via formula-as-feature or explicit residual modeling.
Result: Use domain knowledge as a benchmark. Then measure what ML adds.
When you train on one flood and predict another, feature importance is not enough
Under event shift, a feature can be highly predictive for one flood and fail for the next. The question isn't just what correlates - it's what has a reason to survive a different storm path, intensity, or footprint.
Result: Balance event-specific signals (rainfall timing/intensity) with physically stable features (terrain, slope, flow direction, soil drainage). Good features explain the past; robust features can survive the shift.
Design the Training Table Before Choosing an Algorithm
Before model selection, define what one row represents. The training table sets the observation unit, prediction timestamp, feature window, granularity, and target — and a flexible model can look impressive while learning leakage or the wrong unit of analysis.
Result: A simpler model on a well-designed training table is often a stronger starting point than a sophisticated model trained on a distorted one.
Feature importance is not feature contribution
The same tree model can produce three different feature rankings. Gain, permutation, and SHAP measure different things: split-level training utility, held-out reliance, and per-prediction contribution.
Result: Choose the interpretation question first, use more than one lens, and investigate the disagreements — they reveal correlation, interactions, and instability that a single ranking hides.
Fraud Detection in 20 Hours: One Focused Workflow
A 20-hour fraud-detection hackathon with 191 competitors left no room for endless experimentation or model tourism. Instead of chasing the most advanced model, I asked where the fraud signal lives, what normal customer behaviour looks like, how imbalanced the target is, and which features can represent suspicious behaviour quickly.
Result: Ranked 6th of 191. One strong gradient-boosting baseline, behavioural features around consumption and payment patterns, and a validation setup I could trust. Under time pressure, clarity beats complexity.
Model the Context, Not Just the Curve
In a 2020 COVID-19 forecasting challenge, the direct signals were obvious: reported cases, growth rates, epidemic trajectories and short-term trends. I also modelled the context around each location — healthcare capacity, demographics, mobility, policy timing and environment — and finished 4th of 884 entrants.
Result: Similar case curves produced very different outcomes. The features that helped most did not measure the target directly; they described the system the target was happening to.
10K Clean Rows Can Beat 1M Noisy Rows: Data Quality First
The dataset had 1.2 million rows. After cleaning, deduplicating and filtering unreliable labels, only around 10,000 rows were usable — and the smaller dataset won. Row count is not signal.
Result: When someone says “we need more data,” the visible request often hides a deeper problem: labels built on weak heuristics, duplicates inflating apparent sample size, the same feature meaning different things across sources, undocumented missingness, or a training sample that does not resemble production. Audit label quality, remove duplicates, understand missingness, check the split, improve features with domain context — and only then ask whether more volume is worth the cost.
Target Leakage: Three Hidden Pitfalls
Target leakage is not always obvious. Beyond the obvious proxy-in-the-features version, three subtle forms hide in timestamps, transformations, and how examples are constructed: temporal leakage, transformation leakage, and observation-window leakage.
Result: All three make offline validation look stronger than it will in production. Define the prediction timestamp, use only data available then, fit learned transformations inside training folds, and construct examples that mirror deployment — then ask what the model saw that would not exist at prediction time.
Speed Buys Iterations: Faster Training, More Validated Ideas
Training speed is modelling leverage. A faster training loop lets you run more time-aware cross-validation, test more feature ideas, and inspect more failures before shipping.
Result: Speed doesn't guarantee a better model, it gives you more chances to build one. When two approaches deliver similar validated performance, the faster one creates leverage.
When to Adopt a Feature Store: Pain Before Platform
A feature store is valuable infrastructure, not automatic day-one infrastructure. Start lean with versioned feature definitions and reproducible code, then add a dedicated feature-store platform only when recurring pain makes reuse, consistency, or online serving justify it.
Result: Buy infrastructure to remove repeated friction—not to make the architecture diagram look more complete.
High-Cardinality Categoricals: One-Hot, Target Encoding, or Embeddings?
With thousands of categories, encoding is a modelling decision. One-hot explodes into a wide sparse matrix, naive target encoding leaks, and embeddings only help when categories repeat enough to generalise.
Result: Fit encoders inside training folds, define an unseen-category fallback, and keep only the representation that generalises against a strong baseline.
Preprocessing should have one source of truth
A lot of preprocessing bugs do not come from sophisticated modelling mistakes. They come from ordinary transformation logic being repeated manually in different places — one notebook imputes, another encodes, another scales, and a slightly different version reaches validation or production.
Result: Defining preprocessing once with a scikit-learn Pipeline and ColumnTransformer gives one transformation graph, reused at training and inference. It is not magic leakage prevention — it is a guardrail against inconsistency, so sound validation design is easier to apply consistently.
CatBoost Ordered Target Encoding: Controlling the Leak
Target encoding is powerful, and it is easy to evaluate incorrectly. If a category's average target is computed on the full dataset, a validation row's encoded value has already been influenced by labels that will not exist at scoring time — its own label, and its held-out neighbours'. Offline evaluation then looks better than it has any right to.
Result: CatBoost's ordered target statistics control that specific risk during training: each row's category statistic comes only from rows earlier in a random permutation, never from its own label. The encoding is not the problem — information scope is. Realistic splits, prediction-time feature availability and careful external aggregations still decide whether the number is real.
AI Pre-Flight Review Before You Write Model Code
Before serious model code, an AI assistant earns its keep as a reviewer, not an author: challenge the problem framing, inventory the feature categories, design the validation environment, and use it as a second set of eyes on leakage risk — before the pipeline exists.
Result: The assistant proposes and I verify. Availability, timing, data lineage, and business meaning stay human, but the five assumptions are written down and challengeable on day one instead of surfacing three weeks later. Suggested is not verified, and that is the whole discipline.
Unpack a Categorical Variable Into Behavioural Mechanisms
Do not treat a categorical variable as one flat label when it actually contains several behavioural mechanisms. In a tabular classification project, job_type looked simple - but an occupation category may partly reflect how income is generated, how regular it is, its seasonality, and access to formal financial services.
Result: I translated the field into domain-informed representations - income source type, income regularity, and financial-access context - and validated them, since a raw category is often not the business concept itself.
LLM Semantic Features: Propose, Then Earn Their Place
One interesting use of LLMs in tabular machine learning is not prediction — it is semantic feature generation. Ask the LLM to assign a controlled behavioural archetype, and treat the label as a candidate feature.
Result: The LLM output is not automatically valuable. Evaluate it against the baseline — out-of-sample lift, stability, prediction-time availability, privacy and cost — watch for leakage in the generation process, and keep the feature only if it earns its place.
Preparing Feature Spaces for Distance-Based Clustering
Before clustering telecom customers, the feature space must be usable — recharge tails, call-duration extremes, sparse and zero-heavy variables, and missing values that mean "no activity." Standardisation aligns units but not shapes.
Result: Decide missing-unknown versus missing-zero, review extremes, transform where justified, then standardise only after semantics are clear. In distance-based unsupervised learning, feature shape is part of the model definition.
AI-Generated Validation Can Pass While Data Is Still Wrong
An AI assistant generated a sensible validation suite — and everything passed while the data was still wrong. The missing rule was not technical; it was semantic: a customer was churned, yet a later activation existed without an approved reactivation transition.
Result: AI is right for the scaffold — repetitive syntax, standard null/type/range checks, suite structure. The highest-value quality rules need business context only humans can supply. AI can generate checks; humans define quality.
Feature Engineering Is Assembling Evidence Across Systems
No single source tells the whole story. In a Multi-SIM analytics project, the hardest question was what combination of signals could distinguish low activity from behaviour distributed across more than one SIM or operator — a usage table alone was ambiguous.
Result: Feature engineering often means assembling partial evidence: combine usage behaviour, communication-network context, handset and SIM signals, and coarse mobility patterns into one behavioural view — partial signals become stronger when interpreted together, carefully and under governance.
AI Can Review Feature Code. It Cannot Approve It
One of the best uses of AI in data science is not generation — it is review. Asked an AI reviewer to check a feature pipeline for temporal leakage, target leakage, train/test contamination, and features unavailable at prediction time — it flagged three patterns worth investigating.
Result: AI is a fast second reviewer, not an approver. It flags suspicious patterns and suggests safer alternatives; you still verify timestamps, validation-fold design, data contracts, and business meaning. The highest-leverage prompt is not "Write this for me" but "Challenge this before it goes live."
Polars Lazy Execution: More Than a Faster pandas
pandas executes every operation immediately; Polars lazy mode describes the transformation first and executes only when you call collect(). Lazy execution separates transformation intent from execution strategy — building repeatable data and feature-engineering pipelines around the plan matters more than raw speed.
Result: Describe what transformation you need and let the engine build the execution plan. Benchmark on your own data; pandas stays practical for quick exploration.
Cyclical Encoding: Stop One-Hot Encoding Months — Months Are a Circle, Not a Line
One-hot for months tells the model that January and December are unrelated — but they are neighbours. Encode truly cyclical features — month, hour, weekday — as sin and cos on a unit circle instead.
Result: December and January become adjacent in feature space. Always use it for neural networks and linear models; for tree models, test both and pick the better CV.
Categorical Encoding Cheat Sheet
Every categorical encoding makes an assumption about the structure of a variable. A practical guide to choosing between one-hot, ordinal, target, WoE, and contrast coding based on what your data actually looks like.
Result: Ten minutes of encoding analysis per variable can save days of debugging a model that memorizes instead of generalizes.
isnull() is a feature. Sometimes the best one.
Missingness is often not a data quality problem — it is a behavioral signal. In telecom, missing recharge means no recharge happened. In credit, missing income may mean refusal to disclose. Those are not "unknown" — they carry information.
The order of operations matters: create missingness indicators first, then null_count meta-features, then impute. Imputing first destroys the signal permanently.
Result: In 3 of my last 5 projects, the null flag ranked above the imputed variable in feature importance. The model cannot learn a signal you erased before it saw it.
Don't ask your model to learn what a formula already knows!
In a delivery-time prediction project, the formula was obvious — estimated duration from distance and rider speed. I gave the formula's output to the model as a structured prior, then let the model learn the deviation.
The model's job is no longer "predict delivery time." It becomes "predict how wrong this estimate will be, and in which direction." That's a much easier learning problem.
Result: The formula encodes what we know. The model encodes what we cannot derive analytically. This applies anywhere you have a reasonable first-principles estimate.
Turning One Categorical Variable into Behavioral Signal
Some categorical variables are informative but too coarse in raw form. Job_type mixes several underlying dimensions: how income is generated, how often it arrives, and how savings are managed.
I decomposed it into multiple behavioral features: income source, savings pattern, income frequency. Each derived feature captures a different financial mechanism.
Result: The variable is no longer a flat category — it becomes a behavioral representation layer separating latent mechanisms.
Encoding is a modeling decision, not a preprocessing checkbox
I encoded six categorical variables differently based on what they represented: Helmert Sequential for day_of_week, Polynomial Ordered for hardware generations, WoE for binary splits, Target encoding for high cardinality.
Every encoding imposes an assumption. Better tabular modeling often starts with representing variables in ways that reflect their actual structure.
Result: Encoding is not preprocessing — it is part of how the model is allowed to interpret the variable.
The most dangerous label in ML is the one that looks correct but isn't!
In a startup survival project (~50K funding rounds), the label "did not raise again" breaks if the company hasn't been observable for the full 36-month horizon. A startup founded in 2019, observed at 2021, looks like failure but simply hasn't had enough time.
Made two design decisions: eligibility window (only train on 36+ months observable history) and asymmetric holdout (mirror deployment prevalence, not balanced 50/50).
Result: Label design is often more important than algorithm choice. Once temporal contamination enters training, the model learns recency instead of risk.
Late Fusion for Multimodal Data: Represent Every Modality Well
Production data is rarely one clean modality. A customer record can combine tabular behaviour, free-text tickets, and documents or images — and the real challenge is representing each one well enough to combine it safely.
I start with separate branches: keep structured data structured, turn text into measurable signals, turn documents and images into structured outputs, then align every signal to the correct entity and prediction timestamp before fusing.
Result: Represent each modality well, validate each branch, then combine only what earns its place — start simple and add modalities with evidence.
Share on LinkedIn →