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.
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'.
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.
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.
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?