Sub topic 1
A First End-to-End Project: Predicting House Prices with scikit-learn
Prerequisites
This chapter assumes basic Python, pandas DataFrames, and the supervised learning idea of features and a target. You should also have scikit-learn installed.
What We Are Predicting
We will predict the median house value for a California district. The target is numeric: it is measured in units of $100,000. A prediction such as 2.35 means an estimated value of $235,000.
This is a supervised learning problem because the dataset includes known answers for past examples. It is a regression problem because the answer can take many numeric values. Classification would instead choose among labels such as “low,” “medium,” or “high.”
Our main question is: how close are the predicted prices to the real prices?
Loading the California Housing Data
fetch_california_housing downloads the dataset the first time and then caches it locally. With as_frame=True, scikit-learn returns pandas objects.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
df = housing.frame
print(df.shape)
print(df.head())
print(df.describe())The MedHouseVal column is the target. The other columns are features, such as average rooms, population, and median income.
Looking at the Data Before Modeling
Exploration can reveal the number of rows, column names, ranges, and unusual values. describe() reports counts, means, standard deviations, and percentiles. Check these before choosing preprocessing or a model.
A feature with a large numeric range is not automatically more important. Its units may simply be different.
Choosing How to Measure Error
A metric turns predictions into a number that we can compare.
| Metric | Meaning | Useful when |
|---|---|---|
| MAE | Average absolute error | You want an error in target units |
| RMSE | Penalizes large errors more strongly | Large mistakes are especially costly |
| R² | Variance explained relative to a mean baseline | You want a relative goodness-of-fit measure |
We will use mean absolute error (MAE) as the primary metric. An MAE of 0.5 means predictions miss by about $50,000 on average.
Setting Aside a Test Set
Split the data before modeling. The training set is used to learn. The test set imitates new data and is used later for an honest check.
from sklearn.model_selection import train_test_split
X = df.drop(columns="MedHouseVal")
y = df["MedHouseVal"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(X_train.shape, X_test.shape)The fixed random_state makes the split repeatable.
Exercise
Why should the test set remain untouched while you choose a model?
Show answer
It must represent unseen data; using it during choices leaks information and makes performance look better than it is.