30 Mins

5. Feature Generation

Decomposing Date and Time

Raw timestamps contain implicit temporal information that machine learning models cannot interpret directly. By decomposing these into components like hour, day of the week, or month, we allow models to capture seasonal or cyclic patterns.

Cyclical features, such as hours of the day (0-23), pose a problem: the distance between 23 and 0 is smaller than 23 and 1. We solve this by applying sine and cosine transformations to map the temporal data onto a unit circle.

Operator Note: Always check for periodic behavior in your data; if a feature repeats (like days, months, or hours), sine/cosine encoding is essential.
Python 3
import pandas as pd
import numpy as np
dates = pd.to_datetime(['2023-01-01 08:00', '2023-01-02 22:00'])
df = pd.DataFrame({'date': dates})
df['hour'] = df['date'].dt.hour
df['hour_sin'] = np.sin(2 * np.pi * df['hour'] / 24)
df['hour_cos'] = np.cos(2 * np.pi * df['hour'] / 24)
print(df[['hour', 'hour_sin', 'hour_cos']])

Interaction Features and Ratios

Interaction features capture the relationship between two independent variables that together have an effect on the target that isn't captured by each variable individually. Common methods include multiplication (interaction) and division (ratios).

Ratios are particularly useful for normalizing data, such as calculating 'price per square foot' instead of just 'total price' and 'total area'.

Operator Note: Use ratios when you want to make a feature scale-invariant, allowing the model to focus on densities rather than total magnitudes.
Python 3
import pandas as pd
data = {'price': [200000, 500000], 'area': [1000, 2500]}
df = pd.DataFrame(data)
df['price_per_sqft'] = df['price'] / df['area']
df['area_x_rooms'] = df['area'] * 2 # Example interaction
print(df)

Polynomial Feature Transformations

Linear models are limited by their assumption of linear relationships. Scikit-learn's PolynomialFeatures generates interaction terms and powers of existing features automatically.

For features [a, b], a degree-2 transformation will produce [1, a, b, a^2, ab, b^2]. This enables linear models to map non-linear decision boundaries.

Operator Note: Be careful with degrees higher than 2 or 3; the number of features grows factorially, leading to the 'Curse of Dimensionality' and overfitting.
Python 3
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
X = np.array([[2, 3]])
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
print('Original shape:', X.shape)
print('New shape:', X_poly.shape)
print('Features:', poly.get_feature_names_out())

Binning Continuous Features

Binning, or discretization, transforms continuous numerical variables into categorical ones. This is helpful when the relationship between the feature and target is non-monotonic or when you need to group outliers together.

You can use fixed-width binning or quantile-based binning where every bin contains the same number of observations.

Operator Note: Binning is a great way to handle skewed distributions or to make a model more robust to noisy measurements within specific ranges.
Python 3
import pandas as pd
vals = [12, 15, 22, 28, 45, 60]
df = pd.DataFrame({'age': vals})
df['age_group'] = pd.cut(df['age'], bins=[0, 18, 30, 100], labels=['young', 'adult', 'senior'])
print(df)

Knowledge Check

Ready to test your understanding of 5. Feature Generation?

Back