TExcelTAD
Home › Data Science › DS Feature Engineering

DS Feature Engineering

A feature is an input variable for a model. Feature engineering means creating better inputs from the raw columns — using domain knowledge to express the information in a form a model can use. A simple model with good features often beats a complex model with raw ones.

Features from dates

A raw date is useless to a linear model, but it hides many useful features:

python · try it yourself
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["dow"] = bikes["date"].dt.dayofweek            # 0 = Monday
bikes["month"] = bikes["date"].dt.month
bikes["day_index"] = (bikes["date"] - bikes["date"].min()).dt.days   # for trends
holidays = pd.to_datetime(["2024-05-01", "2024-05-09", "2024-05-20"])
bikes["holiday"] = bikes["date"].isin(holidays).astype(int)

print(bikes[["date", "dow", "month", "day_index", "holiday"]].iloc[29:33])
print("Holidays in data:", bikes["holiday"].sum())
         date  dow  month  day_index  holiday
29 2024-04-30    1      4         29        0
30 2024-05-01    2      5         30        1
31 2024-05-02    3      5         31        0
32 2024-05-03    4      5         32        0
Holidays in data: 3

A day_index lets a model capture a trend; holiday encodes knowledge that isn't in the data at all — it comes from a calendar.

Transforming numeric features

Transformation When it helps pandas / NumPy
Binary flag "Did it rain at all?" matters more than how much (x > 0).astype(int)
Bins Effect changes in steps pd.cut
Log Right-skewed values, multiplicative effects np.log1p(x)
Square Curved (U-shaped) relationships x ** 2
Interaction One variable's effect depends on another x1 * x2
Standardise Compare coefficients across units (x - x.mean()) / x.std()

Is it "any rain" or "how much rain" that keeps riders away? We can compare models with different versions of the rain feature:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

bikes["wet"] = (bikes["rain_mm"] > 0).astype(int)
bikes["log_rain"] = np.log1p(bikes["rain_mm"])

for feature in ["rain_mm", "wet", "log_rain"]:
    m = smf.ols(f"rides ~ temp_c + weekend + {feature}", data=bikes).fit()
    print(f"{feature:9} coef={m.params[feature]:8.2f}  adj R2={m.rsquared_adj:.3f}  AIC={m.aic:.1f}")
rain_mm   coef=   -9.11  adj R2=0.911  AIC=591.5
wet       coef=  -64.40  adj R2=0.873  AIC=612.9
log_rain  coef=  -35.45  adj R2=0.899  AIC=598.8

The amount of rain (rain_mm) fits best — no surprise, since we simulated rides from millimetres of rain. On real data you don't know the truth, and comparing candidate features like this is exactly how you find out.

Capturing curves with a squared term

Suppose that above 25 °C riders start to avoid the heat. A straight line can't bend, but adding temp² as a feature lets a linear model fit a curve. Here we simulate a summer with heat:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(8)
temp = rng.uniform(5, 38, 80).round(1)
rides = (40 + 32 * temp - 0.7 * temp ** 2 + rng.normal(0, 30, 80)).round()
summer = pd.DataFrame({"temp_c": temp, "rides": rides})

linear = smf.ols("rides ~ temp_c", data=summer).fit()
curved = smf.ols("rides ~ temp_c + I(temp_c ** 2)", data=summer).fit()
print(f"linear: adj R2={linear.rsquared_adj:.3f}")
print(f"curved: adj R2={curved.rsquared_adj:.3f}")
print(curved.params.round(3))

b1, b2 = curved.params["temp_c"], curved.params["I(temp_c ** 2)"]
print(f"busiest temperature: {-b1 / (2 * b2):.1f} °C")
linear: adj R2=0.090
curved: adj R2=0.766
Intercept         57.380
temp_c            29.661
I(temp_c ** 2)    -0.640
dtype: float64
busiest temperature: 23.2 °C

In a formula, I(...) means "compute this expression literally". The curved model fits much better and tells us rides peak at a comfortable temperature, then decline.

Interactions

An interaction lets one feature's effect depend on another. Maybe warm weather boosts rides more at weekends (leisure riders) than on weekdays (commuters ride anyway). In a formula, temp_c * weekend expands to temp_c + weekend + temp_c:weekend:

python · try it yourself
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
                      "humidity": humidity, "weekend": weekend, "rides": rides})

m = smf.ols("rides ~ temp_c * weekend + rain_mm", data=bikes).fit()
print(m.summary2().tables[1][["Coef.", "P>|t|"]].round(3))
                  Coef.  P>|t|
Intercept       159.305  0.000
temp_c           11.366  0.000
weekend          51.228  0.095
temp_c:weekend    0.677  0.652
rain_mm          -9.090  0.000

The interaction term temp_c:weekend is small and its p-value is large, so there is no evidence that temperature matters differently at weekends — which is right, because our simulation used the same +12 per degree for every day. Testing an interaction and not finding one is a useful result too.

Warning: Every engineered feature is a new chance to overfit. Prefer features that make domain sense, and check them on held-out data (Train/Test Split).

Test yourself

What does I(temp_c ** 2) do in a statsmodels formula?

  1. Takes the absolute value
  2. Adds the squared temperature as a feature, allowing a curved fit
  3. Removes temperature
  4. Creates an interaction

rides ~ temp_c * weekend includes which terms?

  1. Only temp_c × weekend
  2. temp_c, weekend and temp_c:weekend
  3. temp_c and weekend only
  4. weekend only

Which feature would best help a model capture public holidays?

  1. The date as a string
  2. A 0/1 holiday flag built from a calendar
  3. The row number
  4. Humidity