Sub topic 2
Scaling Numeric Features
Assume basic Python, pandas, scikit-learn, supervised learning, and descriptive statistics. Feature engineering changes raw columns into useful model inputs. The transformation must be learned from training data only.
Scaling Numeric Features
Scaling puts numeric columns on comparable ranges. Standardization subtracts the training mean and divides by the training standard deviation:
\[ x' = \frac{x-\mu}{\sigma} \]
This matters for distance-based models, linear models with regularization, support vector machines, and neural networks. Tree-based models usually do not need scaling.
import numpy as np
from sklearn.preprocessing import StandardScaler
X_train = np.array([[20.0, 1000.0], [30.0, 2000.0], [40.0, 5000.0]])
X_test = np.array([[35.0, 3000.0]])
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(X_train_scaled)
print(X_test_scaled)Fit the scaler on training data, then use transform on validation and test data. Fitting on all rows leaks information about the evaluation set.
| Situation | Common treatment |
|---|---|
| Similar numeric ranges | Scaling may be unnecessary |
| Very different ranges | StandardScaler or MinMaxScaler |
| Strong outliers | RobustScaler or an outlier-aware transform |
Log Transforms, Skew, and Binning
A right-skewed column has many small values and a few very large values. For non-negative values, log1p(x) often compresses the large values. Binning replaces a continuous value with ranges, such as income bands. Bins can improve interpretability but discard detail and create arbitrary boundaries.
Encoding Categorical Features
Categorical columns contain labels such as "city" or "plan". One-hot encoding creates one indicator column per category. Use ordinal encoding only when categories have a real order. Target encoding replaces a category with a target statistic, but it needs careful cross-validation to prevent leakage.
Extracting Features from Dates and Times
Convert timestamps to datetime values, then extract meaningful parts such as year, month, hour, weekday, or a weekend flag. Time is cyclical: hour 23 is close to hour 0. Sine and cosine features preserve that relationship.
Interaction and Polynomial Features
An interaction feature combines columns, such as price * quantity. Polynomial features add powers and interactions. They can represent curved relationships, but they increase feature count and overfitting risk. Add them only when domain knowledge or validation supports them.
Exercise
Why should a scaler be fitted on the training set instead of the complete dataset?
Show answer
Fitting on the complete dataset uses information from validation or test rows and can make evaluation scores too optimistic.