Skip to content

33. Feature engineering — Mini-project

You join the pricing team of a real-estate platform. The team’s current model is a plain linear regression on the raw columns of data/houses.csv. It explains about 79% of the variance in sale prices, and its typical error is close to 100,000 USD. The team asks you to improve it without changing the algorithm: same LinearRegression, better features.

There is one hard rule. The model will price houses that do not exist yet, so nothing about the test houses may influence training. Every value that your features learn from data (medians, categories, bin edges, scaling) must come from the training rows only. You make every feature decision with cross-validation on the training rows, rebuilding the features inside every fold. The hold-out set is scored once, at the end.

The project uses most of module 33: imputation with training statistics, scaling, one-hot encoding with unknown categories, a log target, log-transformed features, binning with KBinsDiscretizer, a polynomial term, size × neighborhood interactions, date features and leakage-safe evaluation. It also reuses the classes of module 18: your feature builder is a small class with fit and transform.

data/houses.csv has 3,000 house sales from 2022 to 2024 (see the data dictionary). The columns you use:

Column Notes
neighborhood 8 areas with very different median prices (Cedar Park 249,000 to Lakeview 777,000)
sqft, bedrooms, bathrooms size; bedrooms and bathrooms are strongly correlated with sqft
year_built, sold_date together they give the age at sale; the sale date also carries any market trend
lot_sqft 90 blank values; right-skewed
school_rating 90 blank values, placed at random
garage_spaces, has_pool, condition, distance_to_center_km other house attributes
price the target; right-skewed, from 117,500 to 3,730,500

Do not use house_id (it follows the sale date, see exercise M33-C13) and never use anything derived from price as a feature.

The sales span three years, and a deployed model prices future sales. This project keeps the random split of the data dictionary baselines, so your scores are comparable with them. With a random split, the trend feature only interpolates between known dates, so the hold-out score is somewhat optimistic for future sales. Stretch goal 5 measures the difference with a split by date.

Your script house_features.py must:

  1. Read the data with parse_dates=["sold_date"] and split it first: train_test_split(test_size=0.25, random_state=42).
  2. Build a baseline: the ten raw numeric columns with blank values filled by the training medians, scaled with StandardScaler, plus one-hot neighborhood (handle_unknown="ignore"). Fit LinearRegression on the raw price.
  3. Write a class HouseFeatures with fit(df) (learns and returns self) and transform(df) (returns a DataFrame). Store every learned object in an attribute that ends with _.
  4. Create at least these features: log(sqft), age at sale and its square, 6 quantile bins of age, log(lot_sqft) with a missing-value flag, school_rating with a missing flag and a >= 8 flag, log(distance_to_center_km), years since 2022-01-01 (a market trend) and one log(sqft) × neighborhood column per neighborhood.
  5. Model log(price) and transform the predictions back with np.exp before you compute any metric.
  6. Report, for the hold-out set: R², the mean absolute error in dollars, the share of houses priced within 10% and the number of features. Show three rows: the baseline, the baseline with a log target, and the engineered features.
  7. Run 5-fold cross-validation on the training set (KFold(5, shuffle=True, random_state=42)). Refit the feature builder on each training fold. Print the mean and the five fold scores for the baseline and the engineered model.
  8. End with assert checks: the builder’s medians equal the training medians, the transformed test set has no blank values, and the engineered R² beats the baseline by at least 0.05.

The expected report:

Expected output
Hold-out test set (750 houses)
baseline R2 0.792 MAE 98,861 within 10%: 32.4% features: 18
baseline, log target R2 0.898 MAE 65,262 within 10%: 45.5% features: 18
engineered R2 0.945 MAE 49,829 within 10%: 57.1% features: 37
5-fold CV R2 on the training set, builder refit in every fold
baseline mean 0.784 folds [0.807 0.767 0.728 0.793 0.825]
engineered mean 0.925 folds [0.939 0.876 0.924 0.934 0.949]
  1. Split first. Load the data and split it before you compute any statistic. Print the shapes to check: 2,250 training and 750 test rows.

  2. Write the baseline builder. A small class BaselineFeatures with fit and transform keeps the baseline and the engineered version comparable. In fit, learn the medians, then fit the scaler on the filled columns and the encoder on neighborhood.

  3. Write an evaluation function. evaluate(builder, fit_df, eval_df, log_target) fits the builder and the model on fit_df, predicts eval_df and returns a dictionary of metrics. You reuse it for the hold-out set and for every fold.

  4. Add a log target. Run the baseline once more with log_target=True. This one change shows how much of the gain comes from the target alone.

  5. Build the engineered features step by step. Start with log(sqft) and age. Add one group of features at a time (lot, school, distance, trend, age bins, interactions) and judge each group with the 5-fold cross-validation of step 7, on the training rows. Keep a group only if it helps there. Do not look at the hold-out score while you decide: every check of the hold-out set that changes a decision makes the test set part of the selection, and its score becomes optimistic. Score the hold-out set once, at the end.

  6. Learn everything in fit. Medians, one-hot categories, age bin edges and the scaler are fitted on the data passed to fit. transform only applies them. Fixed constants such as the reference date 2022-01-01 do not learn from data, so they are safe.

  7. Cross-validate by hand. Loop over folds.split(train). In each fold, create a new builder, fit it on the fold’s training part and evaluate on the fold’s validation part.

  8. Add the asserts and print the report. Compare every line with the expected report.

Criterion Points Full points when
Split before feature work 2 the split is the first data step; no statistic uses the test rows
Baseline 2 raw columns, training medians, scaling and one-hot; R² about 0.79
Feature builder class 3 fit learns and returns self; transform applies; learned attributes end with _
Engineered features 4 all features of requirement 4, each computed correctly
Log target 2 the model fits log(price) and every metric uses back-transformed prices
Leakage-safe CV 3 a new builder is fitted inside every fold
Report 2 the output matches the expected report
Self-checks 2 the three asserts of requirement 8
Total 20 16 or more: you are ready for module 34
  1. Extend the ablation of the reference solution to every feature group (lot, school, distance). Use the cross-validated R² on the training rows, never the hold-out set.
  2. Replace LinearRegression with Ridge(alpha=1.0) and check whether the 37 features need the penalty.
  3. Add a SequentialFeatureSelector (cv=3) inside your evaluation function and check whether a smaller feature set loses accuracy.
  4. Compare your engineered linear model with HistGradientBoostingRegressor(random_state=42) on the raw columns. The data dictionary reports an R² of about 0.92 on the log price. How close does your linear model come, and which one is easier to explain?
  5. Split by time instead: train on sales before 2024-07-01 and test on the rest. A deployed model prices future sales, so its trend feature must extrapolate beyond the training dates. Compare the score with the random split.
  6. Wrap your builder in a scikit-learn Pipeline after you read module 34, which shows how to make it a real transformer with BaseEstimator and TransformerMixin.

Try the project yourself first. Then compare your script with this one. Your feature names can differ; your workflow must keep every learned value inside fit.

Reference solution
house_features.py
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import KFold, train_test_split
from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder, StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
houses = pd.read_csv("data/houses.csv", parse_dates=["sold_date"])
train, test = train_test_split(houses, test_size=0.25, random_state=42)
RAW_NUMERIC = ["sqft", "bedrooms", "bathrooms", "year_built", "lot_sqft",
"garage_spaces", "has_pool", "condition",
"distance_to_center_km", "school_rating"]
FIRST_SALE = pd.Timestamp("2022-01-01") # fixed reference date for the trend
class BaselineFeatures:
"""Raw numeric columns (median-imputed, scaled) plus one-hot neighborhood."""
def fit(self, df):
self.medians_ = df[RAW_NUMERIC].median()
self.scaler_ = StandardScaler().set_output(transform="pandas")
self.scaler_.fit(df[RAW_NUMERIC].fillna(self.medians_))
self.onehot_ = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
self.onehot_.set_output(transform="pandas").fit(df[["neighborhood"]])
return self
def transform(self, df):
numeric = self.scaler_.transform(df[RAW_NUMERIC].fillna(self.medians_))
areas = self.onehot_.transform(df[["neighborhood"]])
return pd.concat([numeric, areas], axis=1)
class HouseFeatures:
"""Engineered house features; every learned value comes from fit()."""
def fit(self, df):
self.medians_ = df[["lot_sqft", "school_rating"]].median()
self.onehot_ = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
self.onehot_.set_output(transform="pandas").fit(df[["neighborhood"]])
self.age_bins_ = KBinsDiscretizer(n_bins=6, encode="onehot-dense",
strategy="quantile")
self.age_bins_.set_output(transform="pandas").fit(self._age(df))
self.scaler_ = StandardScaler().set_output(transform="pandas")
self.scaler_.fit(self._numeric(df))
return self
@staticmethod
def _age(df):
return pd.DataFrame({"age": df["sold_date"].dt.year - df["year_built"]})
def _numeric(self, df):
age = self._age(df)["age"]
filled = df[["lot_sqft", "school_rating"]].fillna(self.medians_)
return pd.DataFrame({
"log_sqft": np.log(df["sqft"]),
"bedrooms": df["bedrooms"],
"bathrooms": df["bathrooms"],
"age": age,
"age_sq": age ** 2,
"log_lot": np.log(filled["lot_sqft"]),
"lot_missing": df["lot_sqft"].isna().astype(int),
"school_rating": filled["school_rating"],
"good_school": (filled["school_rating"] >= 8).astype(int),
"school_missing": df["school_rating"].isna().astype(int),
"garage_spaces": df["garage_spaces"],
"has_pool": df["has_pool"],
"condition": df["condition"],
"log_distance": np.log(df["distance_to_center_km"]),
"years_since_2022": (df["sold_date"] - FIRST_SALE).dt.days / 365.25,
}, index=df.index)
def transform(self, df):
numeric = self.scaler_.transform(self._numeric(df))
areas = self.onehot_.transform(df[["neighborhood"]])
size_by_area = areas.mul(np.log(df["sqft"]), axis=0)
size_by_area.columns = [c.replace("neighborhood_", "logsqft_x_")
for c in areas.columns]
return pd.concat([numeric, areas, size_by_area,
self.age_bins_.transform(self._age(df))], axis=1)
def evaluate(builder, fit_df, eval_df, log_target):
X_fit = builder.fit(fit_df).transform(fit_df)
X_eval = builder.transform(eval_df)
y_fit = np.log(fit_df["price"]) if log_target else fit_df["price"]
model = LinearRegression().fit(X_fit, y_fit)
pred = model.predict(X_eval)
pred = np.exp(pred) if log_target else pred
actual = eval_df["price"]
within_10 = (np.abs(pred - actual) / actual <= 0.10).mean()
return {"r2": r2_score(actual, pred), "mae": mean_absolute_error(actual, pred),
"within_10pct": within_10, "n_features": X_fit.shape[1]}
results = pd.DataFrame({
"baseline": evaluate(BaselineFeatures(), train, test, log_target=False),
"baseline, log target": evaluate(BaselineFeatures(), train, test, log_target=True),
"engineered": evaluate(HouseFeatures(), train, test, log_target=True),
}).T
print("Hold-out test set (750 houses)")
for name, row in results.iterrows():
print(f" {name:<21} R2 {row['r2']:.3f} MAE {row['mae']:>7,.0f} "
f"within 10%: {row['within_10pct']:.1%} features: {row['n_features']:.0f}")
folds = KFold(5, shuffle=True, random_state=42)
cv_r2 = {"baseline": [], "engineered": []}
for fit_idx, eval_idx in folds.split(train):
fit_part, eval_part = train.iloc[fit_idx], train.iloc[eval_idx]
cv_r2["baseline"].append(
evaluate(BaselineFeatures(), fit_part, eval_part, log_target=False)["r2"])
cv_r2["engineered"].append(
evaluate(HouseFeatures(), fit_part, eval_part, log_target=True)["r2"])
print("5-fold CV R2 on the training set, builder refit in every fold")
for name, scores in cv_r2.items():
print(f" {name:<11} mean {np.mean(scores):.3f} folds {np.round(scores, 3)}")
builder = HouseFeatures().fit(train)
assert builder.medians_.equals(train[["lot_sqft", "school_rating"]].median())
assert builder.transform(test).notna().all().all()
assert results.loc["engineered", "r2"] > results.loc["baseline", "r2"] + 0.05
Output
Hold-out test set (750 houses)
baseline R2 0.792 MAE 98,861 within 10%: 32.4% features: 18
baseline, log target R2 0.898 MAE 65,262 within 10%: 45.5% features: 18
engineered R2 0.945 MAE 49,829 within 10%: 57.1% features: 37
5-fold CV R2 on the training set, builder refit in every fold
baseline mean 0.784 folds [0.807 0.767 0.728 0.793 0.825]
engineered mean 0.925 folds [0.939 0.876 0.924 0.934 0.949]

Run it from the project folder:

Terminal
python house_features.py

An ablation shows which feature groups carry the gain. It drops one group at a time and recomputes the 5-fold CV R² on the training rows, with the builder refit in every fold. The hold-out set is not used.

ablation (append to house_features.py)
groups = {
"size x area": lambda c: c.startswith("logsqft_x_"),
"age terms": lambda c: c in ("age", "age_sq") or c.startswith("age_"),
"trend": lambda c: c == "years_since_2022",
"good_school": lambda c: c == "good_school",
}
def cv_r2_without(drop):
scores = []
for fit_idx, eval_idx in folds.split(train):
fit_part, eval_part = train.iloc[fit_idx], train.iloc[eval_idx]
fe = HouseFeatures().fit(fit_part)
X_fit, X_eval = fe.transform(fit_part), fe.transform(eval_part)
keep = [c for c in X_fit.columns if not drop(c)]
model = LinearRegression().fit(X_fit[keep], np.log(fit_part["price"]))
pred = np.exp(model.predict(X_eval[keep]))
scores.append(r2_score(eval_part["price"], pred))
return np.mean(scores)
print(f"all features CV R2 {cv_r2_without(lambda c: False):.3f}")
for name, rule in groups.items():
print(f"without {name:<11} CV R2 {cv_r2_without(rule):.3f}")
Output
all features CV R2 0.925
without size x area CV R2 0.862
without age terms CV R2 0.911
without trend CV R2 0.918
without good_school CV R2 0.922

The size × area interactions carry the largest share of the gain (about 6 points of CV R²), then the trend and the age terms. The good-school flag adds little, because school_rating already carries most of that signal.

How it works:

  1. Split first. The split is the first data step, so the test houses never influence a median, a category list, a bin edge or a scaler.
  2. Two builders, one interface. BaselineFeatures and HouseFeatures both have fit and transform. evaluate does not care which one it gets: this is the duck typing of module 19, and it is the same contract that scikit-learn transformers follow.
  3. The log target alone lifts the R² from 0.792 to 0.898 and cuts the mean error by a third. Prices grow in percent, and the log makes the linear model work in percent too.
  4. The engineered features add another 5 points of R². The ablation below shows where the gain comes from.
  5. Missing-value flags keep the information that a value was blank, which the median fill alone would hide. Here they add almost nothing, because the blanks in this dataset are random. In real data, a blank often carries signal (a listing without a lot size may be a flat).
  6. Cross-validation creates a new builder in every fold, so each fold’s validation houses are as unseen as the test set. The CV means (0.784 and 0.925) agree with the hold-out scores. That is a sign that the split and the builder do not leak information from the test rows into training. It does not rule out target leakage: a feature such as price_per_sqft would inflate both scores. That needs the “known at prediction time?” check for every feature.
  7. The asserts check the learned medians, the absence of blanks after transform (the missing flags and the medians cover every gap), and the size of the improvement.

Alternative: the same features fit in a ColumnTransformer inside a Pipeline, with FunctionTransformer for the logs and TransformedTargetRegressor for the log target. Module 34 builds that version. The hand-written class here makes every learned value visible, which is the point of this module.