AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
◎AI Foundations
  1. What is AI?
  2. Types of learning
  3. Math essentials for ML
  4. Data and features
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/AI Foundations

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.

Beginner~20 min·5 references
Key terms
DatasetFeatureLabel (target)Training setValidation setTest setFeature engineeringFeature scaling (normalisation / standardisation)One-hot encodingData leakage

‘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.

≈
A dataset is a spreadsheet
Each row is one example (a house, a customer, an email). Each column is a feature — a measurable property. One special column is the label: the answer you want to predict. The model's job is to learn the link from the feature columns to the label column.
area_m2bedroomscityyear_builtprice (label, M Rp)
723Bandung20121,150
452Jakarta20181,300
1204Surabaya20051,600
60—Bandung2020980
A tiny Dataset: four examples, four features (two numerical, one categorical, one date-like), one label. Note the missing value (—).

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.

SplitUsed forTypical share
Trainingfitting parameters (fit)60–80%
Validationmodel selection, hyperparameter tuning, early stopping10–20%
Testfinal unbiased estimate — touch once10–20%
With millions of examples, 98/1/1 is common — 1% is already plenty. With small data, use k-fold Cross-validation instead of a single validation set.
knobtest_size / validation fraction
What it is
The fraction of the data held out for evaluation (e.g. test_size=0.2 in train_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).

Standardisation: z = (x − μ) / σ Min-max: x′ = (x − min) / (max − min)
μ, σ, min and max must be computed on the training set only, then applied unchanged to validation/test data.
In words: Standardisation reads “how many standard deviations is x above or below the average?” — the result is centred on 0 with spread 1. Min-max reads “what fraction of the way from the smallest to the largest value is x?” — the result lies in [0, 1]. Either way, every feature ends up on a comparable scale (Feature scaling (normalisation / standardisation)).
Symbols(hover a symbol in the formula)
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
Training ages: [20, 30, 40] Standardisation: μ = 30, σ = √((100 + 0 + 100)/3) ≈ 8.165 x = 40 → z = (40 − 30) / 8.165 ≈ 1.22 x = 25 → z = (25 − 30) / 8.165 ≈ −0.61 Min-max: min = 20, max = 40 x = 40 → x′ = (40 − 20) / 20 = 1 x = 25 → x′ = (25 − 20) / 20 = 0.25 A test age of 50 uses the SAME μ, σ, min, max: z ≈ 2.45, x′ = 1.5 (outside 0…1 is fine).
Scaler (scikit-learn)ResultUse when
StandardScalermean 0, std 1default for linear models, SVM, neural nets, PCA
MinMaxScalerrange [0, 1]bounded inputs (e.g. pixel intensities)
RobustScalermedian 0, scaled by IQRdata 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].

knobmin_frequency / max_categories (OneHotEncoder)
What it is
Options of scikit-learn's OneHotEncoder that merge rare categories into a single ‘infrequent’ column: categories seen fewer than min_frequency times, or beyond the top max_categories.
↑ If you increase it
Higher min_frequency (or lower max_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_frequency of 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.
python
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))
A leak-free workflow: split first, and keep all preprocessing inside a Pipeline so it is re-fitted only on training data (also inside cross-validation).
!
Leakage red flags
Suspiciously high scores (99% on a hard problem), one feature that dominates importance, or a big drop from validation to production. When you see these, ask for every feature: ‘Would I really know this value at the moment I make the prediction?’
✓
Checklist before training
1) Look at the data (head, describe, histograms). 2) Define the label and check its quality. 3) Split before anything else (by time or by group when relevant). 4) Build preprocessing in a Pipeline. 5) Train a simple Baseline first. 6) Only then try complex models.
▸Go deeper: stratified, grouped and time-based splits
  • Stratified split (stratify=y or StratifiedKFold): 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

1.
Why should the test set be used only once, at the end?
2.
You fit a StandardScaler on all 10,000 rows, then split into train/test. What is the problem?
3.
Which model does NOT need feature scaling?
4.
Encoding cities as Bandung = 1, Jakarta = 2, Surabaya = 3 for a linear model is risky because…
5.
A churn model uses the feature ‘account_closed_date’. Validation accuracy is 99.5%. Most likely explanation?
Score: 0/5

References

  1. [1]
    scikit-learn User Guide — Preprocessing data
    Docsscikit-learn developersscikit-learn.org
  2. [2]
    scikit-learn User Guide — Pipelines and composite estimators
    Docsscikit-learn developersscikit-learn.org
  3. [3]
    scikit-learn User Guide — Common pitfalls and recommended practices
    Docsscikit-learn developersscikit-learn.org
    Data leakage during preprocessing.
  4. [4]
    Machine Learning Crash Course — Working with categorical data
    CourseGoogledevelopers.google.com
  5. [5]
    A Few Useful Things to Know About Machine Learning
    PaperDomingos2012doi.org
    ‘Feature engineering is the key.’
← Previous
Math essentials for ML
Next → · Classical Machine Learning
Linear regression