TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Mini Project: House Prices and Customer Segments

Mini Project: House Prices and Customer Segments

Two projects that use the course end to end. Part A (the main project) predicts house prices: a baseline, a linear model, a random forest and LightGBM compared with cross-validation, an improvement driven by what the data looks like, one final test, error analysis and a write-up. Part B (shorter) segments customers with k-means. Both follow the beginner projects of the curriculum this track is built on, and both use generated tables so that everything runs offline. Each step is a complete program; run them in order or one by one.

About the data. Real house-price data would come from sales records, listings or public registers, each with its own licence and privacy rules (an address and a price identify a person's home); see Data for ML. Here a generator builds 1500 houses with known structure: price grows with the square root of the area, each district has its own price level that multiplies everything, age only matters beyond 40 years, distance from the centre lowers the price, a garden adds more the farther out a house is, and there is about 7 % random variation. About 3 % of ages are missing. Knowing the truth lets you judge your model's choices afterwards. If you prefer real measurements, the same steps work on load_diabetes (a disease-progression score instead of a price).

Part A, step 1: look at the data

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

def make_housing(n=1500, seed=0):
    """A generated housing table (prices in thousands). Nonlinear on purpose: size has diminishing returns,
    age matters only for old houses, each district has its own price level, and a garden adds more far out."""
    rng = np.random.default_rng(seed)
    district = rng.choice(["centre", "north", "east", "south", "west"], n, p=[0.15, 0.25, 0.2, 0.25, 0.15])
    level = {"centre": 1.8, "north": 1.15, "east": 0.7, "south": 1.0, "west": 1.3}
    area = rng.gamma(9, 11, n).round(0) + 25                         # square metres
    rooms = np.clip(np.round(area / 28 + rng.normal(0, 0.8, n)), 1, 8).astype(int)
    age = rng.integers(0, 90, n)
    dist_km = np.where(district == "centre", rng.uniform(0, 3, n), rng.uniform(2, 25, n)).round(1)
    garden = (rng.random(n) < np.clip(dist_km / 20, 0.05, 0.9)).astype(int)
    price = (np.array([level[d] for d in district]) * 900 * np.sqrt(area) - 6 * np.maximum(age - 40, 0) ** 1.2
             - 9 * dist_km + garden * (20 + 3 * dist_km) + 4 * rooms)
    price = price * np.exp(rng.normal(0, 0.07, n))                  # multiplicative noise, about 7 %
    df = pd.DataFrame({"district": district, "area_m2": area, "rooms": rooms, "age_years": age,
                       "dist_km": dist_km, "garden": garden, "price_k": (price / 100).round(1)})
    df.loc[rng.random(n) < 0.03, "age_years"] = np.nan             # a few missing ages
    return df
df = make_housing()
print(df.head().to_string())
print(df.describe().round(1).loc[["mean", "min", "max"]].to_string())
print("missing:", df.isna().sum()[df.isna().sum() > 0].to_dict())
print(df.groupby("district")["price_k"].median().sort_values().to_string())
  district  area_m2  rooms  age_years  dist_km  garden  price_k
0    south    130.0      5       87.0      3.1       0     93.5
1    north    114.0      4       53.0     24.3       1    115.7
2   centre    112.0      4        NaN      1.1       0    175.0
3   centre    111.0      5        NaN      1.7       0    175.6
4    south    104.0      3       14.0     22.3       1     88.8
      area_m2  rooms  age_years  dist_km  garden  price_k
mean    123.8    4.4       44.3     11.9     0.6    111.5
min      58.0    1.0        0.0      0.0     0.0     41.5
max     255.0    8.0       89.0     25.0     1.0    258.0
missing: {'age_years': 42}
district
east       67.0
south      97.4
north     111.4
west      124.1
centre    175.0

What to notice. Prices range from about 40k to 260k. 42 ages are missing, so the pipeline needs an imputer. The district medians differ a lot (east is cheapest, the centre most expensive), so district must be a feature, encoded one-hot.

Step 2: baseline and three models

The test set (20 %) is split off first and not touched until step 4. Every model is a pipeline (imputer, scaler for the linear model, one-hot encoder), so preprocessing is learned inside each training fold. All four share the same 5 folds. The metric is the mean absolute error in thousands (MAE, easy to explain to a buyer) plus R2R^2. Note the import order (scikit-learn before LightGBM), explained in the XGBoost lesson.

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, KFold, cross_validate
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import RidgeCV
from sklearn.ensemble import RandomForestRegressor
import lightgbm as lgb

def make_housing(n=1500, seed=0):
    """A generated housing table (prices in thousands). Nonlinear on purpose: size has diminishing returns,
    age matters only for old houses, each district has its own price level, and a garden adds more far out."""
    rng = np.random.default_rng(seed)
    district = rng.choice(["centre", "north", "east", "south", "west"], n, p=[0.15, 0.25, 0.2, 0.25, 0.15])
    level = {"centre": 1.8, "north": 1.15, "east": 0.7, "south": 1.0, "west": 1.3}
    area = rng.gamma(9, 11, n).round(0) + 25                         # square metres
    rooms = np.clip(np.round(area / 28 + rng.normal(0, 0.8, n)), 1, 8).astype(int)
    age = rng.integers(0, 90, n)
    dist_km = np.where(district == "centre", rng.uniform(0, 3, n), rng.uniform(2, 25, n)).round(1)
    garden = (rng.random(n) < np.clip(dist_km / 20, 0.05, 0.9)).astype(int)
    price = (np.array([level[d] for d in district]) * 900 * np.sqrt(area) - 6 * np.maximum(age - 40, 0) ** 1.2
             - 9 * dist_km + garden * (20 + 3 * dist_km) + 4 * rooms)
    price = price * np.exp(rng.normal(0, 0.07, n))                  # multiplicative noise, about 7 %
    df = pd.DataFrame({"district": district, "area_m2": area, "rooms": rooms, "age_years": age,
                       "dist_km": dist_km, "garden": garden, "price_k": (price / 100).round(1)})
    df.loc[rng.random(n) < 0.03, "age_years"] = np.nan             # a few missing ages
    return df

df = make_housing()
X, y = df.drop(columns="price_k"), df["price_k"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)   # the test set waits until the end
num = ["area_m2", "rooms", "age_years", "dist_km", "garden"]
prep_linear = ColumnTransformer([("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
                                 ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["district"])]).set_output(transform="pandas")
prep_trees = ColumnTransformer([("num", SimpleImputer(strategy="median"), num),
                                ("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["district"])]).set_output(transform="pandas")
models = {
    "baseline (median)": DummyRegressor(strategy="median"),
    "ridge regression":  make_pipeline(prep_linear, RidgeCV(alphas=np.logspace(-2, 3, 20))),
    "random forest":     make_pipeline(prep_trees, RandomForestRegressor(n_estimators=100, min_samples_leaf=3, random_state=0, n_jobs=1)),
    "LightGBM":          make_pipeline(prep_trees, lgb.LGBMRegressor(n_estimators=300, learning_rate=0.05, num_leaves=15,
                                                                     verbose=-1, n_jobs=1, random_state=0)),
}
cv = KFold(5, shuffle=True, random_state=0)
print(f"{'model':18s}  CV MAE (k)        CV R^2")
for name, model in models.items():
    r = cross_validate(model, X_tr, y_tr, cv=cv, scoring=("neg_mean_absolute_error", "r2"))
    mae = -r["test_neg_mean_absolute_error"]
    print(f"{name:18s}  {mae.mean():6.1f} +/- {mae.std():4.1f}   {r['test_r2'].mean():.3f}")
model               CV MAE (k)        CV R^2
baseline (median)     28.4 +/-  0.9   -0.022
ridge regression       7.0 +/-  0.2   0.937
random forest          6.6 +/-  0.2   0.945
LightGBM               6.8 +/-  0.2   0.941

Reading the result. Every model is far better than the baseline. The random forest is best (MAE 6.6k), but the margins between the three real models are small compared with a typical price of about 110k, and only about twice the fold-to-fold spread of 0.2k. Plain ridge regression is surprisingly close: most of the price is a smooth function of a few features. Before tuning the forest, ask why the linear model is close and what it misses.

Step 3: improve with what you know

The district level multiplies the price, and a multiplicative structure becomes additive after a logarithm: log⁡(price)=log⁡(level)+12log⁡(area)+…\log(\text{price}) = \log(\text{level}) + \frac{1}{2}\log(\text{area}) + \dots for the main terms. A linear model on log⁡(price)\log(\text{price}), with log⁡(area)\log(\text{area}) as an extra feature, can express that. TransformedTargetRegressor fits on the log and converts predictions back:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, KFold, cross_validate
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, FunctionTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import RidgeCV

def make_housing(n=1500, seed=0):
    """A generated housing table (prices in thousands). Nonlinear on purpose: size has diminishing returns,
    age matters only for old houses, each district has its own price level, and a garden adds more far out."""
    rng = np.random.default_rng(seed)
    district = rng.choice(["centre", "north", "east", "south", "west"], n, p=[0.15, 0.25, 0.2, 0.25, 0.15])
    level = {"centre": 1.8, "north": 1.15, "east": 0.7, "south": 1.0, "west": 1.3}
    area = rng.gamma(9, 11, n).round(0) + 25                         # square metres
    rooms = np.clip(np.round(area / 28 + rng.normal(0, 0.8, n)), 1, 8).astype(int)
    age = rng.integers(0, 90, n)
    dist_km = np.where(district == "centre", rng.uniform(0, 3, n), rng.uniform(2, 25, n)).round(1)
    garden = (rng.random(n) < np.clip(dist_km / 20, 0.05, 0.9)).astype(int)
    price = (np.array([level[d] for d in district]) * 900 * np.sqrt(area) - 6 * np.maximum(age - 40, 0) ** 1.2
             - 9 * dist_km + garden * (20 + 3 * dist_km) + 4 * rooms)
    price = price * np.exp(rng.normal(0, 0.07, n))                  # multiplicative noise, about 7 %
    df = pd.DataFrame({"district": district, "area_m2": area, "rooms": rooms, "age_years": age,
                       "dist_km": dist_km, "garden": garden, "price_k": (price / 100).round(1)})
    df.loc[rng.random(n) < 0.03, "age_years"] = np.nan             # a few missing ages
    return df

df = make_housing()
X, y = df.drop(columns="price_k"), df["price_k"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
num = ["area_m2", "rooms", "age_years", "dist_km", "garden"]
# prices are multiplicative (district level x size): model log(price), with log(area) as a feature
log_area = FunctionTransformer(np.log)
prep = ColumnTransformer([("logarea", make_pipeline(log_area, StandardScaler()), ["area_m2"]),
                          ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
                          ("cat", OneHotEncoder(handle_unknown="ignore"), ["district"])])
log_ridge = TransformedTargetRegressor(make_pipeline(prep, RidgeCV(alphas=np.logspace(-2, 3, 20))),
                                       func=np.log, inverse_func=np.exp)
cv = KFold(5, shuffle=True, random_state=0)
r = cross_validate(log_ridge, X_tr, y_tr, cv=cv, scoring=("neg_mean_absolute_error", "r2"))
print(f"ridge on log(price)  CV MAE {-r['test_neg_mean_absolute_error'].mean():.1f}  CV R^2 {r['test_r2'].mean():.3f}")
ridge on log(price)  CV MAE 6.1  CV R^2 0.953

Reading the result. The log-target ridge (MAE 6.1k, R2R^2 0.953) beats every model of step 2, including the forest and LightGBM, on the same cross-validation folds. Understanding the structure of the problem mattered more than the choice of algorithm. It is the model to take to the test set. Strictly, choosing it after looking at five cross-validated scores makes its CV score slightly optimistic; the test set in the next step checks that.

Step 4: test once, then analyse the errors

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer, TransformedTargetRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, FunctionTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import RidgeCV
from sklearn.metrics import mean_absolute_error, r2_score

def make_housing(n=1500, seed=0):
    """A generated housing table (prices in thousands). Nonlinear on purpose: size has diminishing returns,
    age matters only for old houses, each district has its own price level, and a garden adds more far out."""
    rng = np.random.default_rng(seed)
    district = rng.choice(["centre", "north", "east", "south", "west"], n, p=[0.15, 0.25, 0.2, 0.25, 0.15])
    level = {"centre": 1.8, "north": 1.15, "east": 0.7, "south": 1.0, "west": 1.3}
    area = rng.gamma(9, 11, n).round(0) + 25                         # square metres
    rooms = np.clip(np.round(area / 28 + rng.normal(0, 0.8, n)), 1, 8).astype(int)
    age = rng.integers(0, 90, n)
    dist_km = np.where(district == "centre", rng.uniform(0, 3, n), rng.uniform(2, 25, n)).round(1)
    garden = (rng.random(n) < np.clip(dist_km / 20, 0.05, 0.9)).astype(int)
    price = (np.array([level[d] for d in district]) * 900 * np.sqrt(area) - 6 * np.maximum(age - 40, 0) ** 1.2
             - 9 * dist_km + garden * (20 + 3 * dist_km) + 4 * rooms)
    price = price * np.exp(rng.normal(0, 0.07, n))                  # multiplicative noise, about 7 %
    df = pd.DataFrame({"district": district, "area_m2": area, "rooms": rooms, "age_years": age,
                       "dist_km": dist_km, "garden": garden, "price_k": (price / 100).round(1)})
    df.loc[rng.random(n) < 0.03, "age_years"] = np.nan             # a few missing ages
    return df

df = make_housing()
X, y = df.drop(columns="price_k"), df["price_k"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
num = ["area_m2", "rooms", "age_years", "dist_km", "garden"]
prep = ColumnTransformer([("logarea", make_pipeline(FunctionTransformer(np.log), StandardScaler()), ["area_m2"]),
                          ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num),
                          ("cat", OneHotEncoder(handle_unknown="ignore"), ["district"])])
final = TransformedTargetRegressor(make_pipeline(prep, RidgeCV(alphas=np.logspace(-2, 3, 20))),
                                   func=np.log, inverse_func=np.exp).fit(X_tr, y_tr)
pred = final.predict(X_te)                             # the test set is used once, here
print(f"test MAE {mean_absolute_error(y_te, pred):.1f}k  test R^2 {r2_score(y_te, pred):.3f}  ({len(y_te)} houses)")
err = pd.DataFrame({"district": X_te["district"], "abs_err": np.abs(pred - y_te), "pct_err": np.abs(pred - y_te) / y_te})
print(err.groupby("district").agg(houses=("abs_err", "size"), MAE=("abs_err", "mean"), MAPE=("pct_err", "mean")).round(3).to_string())
worst = np.argsort(-np.abs(pred - y_te.to_numpy()))[:3]
print(X_te.iloc[worst].assign(price=y_te.iloc[worst], predicted=pred[worst].round(1)).to_string())
test MAE 6.6k  test R^2 0.950  (300 houses)
          houses     MAE   MAPE
district
centre        47  10.447  0.059
east          54   3.677  0.056
north         73   6.810  0.059
south         80   5.724  0.059
west          46   7.022  0.059
     district  area_m2  rooms  age_years  dist_km  garden  price  predicted
408     north    100.0      4       24.0     12.1       1  126.5      102.6
1026   centre    146.0      5       35.0      2.5       1  171.5      194.6
182    centre     92.0      4       48.0      1.2       0  177.1      154.0

Reading the result. The test MAE (6.6k) is a little above the cross-validated 6.1k, within what you expect from 300 houses and the selection effect just mentioned, and R2R^2 is 0.950. Broken down by district, the absolute error is largest in the centre (10.4k) and smallest in the east (3.7k), but the relative error (MAPE) is about 6 % everywhere: the model's errors are proportional to the price, as the multiplicative noise in the data predicts. The worst predictions are off by about 23k; inspecting them is how you find missing features in real data (a renovated kitchen, a noisy road).

Part B: customer segments with k-means

A shop's 600 customers, described by visits per month, average basket and the share bought on discount (plus tenure, which is not used for clustering). The features are standardised, kk is chosen with the inertia and the silhouette, and the segments are profiled in the original units:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

def make_customers(n=600, seed=0):
    """A generated customer table with four hidden behaviour types."""
    rng = np.random.default_rng(seed)
    kind = rng.choice(4, n, p=[0.4, 0.25, 0.2, 0.15])
    visits = rng.poisson(np.array([2, 8, 3, 12])[kind])                     # visits per month
    basket = rng.gamma(4, np.array([8, 6, 30, 18])[kind] / 4)               # average spend per visit
    discount = np.clip(rng.normal(np.array([0.1, 0.45, 0.05, 0.2])[kind], 0.08), 0, 1)   # share bought on discount
    tenure = rng.integers(1, 120, n)                                        # months as a customer, unrelated
    return pd.DataFrame({"visits": visits, "basket": basket.round(2), "discount_share": discount.round(2),
                         "tenure_m": tenure})

df = make_customers()
features = ["visits", "basket", "discount_share"]
Xs = StandardScaler().fit_transform(df[features])
print(" k  inertia  silhouette")
for k in range(2, 8):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(Xs)
    print(f"{k:2d}  {km.inertia_:7.1f}  {silhouette_score(Xs, km.labels_):.3f}")
km = KMeans(n_clusters=4, n_init=10, random_state=0).fit(Xs)
profile = df.assign(segment=km.labels_).groupby("segment").agg(
    customers=("visits", "size"), visits=("visits", "mean"), basket=("basket", "mean"),
    discount_share=("discount_share", "mean"), tenure_m=("tenure_m", "mean"))
print(profile.round(2).to_string())
 k  inertia  silhouette
 2   1036.3  0.441
 3    681.1  0.468
 4    435.7  0.517
 5    370.1  0.424
 6    328.6  0.404
 7    296.0  0.315
         customers  visits  basket  discount_share  tenure_m
segment
0              287    2.28   10.12            0.11     61.67
1               90   12.56   18.29            0.20     65.06
2               68    3.13   42.25            0.06     56.91
3              155    7.66    6.44            0.46     60.32

Reading the result. The silhouette peaks at k=4k = 4 (0.517) and the drops in inertia shrink after 4. The four segments are easy to name from their profiles: occasional small-basket shoppers (the largest group, 287 customers), frequent loyal customers (12.6 visits a month), rare big-basket shoppers (average basket 42) and discount hunters (46 % bought on offer). Tenure, which was not used, is similar across segments: the segments describe behaviour, not how long people have been customers. Before acting on segments, check that they are stable (cluster a resample, as in Evaluating and Comparing Clusterings) and that they differ in an outcome that matters, such as response to a campaign.

Write-up template

Copy this into your notebook or report and fill it in for Part A (adapt it for Part B):

text
1. Problem      What is predicted, for whom, and what decision it supports.
2. Data         Source, licence and privacy notes, rows and columns, target, missing values,
                anything unusual. Train/test split and why.
3. Metric       Main metric (and why it fits the decision), secondary metrics.
4. Validation   Cross-validation scheme, same folds for all models, what was tuned and where.
5. Models       Baseline, linear, forest, boosting: CV mean and spread in one table.
6. Improvement  What the data suggested (e.g. a log target) and its effect, on the same folds.
7. Final test   The chosen model's test score, used once. Compare it with its CV estimate.
8. Errors       Where the model fails (by segment, worst cases) and likely causes.
9. Limits       What the model cannot do (extrapolation, new districts, drift), and risks.
10. Next steps  More data, more features, monitoring, retraining plan.

Extensions

  1. Run step 2 with load_diabetes instead of the generated table. Which model wins there, and by how much?
  2. Tune the random forest and LightGBM with RandomizedSearchCV inside nested cross-validation (Comparison Bench). Do they catch up with the log-target ridge?
  3. Replace SimpleImputer(strategy="median") by KNNImputer and check whether the CV score changes.
  4. For Part B, fit a Gaussian mixture and compare the number of components BIC prefers with the silhouette's choice.
  5. Look at the generator: which of its effects (the age threshold, the garden bonus that grows with distance) does the log-ridge model capture only roughly? Add a feature for one of them and measure the change with the same folds.

Test yourself

Why is the test set split off in step 2 and used only in step 4?

  1. To make training faster
  2. So the final score measures a model whose every choice was made without it
  3. Because LightGBM needs it
  4. To balance the districts

Why did ridge regression on log⁡(price)\log(\text{price}) beat the tree ensembles?

  1. Ridge is always better than trees
  2. Prices were multiplicative, which a log turns into the additive structure a linear model fits exactly
  3. The trees were not given the district
  4. LightGBM cannot do regression

In Part B, why are the features standardised before k-means?

  1. k-means needs values between 0 and 1
  2. Visits, basket size and discount share are on different scales, and k-means uses Euclidean distance
  3. To remove outliers
  4. To choose kk