Skip to content
ml-recall

Topic notes

Data & Features

Turning raw data into model-ready features — data types, cleaning, missing values, scaling, encoding categories, feature selection, class balance and avoiding leakage.

5-min read AI-checked

Practise 95 questions Take a test

Key ideas

Know your data. Rows are examples, columns are features (measurable properties) or the label. Numerical (quantitative) features can be added and averaged: height, counts, marks. Categorical (qualitative) ones name groups: blood type, colour, free-text reviews. Digits do not make a column numeric — IDs, postcodes and phone numbers are categories. Structured data sits in fixed tables; semi-structured data (JSON documents, graphs) has a flexible structure; unstructured data (essays, images, audio) has none. By definition, a relational database splits data into tables linked by keys — a primary key identifies a row, a foreign key holds the primary key of a row in another table — and is queried with SQL; "NoSQL" is the umbrella name for non-relational stores (key–value, document, column-family, graph).

Cleaning. Fix formats (stray whitespace, mixed date or number conventions), wrong data types and duplicate rows; joining sources with different conventions is a common cause of both. Never delete correct values because they contradict a hypothesis. Plot before modelling: histograms and box plots reveal skew, outliers and class imbalance.

Missing values6. First ask why values are missing. Values missing completely at random leave the remaining sample representative; values missing not at random — the gap depends on the missing value itself — can bias any analysis that ignores the reason6. Example: GarageArea is blank exactly for houses without a garage, so the true value is 0 and filling in the mean invents a typical garage; fill 0, or keep the information in a "was missing" indicator column. Replacing a missing feature value by the column mean is a common simple heuristic4. Never impute the target: an example without a label has nothing to teach, so drop it.

Scaling numerical features1

method formula suits
linear (min–max) (x−xmin⁡)/(xmax⁡−xmin⁡)(x - x_{\min}) / (x_{\max} - x_{\min}) roughly uniform values with stable bounds, e.g. age
z-score (x−μ)/σ(x - \mu) / \sigma roughly bell-shaped values
log ln⁡x\ln x power-law / long right tail, e.g. sales
clipping cap at a chosen limit rare but real extreme values

Z-scores have mean 0 and standard deviation 1 but no fixed range; only min–max maps the training data into [0,1][0, 1]. Values that are recording errors (a temperature of 1000) should be deleted, not clipped1. Methods built on distances, variances or penalties need comparable scales: kk-NN, kk-means and PCA, and — as scikit-learn notes — RBF-kernel SVMs and ℓ1\ell_1/ℓ2\ell_2-regularized linear models2; gradient descent also converges faster1. Trees split one feature at a threshold, so a monotone rescaling does not change them. For a positive, right-skewed target such as a house price, relative errors matter more than absolute ones, so errors are measured (and the model is often fitted) on log⁡y\log y: a difference of logs is a log-ratio, i.e. a relative error4.

Encoding categories2

Feature engineering2. Binning (discretization) followed by one-hot encoding gives a linear model one weight per range, so it can follow a nonlinear relationship. Polynomial features (degree 2 on [a,b][a, b] gives [1,a,b,a2,ab,b2][1, a, b, a^2, ab, b^2]) let it bend2.

Feature selection5. Filters score each feature alone (F-test, χ2\chi^2 for non-negative features, mutual information): fast, but blind to interactions — a feature useless on its own can matter together with another (XOR). Wrappers search subsets by a cross-validation score: forward selection adds and backward selection removes one feature at a time (greedy, no guarantee); exhaustive search scores all 2d2^d subsets. Recursive feature elimination refits and drops the least important feature by coef_ or feature_importances_. Embedded: the L1 penalty of the lasso sets coefficients exactly to zero; ridge shrinks but keeps every feature.

Imbalanced classes. A model trained on skewed classes leans towards the majority. Options: class weights, undersampling the majority, or oversampling the minority — by copying examples, or by generating new synthetic ones as SMOTE (Synthetic Minority Over-sampling Technique) does. Balancing evens out the classes; it is not a way to get more information. Stratified splits keep the class proportions in every fold.

Leakage3. Leakage is using information at training time that will not exist at prediction time; it makes validation scores optimistic. Split first, then fit every imputer, scaler, encoder and selector on the training split only (fit_transform on train, transform on validation and test); a Pipeline does this inside each cross-validation fold. Watch for target leakage — features computed from the label or known only after it (price per square metre, a neighbourhood average that includes the sale itself) — and for train–test contamination: statistics from all rows, near-duplicate photos of one product in both splits, or random splits of time-ordered data.

Formulas

Standardization with training statistics (StandardScaler uses the population standard deviation, dividing by nn):

z=x−μtrainσtrain,σtrain=1n∑i(xi−μtrain)2z = \frac{x - \mu_{\text{train}}}{\sigma_{\text{train}}}, \qquad \sigma_{\text{train}} = \sqrt{\tfrac{1}{n}\textstyle\sum_i (x_i - \mu_{\text{train}})^2}

Polynomial features of total degree at most pp in dd inputs, constant included: (d+pp)\binom{d+p}{p} — 6 for d=p=2d = p = 2, 10 for d=3,p=2d = 3, p = 2.

Worked example

Training column [2,4,6,12][2, 4, 6, 12]: μ=6\mu = 6, σ=14≈3.742\sigma = \sqrt{14} \approx 3.742, so the z-scores are [−1.069,−0.535,0,1.604][-1.069, -0.535, 0, 1.604]. A test value 8 becomes (8−6)/3.742≈0.535(8 - 6)/3.742 \approx 0.535, computed with the training μ\mu and σ\sigma. Min–max scaling with the training minimum 2 and maximum 12 maps 8 to 0.6 and a later value 15 to 1.3 — outside [0,1][0, 1], which is expected. Refitting the scaler on training plus test rows (mean 6.4) would let the test data shift the statistics: leakage3.

In code

import pandas as pd
from sklearn.compose import make_column_transformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

X_train = pd.DataFrame({"area": [50.0, 80.0, None, 120.0], "city": ["Hanoi", "Hue", "Hanoi", "Hue"]})
X_test = pd.DataFrame({"area": [100.0], "city": ["Da Nang"]})   # a city never seen in training
prep = make_column_transformer(
    (make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["area"]),
    (OneHotEncoder(handle_unknown="ignore"), ["city"]))
prep.fit(X_train)                        # medians, means, categories: training split only
print(prep.transform(X_test).round(2))   # [[0.7 0.  0. ]]  -> unseen city = all zeros

Common pitfalls

References

  1. Machine Learning Crash Course — Numerical data: Normalization (Linear scaling, Z-score scaling, Log scaling, Clipping, Summary of normalization techniques, Exercise: Test your knowledge)
  2. scikit-learn User Guide — Sec. 8.3 Preprocessing data (8.3.1 Standardization, or mean removal and variance scaling; 8.3.4 Encoding categorical features; 8.3.5 Discretization; 8.3.7 Generating polynomial features)
  3. scikit-learn User Guide — Sec. 12.2 Data leakage (12.2.1 How to avoid data leakage)
  4. Dive into Deep Learning — Sec. 5.7.4 Data Preprocessing; Sec. 5.7.5 Error Measure
  5. scikit-learn User Guide — Sec. 1.13 Feature selection (1.13.2 Univariate, 1.13.3 Recursive feature elimination, 1.13.4.1 L1-based, 1.13.5 Sequential Feature Selection)
  6. Wikipedia: Missing data — Types (intro; Missing completely at random; Missing not at random)