









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










Chapter 2: End-to-End Machine Learning Project
This chapter guides the reader through an example project end-to-end, acting as a recently hired
data scientist in a real estate company.
Main Steps of the Project
Working with Real Data
It is recommended to experiment with real-world data rather than artificial datasets.
Example Dataset: The California Housing Prices dataset from the StatLib repository is chosen,
based on data from the 1990 California census. The book pretends this is recent data and adds a
categorical attribute while removing a few features for teaching purposes.
Look at the Big Picture
The objective is to build a model of housing prices in California using the California census data,
which includes metrics like the population, median income, and median housing price for each
block group (referred to as "districts"). The model should predict the median housing price in any
district given the other metrics.
Frame the Problem
The first step is to ask about the business objective to determine how to frame the problem, what
algorithms to select, what performance measure to use, and how much effort to spend tweaking the
model.
to another Machine Learning system (a downstream system ) along with other signals (a
piece of information fed to the system). This downstream system will decide if it is worth
investing in a given area, making the prediction critical as it directly affects revenue.
complex rules. This is costly and time-consuming, and estimates are often off by more than
10% compared to actual median housing prices.
o It is a supervised learning task because labeled training examples (instances with
the expected output/median housing price) are provided.
o It is a regression task because the goal is to predict a value.
o It is a multivariate regression problem because multiple features (population,
median income, etc.) will be used for prediction.
o Batch learning is suitable because there is no continuous flow of data, no
immediate need to rapidly adjust to changing data, and the data is small enough to
fit in memory.
o Note on large data: If the data were huge, either splitting the batch learning work
across multiple servers (using MapReduce) or using an online learning technique
would be alternatives.
Select a Performance Measure
A typical performance measure for regression problems is the Root Mean Square Error (RMSE) ,
which estimates the typical error made by the system, assigning a higher weight to large errors.
( 𝑖
)
( 𝑖
)
2
𝑚
𝑖= 1
o m: the number of instances in the dataset being measured (e.g., m = 2,000$ for a
validation set of 2,000 districts).
o 𝑥
( 𝑖
)
: a vector of all the feature values (excluding the label) of the 𝑖
𝑡ℎ
instance.
o 𝑦
(𝑖)
the label (desired output value) of the 𝑖
𝑡ℎ
instance.
▪ Example: If the first district has features: longitude – 118.29°, latitude 33.91°,
1,416 inhabitants, median income of $38,372, and median house value of
$156,400, then:
( 1
)
And
( 1 )
o 𝑋: a matrix containing all the feature values (excluding labels) of all instances. It has
one row per instance, and the 𝑖
𝑡ℎ
row is equal to the transpose o𝑓 𝒙
(𝑖)
: , noted
(𝑖)
𝑇
o $h$: the system's prediction function, or hypothesis. It outputs a predicted value
( 𝑖
( 𝑖
)
) for instance 𝑥
( 𝑖
)
is pronounced “y-hat”).
datasets/housing directory and extracts housing.csv. A small function load_housing_data() is
written to load the data into a Pandas DataFrame object.
Take a Quick Look at the Data Structure
and there are 10 attributes: longitude, latitude, housing_median_age, total_rooms,
total_bedrooms, population, households, median_income, median_house_value, and
ocean_proximity.
values, meaning 207 districts are missing this feature.
categorical due to repetitive values. value_counts() confirms the categories and their
counts:
o <1H OCEAN: 9136
o INLAND: 6551
o NEAR OCEAN: 2658
o NEAR BAY: 2290
o ISLAND: 5
15 (15.0001) for higher incomes and 0.5 (0.4999) for lower incomes.
median_house_value (the target attribute) may be a serious problem, as ML algorithms may learn
prices never go beyond that limit. Options to address this include collecting proper uncapped labels
or removing capped districts from both the training and test sets.
than to the left, which may make it harder for some ML algorithms to detect patterns.
Transformation (e.g., using logarithms) may be needed later to achieve more bell-shaped
distributions.
o The income_cat attribute is then removed so the data returns to its original state.
o Note: Generating the test set is a critical part of a ML project.
Discover and Visualize the Data to Gain Insights
Only the training set should be explored. A copy (housing = strat_train_set.copy()) should be used for
manipulation.
Visualizing Geographical Data
Since geographical information (latitude and longitude) is present, a scatterplot of all districts is
created.
Angeles and San Diego, and the Central Valley.
option, using the jet color map for blue (low values) to red (high prices)) represents the
median house value.
attribute against every other numerical attribute. The main diagonal displays a histogram of
each attribute.
clear upward trend, and a few data quirks are visible (e.g., the capping at $500,000, and
straight horizontal lines at $450,000, $350,000, and $280,000). These vertical lines suggest
domain knowledge may be needed on data processing.
Experimenting with Attribute Combinations
Creating new attributes by combining existing ones can provide deeper insights.
household.
bedrooms_per_room.
population_per_household) show strong correlations; specifically, bedrooms_per_room is
more correlated with median_house_value than total rooms or bedrooms (houses with a
lower bedroom/room ratio tend to be more expensive).
Self-Correction: Using the median is often preferred.
Scikit-Learn provides the Imputer class for handling missing values.
Scikit-Learn Design Principles (Introduced during Data Preparation) :
using the fit() method, which requires a dataset and returns the estimator itself.
filling missing values). Transformation is performed using the transform() method, and
features are learned during fit(). All transformers have a fit_transform() method, which is
equivalent to calling fit() then transform().
have a predict() method and a score() method to measure quality.
(e.g., imputer.strategy), and all learned parameters are accessible via public instance
variables with an underscore suffix (e.g., imputer.statistics_).
matrices.
Handling Text and Categorical Attributes
The categorical attribute ocean_proximity must be converted to numbers.
attributes (one per category), where only one attribute is 1 (hot) and the others are 0. This
prevents ML algorithms from assuming nearby numerical values (e.g., 0 and 1) are more
similar than distant ones (e.g., 0 and 4).
categorical attribute into a sparse matrix of one-hot vectors.
Custom Transformers
Custom transformation classes can be built, typically by inheriting from BaseEstimator (for
get_params() and set_params() support) and TransformerMixin (for fit_transform() shortcut).
attributes discovered during exploration.
Feature Scaling
ML algorithms generally prefer input numerical features to have the same scale. Two common ways
to achieve this are min-max scaling and standardization:
achieved by subtracting the minimum value and dividing by the max minus the min. Scikit-
Learn provides MinMaxScaler.
variance (resulting in unit variance). Standardization does not bound values to a specific
range, but it is much less affected by outliers than min-max scaling. Scikit-Learn provides
StandardScaler.
Transformation Pipelines
Transformations can be executed in the correct order using Scikit-Learn's Pipeline class.
median strategy), CombinedAttributesAdder, and StandardScaler.
CategoricalEncoder.
Select and Train a Model
After transforming the data, a model can be selected.
Training and Evaluating on the Training Set
Start with simple models (e.g., LinearRegression) to get a baseline. Then try a more complex model
(e.g., DecisionTreeRegressor).
training data but poorly on unseen data).
Better Evaluation Using Cross-Validation
To properly evaluate a model and assess generalization error without relying solely on the single
training score, K-fold cross-validation should be used. The training set is split into $K$ unique
subsets (or folds), and the model is trained and evaluated $K$ times, each time using a different
fold for evaluation and the remaining $K-1$ folds for training. The result is an array of scores.
remember statements (e.g., “the median income is the number one predictor of housing
prices”).
write tests.
dashboards), monitor input data quality, and retrain models regularly on fresh data.