Data and features
Datasets, features and labels; train/validation/test splits; feature engineering, scaling and one-hot encoding; missing values — and how to avoid data leakage with pipelines.
‘Garbage in, garbage out.’ In real projects most of the time goes not into choosing algorithms but into collecting, cleaning and representing data. A mediocre algorithm with well-prepared features routinely beats a fancy algorithm with poor ones[5]. This lesson covers how data is organised, how to split it honestly, and how to turn raw columns into features a model can use.
| area_m2 | bedrooms | city | year_built | price (label, M Rp) |
|---|---|---|---|---|
| 72 | 3 | Bandung | 2012 | 1,150 |
| 45 | 2 | Jakarta | 2018 | 1,300 |
| 120 | 4 | Surabaya | 2005 | 1,600 |
| 60 | — | Bandung | 2020 | 980 |
Kinds of features
- Numerical — continuous (area, temperature) or discrete counts (bedrooms). Can be used almost directly, but often need scaling.
- Categorical — nominal with no order (city, colour) or ordinal with an order (size S < M < L, education level). Must be encoded as numbers.
- Text, images, audio — unstructured; classical ML needs hand-made features (word counts), deep learning learns features from the raw signal.
- Dates and time series — rarely useful raw; extract day of week, month, holiday flag, time since last event, rolling averages.
Train, validation and test sets
A model that scores well on the data it trained on may simply have memorised it. To measure real performance we split the data. The [[training-set|training set]] is used to fit the parameters. The [[validation-set|validation set]] is used to compare models and tune hyperparameters. The [[test-set|test set]] is locked away and used once, at the very end, to estimate performance on truly unseen data. Think of practice questions, mock exams, and the final exam: if you peek at the final exam while studying, your grade no longer tells anyone how much you learned.
| Split | Used for | Typical share |
|---|---|---|
| Training | fitting parameters (fit) | 60–80% |
| Validation | model selection, hyperparameter tuning, early stopping | 10–20% |
| Test | final unbiased estimate — touch once | 10–20% |
- What it is
- The fraction of the data held out for evaluation (e.g.
test_size=0.2intrain_test_split). - ↑ If you increase it
- The performance estimate becomes more reliable (less noisy), but the model trains on less data and may be slightly worse.
- ↓ If you decrease it
- More data for training, but the score on a tiny held-out set is noisy — two runs can differ by several points just by chance.
- Typical values
- 0.2 for thousands of rows; 0.01–0.05 for millions; for a few hundred rows prefer 5- or 10-fold cross-validation.
Feature engineering
[[feature-engineering|Feature engineering]] means creating inputs that make the pattern easier to learn, usually using domain knowledge. A linear model cannot discover that ‘price per m²’ matters unless you compute it; a tree cannot easily use a timestamp unless you extract the hour.
- Ratios and differences: debt / income, price per m², age = 2025 − year_built.
- Transformations: log(income) to tame heavy right-skewed values; binning ages into ranges.
- Date parts: weekday, month, is_holiday, hour of day.
- Aggregates: a customer's number of orders in the last 30 days, average basket value.
- Interactions: area × location quality, when the effect of one feature depends on another.
Scaling numerical features
If one feature ranges 0–1 and another 0–1,000,000, distance-based methods (kNN, k-means, SVM), PCA and gradient-based training all get dominated by the big one. [[normalization-scaling|Scaling]] puts features on comparable ranges[1]. Tree-based models do not need it (they only compare thresholds).
- z
- the standardised value (z-score): 0 = average, +1 = one standard deviation above
- x
- the original Feature value
- μ
- mu — mean of the feature over the Training set
- σ
- sigma — standard deviation of the feature over the training set
- Min-max
- the second method: rescale to the range 0…1
- x′
- “x prime”: the rescaled value, between 0 and 1 for training data
- min
- smallest value of the feature in the training set
- max
- largest value of the feature in the training set
▸Worked example
| Scaler (scikit-learn) | Result | Use when |
|---|---|---|
| StandardScaler | mean 0, std 1 | default for linear models, SVM, neural nets, PCA |
| MinMaxScaler | range [0, 1] | bounded inputs (e.g. pixel intensities) |
| RobustScaler | median 0, scaled by IQR | data with strong outliers |
Encoding categories
Models need numbers, but writing Bandung = 1, Jakarta = 2, Surabaya = 3 invents a false order (is Surabaya ‘3× Bandung’?). [[one-hot-encoding|One-hot encoding]] creates one binary column per category: Bandung → [1, 0, 0], Jakarta → [0, 1, 0], Surabaya → [0, 0, 1]. Use ordinal encoding only for truly ordered categories. For very high-cardinality columns (thousands of product ids) consider grouping rare categories, hashing, target encoding (with care) or learned embeddings[2][4].
- What it is
- Options of scikit-learn's
OneHotEncoderthat merge rare categories into a single ‘infrequent’ column: categories seen fewer thanmin_frequencytimes, or beyond the topmax_categories. - ↑ If you increase it
- Higher
min_frequency(or lowermax_categories) → fewer columns, less overfitting to rare categories, but genuinely informative rare values get lumped together. - ↓ If you decrease it
- Every category gets its own column → very wide, sparse data; the model may memorise categories seen only a handful of times.
- Typical values
- Off by default. Try
min_frequencyof 5–50 examples (or a fraction like 0.01) for columns with long tails.
Missing values and outliers
Most models cannot accept missing values. Options: drop rows (wasteful, can bias the data), impute with the median / most frequent value (SimpleImputer), or impute *and* add a ‘was missing’ indicator, because missingness itself can be informative. Outliers can be data-entry errors (a 2,000 m² studio flat) or real extreme cases — investigate before deleting. Some models, such as scikit-learn's HistGradientBoosting*, handle missing values natively.
Data leakage — the silent killer
[[data-leakage|Data leakage]] happens when information that will not be available at prediction time — or information from the evaluation data — sneaks into training. The validation score looks fantastic, then the model fails in production[3]. Classic examples:
- Fitting a scaler, imputer or PCA on the whole dataset before splitting — test statistics leak into training.
- A feature computed from the label or the future: ‘refund_issued’ when predicting fraud; next month's sales when forecasting this month.
- Duplicates or the same patient/user appearing in both train and test.
- Random splits on time series — the model trains on the future and is tested on the past.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import Ridge
df = pd.read_csv("houses.csv")
X = df.drop(columns="price")
y = df["price"]
# 1) Split FIRST — the test set is never seen by any fit()
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
numeric = ["area_m2", "bedrooms", "year_built"]
categorical = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
("scale", StandardScaler()),
]), numeric),
("cat", OneHotEncoder(handle_unknown="ignore", min_frequency=5), categorical),
])
# 2) Preprocessing + model in ONE pipeline: statistics come from train only
model = Pipeline([("prep", preprocess), ("reg", Ridge(alpha=1.0))])
model.fit(X_train, y_train)
print("test R²:", model.score(X_test, y_test))▸Go deeper: stratified, grouped and time-based splits
- Stratified split (
stratify=yorStratifiedKFold): keeps class proportions equal across splits — essential when one class is rare (e.g. 2% fraud). - Group split (
GroupKFold): all rows of one patient, user or store go to the same side, so the model cannot ‘recognise’ individuals. - Time-based split (
TimeSeriesSplit): train on the past, validate on the future — mirrors how the model will be used.
Quiz
References
- [1]scikit-learn User Guide — Preprocessing dataDocsscikit-learn developersscikit-learn.org
- [2]scikit-learn User Guide — Pipelines and composite estimatorsDocsscikit-learn developersscikit-learn.org
- [3]scikit-learn User Guide — Common pitfalls and recommended practicesDocsscikit-learn developersscikit-learn.orgData leakage during preprocessing.
- [4]Machine Learning Crash Course — Working with categorical dataCourseGoogledevelopers.google.com
- [5]A Few Useful Things to Know About Machine LearningPaperDomingos2012doi.org‘Feature engineering is the key.’