Docsity

Hands-On Machine Learning with Scikit-Learn – Chapter 2 Detailed Notes, Study notes of Introduction to Machine Learning

Toggle sidebar
bg1
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
1. Look at the big picture.
2. Get the data.
3. Discover and visualize the data to gain insights.
4. Prepare the data for Machine Learning algorithms.
5. Select a model and train it.
6. Fine-tune your model.
7. Present your solution.
8. Launch, monitor, and maintain your system.
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.
• Business Objective: The model's prediction of a district's median housing price will be fed
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.
• Current Solution: District housing prices are currently estimated manually by experts using
complex rules. This is costly and time-consuming, and estimates are often off by more than
10% compared to actual median housing prices.
• Problem Framing:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Hands-On Machine Learning with Scikit-Learn – Chapter 2 Detailed Notes and more Study notes Introduction to Machine Learning in PDF only on Docsity!

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

  1. Look at the big picture.
  2. Get the data.
  3. Discover and visualize the data to gain insights.
  4. Prepare the data for Machine Learning algorithms.
  5. Select a model and train it.
  6. Fine-tune your model.
  7. Present your solution.
  8. Launch, monitor, and maintain your system.

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.

  • Business Objective: The model's prediction of a district's median housing price will be fed

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.

  • Current Solution: District housing prices are currently estimated manually by experts using

complex rules. This is costly and time-consuming, and estimates are often off by more than

10% compared to actual median housing prices.

  • Problem Framing:

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.

  • Equation 2-1: Root Mean Square Error (RMSE)

( 𝑖

)

( 𝑖

)

2

𝑚

𝑖= 1

  • Notations :

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

  • Instances and Attributes: The head () method reveals that each row represents one district,

and there are 10 attributes: longitude, latitude, housing_median_age, total_rooms,

total_bedrooms, population, households, median_income, median_house_value, and

ocean_proximity.

  • Data Size: The dataset contains 20,640 instances.
  • Missing Features: The info () method shows that total_bedrooms has only 20,433 non-null

values, meaning 207 districts are missing this feature.

  • Categorical Attribute: ocean_proximity is an object type (text attribute) and is probably

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

  • Numerical Summary: The describe() method provides statistics for numerical attributes.
  • Histograms and Data Quirks (Observed from attribute histograms):
  1. Median Income: Does not look like it is expressed in USD. It has been scaled and capped at

15 (15.0001) for higher incomes and 0.5 (0.4999) for lower incomes.

  1. Housing Median Age and Median House Value: These were also capped. Capping the

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.

  1. Scales: Attributes have very different scales, suggesting the need for feature scaling later.
  2. Distribution: Many histograms are tail heavy , extending farther to the right of the median

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.

  • Setting the alpha option to 0.1 reveals high-density areas, namely the Bay Area, around Los

Angeles and San Diego, and the Central Valley.

  • Visualizing prices: Setting the radius (s option) to represent population and the color (c

option, using the jet color map for blue (low values) to red (high prices)) represents the

median house value.

  • A scatter matrix (using pandas.tools.plotting.scatter_matrix()) plots every numerical

attribute against every other numerical attribute. The main diagonal displays a histogram of

each attribute.

  • Zooming in on the correlation between median_income and median_house_value shows a

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.

  • Example: The total number of rooms is less useful than the number of rooms per

household.

  • Example: Comparing the total number of bedrooms to total rooms yields

bedrooms_per_room.

  • Example: Population per household seems interesting.
  • These new attributes (rooms_per_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).

  1. Get rid of the corresponding districts (using dropna()).
  2. Get rid of the whole attribute (using drop()).
  3. Set the values to some value (zero, mean, the median , etc.) (using fillna()).

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) :

  • Estimators: Any object that estimates some parameters (e.g., Imputer). Training is done

using the fit() method, which requires a dataset and returns the estimator itself.

  • Transformers: Estimators that transform a dataset (e.g., Imputer transforms a dataset by

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().

  • Predictors: Estimators capable of making predictions (e.g., LinearRegression). Predictors

have a predict() method and a score() method to measure quality.

  • Inspection: All estimator hyperparameters are accessible via public instance variables

(e.g., imputer.strategy), and all learned parameters are accessible via public instance

variables with an underscore suffix (e.g., imputer.statistics_).

  • Nonproliferation of classes: Datasets are represented as NumPy arrays or SciPy sparse

matrices.

  • Composition: Existing building blocks can be reused, such as creating a Pipeline estimator.
  • Sensible defaults: Scikit-Learn provides reasonable default values for most parameters.

Handling Text and Categorical Attributes

The categorical attribute ocean_proximity must be converted to numbers.

  • One-Hot Encoding: Categorical features are typically converted into a set of binary

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).

  • Scikit-Learn's CategoricalEncoder (used in the provided notebook example) converts the

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).

  • Example: Creating an CombinedAttributesAdder transformer to add the composite

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:

  • Min-max scaling (Normalization): Values are shifted and rescaled to range from 0 to 1,

achieved by subtracting the minimum value and dividing by the max minus the min. Scikit-

Learn provides MinMaxScaler.

  • Standardization: Subtracts the mean value (resulting in zero mean) and divides by the

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.

  • Example: A numerical pipeline (num_pipeline) using DataFrameSelector, Imputer (with

median strategy), CombinedAttributesAdder, and StandardScaler.

  • Example: A categorical pipeline (cat_pipeline) using DataFrameSelector and

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).

  • A Decision Tree trained without constraints is prone to severe overfitting (performing well on

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”).

  • Launch: Get the solution ready for production, plug in production input data sources, and

write tests.

  • Maintenance: Continuously monitor the system’s live performance (e.g., using

dashboards), monitor input data quality, and retrain models regularly on fresh data.