Sub topic 1
What We Are Predicting and Why It Is a Regression Problem
This chapter starts a project that runs from raw data to a saved model. Before writing any modeling code, you decide what the model must predict, what it learns from, and how you will judge it. These choices fix the rest of the project. A wrong framing gives you a model that is accurate on paper and useless in practice.
Prerequisites
This chapter assumes you already have:
- Basic Python: functions, imports, lists and dictionaries.
- Basic pandas: DataFrames, selecting columns, and
describe(). - The idea of supervised learning: a table of features and a target column to predict.
- A Python environment with numpy, pandas, matplotlib and scikit-learn installed.
You do not need to know any specific model yet. Later chapters introduce Ridge regression and gradient boosting.
The task in one sentence
Given a few facts about a neighborhood in California, predict its typical house price.
That sentence contains three decisions:
- The unit of prediction. You predict one value per row of the dataset.
- The inputs. You use facts known before the price is known, such as income and location.
- The output. You predict a number, not a label.
Features, target, and supervised learning
In supervised learning, the training data contains both the inputs and the correct answer for each row. The inputs are called features. The correct answer is the target. The model learns a mapping from features to target, and you then use it on rows where the target is unknown.
By convention, scikit-learn code names the feature table X (capital, because it is two-dimensional) and the target y (lowercase, because it is one-dimensional). You will see this convention throughout the project.
Regression versus classification
A regression problem predicts a continuous number. A classification problem predicts one of a fixed set of categories. House price is continuous: a price can be 1.2, 1.25 or 3.871 in the dataset's units, and the distance between two predictions carries meaning. Predicting 3.9 when the answer is 4.0 is a small miss. Predicting 1.0 is a large one.
| Question | Output type | Problem type | Typical error measure |
|---|---|---|---|
| What is the price of this area? | Continuous number | Regression | Mean absolute error |
| Is this area expensive or cheap? | Category | Classification | Accuracy, precision, recall |
| Which price band is this area in? | Ordered category | Classification (ordinal) | Accuracy, per-class recall |
You could turn the regression into a classification by cutting prices into bands. That throws away information, and it creates edge cases at the band boundaries, where a tiny price difference puts two similar areas in different classes. Keep the numeric target unless the decision you support is really a category.
The California housing data
The project uses the California housing dataset that ships with scikit-learn. It comes from the 1990 US census. Each row describes one block group, a small census area of typically 600 to 3,000 people. A row is not a single house. This matters for interpretation: the target is the median house value in an area, and the features are averages or medians over that area.
| Column | Meaning |
|---|---|
| `MedInc` | Median household income in the block group (tens of thousands of dollars) |
| `HouseAge` | Median age of houses |
| `AveRooms` | Average number of rooms per household |
| `AveBedrms` | Average number of bedrooms per household |
| `Population` | People living in the block group |
| `AveOccup` | Average number of household members |
| `Latitude`, `Longitude` | Location of the block group |
| `MedHouseVal` | **Target.** Median house value, in units of $100,000 |
The dataset has 20,640 rows and 8 features. All features are numeric and there are no missing values, which keeps this first project free of cleaning work.
The units of the target need care. A value of 2.5 means $250,000. The dataset also caps the target at 5.0, so every area worth $500,000 or more is recorded as 5.0. A model trained on this data can never learn that an area is worth more than the cap, and some of its errors come from that.
Checking the framing in code
The next script loads the data, separates features from target, and confirms that the target looks like a continuous number. It needs a network connection the first time, because scikit-learn downloads and caches the file.
from sklearn.datasets import fetch_california_housing
housing = fetch_california_housing(as_frame=True)
X = housing.data
y = housing.target
print("Features:", X.shape)
print("Target: ", y.shape, "name =", y.name)
print("Distinct target values:", y.nunique())
print(y.describe())
print("Share of rows at the cap:", round((y >= 5.0).mean(), 3))Look at the output for three things. The target has thousands of distinct values, which is what a continuous target looks like. The mean is about 2.07, so a typical area is worth about $207,000. A few percent of rows sit exactly at the cap.
You now know that a classifier is the wrong tool. To see what happens when you pick it anyway, run this:
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LogisticRegression
housing = fetch_california_housing(as_frame=True)
try:
LogisticRegression().fit(housing.data, housing.target)
except ValueError as err:
print("ValueError:", str(err)[:60])scikit-learn rejects the call with an error whose message starts with Unknown label type. It checks the target's type and refuses to treat continuous values as classes. Estimators are named after their problem type: LogisticRegression is a classifier despite its name, while Ridge and HistGradientBoostingRegressor are regressors.
Defining success before you model
State how you will measure success before you train anything. If you pick a metric after seeing results, you are tempted to choose the one that flatters the model.
For this project the primary metric is mean absolute error (MAE): the average of the absolute differences between predicted and true values. It is expressed in the target's units, so an MAE of 0.5 means predictions are off by about $50,000 on average. That is easy to explain to a non-technical reader. The project also reports R², which compares your model to a model that always predicts the mean. A later chapter covers MAE, RMSE and R² in detail, including when they disagree.
A metric number means little alone. You also need a reference point, which is why the project builds a baseline early: a trivial model whose error any real model must beat.
The shape of the project
The project follows the order below. Each step depends on the one before it, and the test set stays untouched until the last evaluation.
Common errors when framing a problem
- Treating a number as a class. Binning the target into "cheap" and "expensive" because classification feels more familiar discards information. Keep the numeric target unless the decision truly is a category.
- Reading a row as one house. Each row is a block group. A prediction describes the typical value in an area, not a specific property. Using the model to price one house on a street oversteps what the data supports.
- Misreading units. The target is in $100,000 units, and
MedIncis in $10,000 units. Reporting "MAE of 0.5 dollars" is a unit error. - Ignoring the cap. About 5.0 in the target means "500,000 or more". Errors on those rows are partly an artifact of the data.
- Leaving the target in the features. If
MedHouseValstays inX, the model reads the answer directly and scores almost perfectly. This is one form of leakage, covered in a later chapter. Withas_frame=True,housing.dataexcludes the target, buthousing.frameincludes it, so be careful which one you use. - Choosing the metric afterward. Fix the metric before you compare models.
Exercises
Exercise
A bank wants to predict whether a loan applicant will default (yes or no). A retailer wants to predict next month's sales in dollars. Which is a regression problem, and what property of the target decides it?
Show answer
The retailer's sales forecast is regression, because the target is a continuous number. The loan default prediction is classification, because the target is one of two categories. The type of the target decides the problem type.
Exercise
A model trained on this dataset predicts an MAE of 0.45 on the target. What does that mean in dollars, and why might a prediction of $500,000 for a very expensive area still be too low?
Show answer
An MAE of 0.45 means predictions are off by about $45,000 on average, because the target is in units of $100,000. The dataset caps the target at 5.0 ($500,000), so areas worth more are recorded as 5.0, and the model cannot learn values above that cap.