This notebook continues the starting_your_ml_project
tutorial while working with the Iowa housing data instead of the Melbourne data.
In [1]:
import pandas as pd
filepath = 'input/train.csv'
iowa = pd.read_csv(filepath)
print(iowa.head())
iowa.describe()
Out[1]:
Now it's time for you to define and fit a model for your data (in your notebook).
Select the target variable you want to predict.
You can go back to the list of columns from your earlier commands to recall what it's called (hint: you've already worked with this variable).
Save this to a new variable called y.
Create a list of the names of the predictors we will use in the initial model.
Use just the following columns in the list (you may need to remove or replace NaN values from some of the predictors):
Using the list of variable names you just created, select a new DataFrame of the predictors data.
Save this with the variable name X.
Create a DecisionTreeRegressorModel and save it to a variable (with a name like my_model or iowa_model).
Ensure you've done the relevant import so you can run this command.
Fit the model you have created using the data in X and the target data you saved above.
Make a few predictions with the model's predict command and print out the predictions.
In [2]:
y = iowa.SalePrice
y.describe()
Out[2]:
In [3]:
iowa.columns
Out[3]:
In [4]:
iowa_predictors = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
X = iowa[iowa_predictors]
X.describe()
Out[4]:
In [5]:
from sklearn.tree import DecisionTreeRegressor
iowa_model = DecisionTreeRegressor()
iowa_model.fit(X,y)
Out[5]:
In [6]:
print(X.head())
iowa_model.predict(X.head())
Out[6]:
You've built a model.
But how good is it?
You'll need to answer this question for every model you ever build.
In most (though not necessarily all) applications, the relevant measure of model quality is predictive accuracy.
In other words, will the model's predictions be close to what actually happens?
Some people try answering this problem by making predictions with their training data.
They compare those predictions to the actual target values in the training data.
This approach has a critical shortcoming, which you will see in a moment (and which you'll subsequently see how to solve).
Even with this simple approach, you'll need to summarize the model quality into a form that someone can understand.
If you have predicted and actual home values for 10,000 houses, you will inevitably end up with a mix of good and bad predictions.
Looking through such a long list would be pointless.
There are many metrics for summarizing model quality, but we'll start with one called Mean Absolute Error (also called MAE).
Let's break down this metric starting with the last word, error.
The prediction error for each house is:
error = actual − predicted
So, if a house cost \$150,000 and you predicted it would cost \$100,000, then the error is \$50,000.
With the MAE metric, we take the absolute value of each error.
This converts each error to a positive number.
We then take the average of those absolute errors.
This is our measure of model quality.
In plain English, it can be said as:
"On average, our predictions are off by about X".
In [7]:
from sklearn.metrics import mean_absolute_error as mae
predicted_home_prices = iowa_model.predict(X)
mae(y, predicted_home_prices)
Out[7]:
The measure we just computed can be called an "in-sample" score.
We used a single set of houses (called a data sample) for both building the model and for calculating it's MAE score.
This is bad.
Imagine that, in the large real estate market, door color is unrelated to home price.
However, in the sample of data you used to build the model, it may be that all homes with green doors were very expensive.
The model's job is to find patterns that predict home prices, so it will see this pattern, and it will always predict high prices for homes with green doors.
Since this pattern was originally derived from the training data, the model will appear accurate in the training data.
But this pattern likely won't hold when the model sees new data, and the model would be very inaccurate (and cost us lots of money) when we applied it to our real estate business.
Even a model capturing only happenstance relationships in the data, relationships that will not be repeated when new data, can appear to be very accurate on in-sample accuracy measurements.
Models' practical value come from making predictions on new data, so we should measure performance on data that wasn't used to build the model.
The most straightforward way to do this is to exclude some data from the model-building process, and then use those to test the model's accuracy on data it hasn't seen before.
This data is called validation data.
The scikit-learn
library has a function called train_test_split()
to break up the data into two pieces, so the code to get a validation score looks like this:
In [8]:
from sklearn.model_selection import train_test_split
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=0)
iowa_model = DecisionTreeRegressor()
iowa_model.fit(train_X, train_y)
# Get the predicted prices for the cross-validation data:
val_predictions = iowa_model.predict(val_X)
print(mae(val_y, val_predictions))
Now that you have a trustworthy way to measure model accuracy, you can experiment with alternative models and see which gives the best predictions.
But what alternatives do you have for models?
You can see in scikit-learn's documentation that the decision tree model has many options (more than you'll want or need for a long time).
The most important options determine the tree's depth.
Recall from earlier that a tree's depth is a measure of how many splits it makes before coming to a prediction.
In practice, it's not uncommon for a tree to have 10 splits between the top level (all houses and a leaf).
As the tree gets deeper, the dataset gets sliced up into leaves with fewer houses.
If a tree only had 1 split, it divides the data into 2 groups.
If each group is split again, we would get 4 groups of houses.
Splitting each of those again would create 8 groups.
If we keep doubling the number of groups by adding more splits at each level, we'll have 210 groups of houses by the time we get to the 10th level.
That's 1024 leaves!
When we divide the houses between many leaves, we also have fewer houses in each leaf.
Leaves with very few houses will make predictions that are quite close to those homes' actual values, but they may make very unreliable predictions for new data (because each prediction is based on only a few houses).
This is a phenomenon called overfitting, where a model matches the training data almost perfectly, but does poorly in validation and other new data.
On the flip side, if we make our tree very shallow, it doesn't divide up the houses into very distinct groups.
At an extreme, if a tree divides houses into only 2 or 4, each group still has a wide variety of houses.
Resulting predictions may be far off for most houses, even in the training data (and it will be bad in validation too for the same reason).
When a model fails to capture important distinctions and patterns in the data, so it performs poorly even in training data, that is called underfitting.
Since we care about accuracy on new data, which we estimate from our validation data, we want to find the sweet spot between underfitting and overfitting.
There are a few alternatives for controlling the tree depth, and many allow for some routes through the tree to have greater depth than other routes.
But the max_leaf_nodes
argument provides a very sensible way to control overfitting vs underfitting.
The more leaves we allow the model to make, the more we move from the underfitting area in the above graph to the overfitting area.
We can use a utility function to help compare MAE scores from different values for max_leaf_nodes
:
In [9]:
from sklearn.metrics import mean_absolute_error
from sklearn.tree import DecisionTreeRegressor
def get_mae(max_leaf_nodes, predictors_train, predictors_val, targ_train, targ_val):
model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
model.fit(predictors_train, targ_train)
preds_val = model.predict(predictors_val)
mae = mean_absolute_error(targ_val, preds_val)
return(mae)
The data is loaded into train_X, val_X, train_y,
and val_y
just like before, and a little repetition never hurt anyone:
In [10]:
import pandas as pd
file_path = 'input/train.csv'
iowa_data = pd.read_csv(file_path)
# Filter the rows with missing data:
iowa_data = iowa_data.dropna(axis=0)
# Choose the target and predictors:
y = iowa_data.SalePrice
iowa_predictors = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd']
X = iowa_data[iowa_predictors]
Now we can split our data into training and cross-validation datasets for both the target and the predictors.
In [11]:
train_X, val_X, train_y, val_y = train_test_split(X, y, random_state=0)
A for-loop can be used to compare the accuracy of the models built with different values for max_leaf_nodes
.
In [12]:
# Compare MAE with the different values of max_leaf_nodes:
for max_leaf_nodes in [5, 50, 500, 5000]:
from sklearn.tree import DecisionTreeRegressor
my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
print("Max leaf nodes: %d \t\t Mean Absolute Error: %d" %(max_leaf_nodes, my_mae))
In [ ]: