Machine Learning Engineer Nanodegree

Model Evaluation and Validation

📑   P1: Predicting Boston Housing Prices

Getting Started

Dataset

In this project, we will evaluate the performance and predictive power of a model that has been trained and tested on data collected from homes in suburbs of Boston, Massachusetts. A model trained on this data that is seen as a good fit could then be used to make certain predictions about a home — in particular, its monetary value. This model would prove to be invaluable for someone like a real estate agent who could make use of such information on a daily basis.

Origin: This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University.

Creators: Harrison, D. and Rubinfeld, D.L.

Data Set Information: Concerns housing values in suburbs of Boston.

Attribute Information:

  • CRIM: per capita crime rate by town
  • ZN: proportion of residential land zoned for lots over 25,000 sq.ft.
  • INDUS: proportion of non-retail business acres per town
  • CHAS: Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
  • NOX: nitric oxides concentration (parts per 10 million)
  • RM: average number of rooms per dwelling
  • AGE: proportion of owner-occupied units built prior to 1940
  • DIS: weighted distances to five Boston employment centres
  • RAD: index of accessibility to radial highways
  • TAX: full-value property-tax rate per 10,000 USD
  • PTRATIO: pupil-teacher ratio by town
  • B: 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
  • LSTAT: % lower status of the population
  • MEDV: Median value of owner-occupied homes in 1000 USD

The Boston housing data was collected in 1978 and each of the 506 entries represents aggregated data about 14 features for homes from various suburbs.

For the purposes of this project, the following preprocessing steps have been made to the dataset:

  • 16 data points have an 'MEDV' value of 50.0. These data points likely contain missing or censored values and have been removed.
  • 1 data point has an 'RM' value of 8.78. This data point can be considered an outlier and has been removed.
  • The features 'RM', 'LSTAT', 'PTRATIO', and 'MEDV' are essential. The remaining non-relevant features have been excluded.
  • The feature 'MEDV' has been multiplicatively scaled to account for 35 years of market inflation.

Resources

Code Library

In [1]:
%%html
<style>
@import url('https://fonts.googleapis.com/css?family=Orbitron|Roboto');
body {background-color: aliceblue;} 
a {color: #4876ff; font-family: 'Roboto';} 
h1 {color: #348ABD; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #ccc;} 
h2, h3 {color: slategray; font-family: 'Orbitron'; text-shadow: 4px 4px 4px #ccc;}
h4 {color: #348ABD; font-family: 'Roboto';}
span {text-shadow: 4px 4px 4px #ccc;}
div.output_prompt, div.output_area pre {color: slategray;}
div.input_prompt, div.output_subarea {color: #4876ff;}      
div.output_stderr pre {background-color: aliceblue;}  
div.output_stderr {background-color: slategrey;}                        
</style>
<script>
code_show = true; 
function code_display() {
    if (code_show) {
        $('div.input').each(function(id) {
            if (id == 0 || $(this).html().indexOf('hide_code') > -1) {$(this).hide();}
        });
        $('div.output_prompt').css('opacity', 0);
    } else {
        $('div.input').each(function(id) {$(this).show();});
        $('div.output_prompt').css('opacity', 1);
    };
    code_show = !code_show;
} 
$(document).ready(code_display);
</script>
<form action="javascript: code_display()">
<input style="color: #348ABD; background: aliceblue; opacity: 0.8;" \ 
type="submit" value="Click to display or hide code cells">
</form>                       
In [6]:
hide_code = ''
# Import libraries necessary for this project
import numpy as np
import pandas as pd
import pylab as plt
from sklearn import datasets

################################
### ADD EXTRA LIBRARIES HERE ###
################################
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
import seaborn as sns

from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score, make_scorer
from sklearn.tree import DecisionTreeRegressor
import sklearn.learning_curve as curves
from sklearn.cross_validation import ShuffleSplit

# Make matplotlib show our plots inline 
%matplotlib inline
In [44]:
hide_code
# https://github.com/udacity/machine-learning/blob/master/projects/boston_housing/visuals.py
def ModelLearning(X, y):
    """ Calculates the performance of several models with varying sizes of training data.
        The learning and testing scores for each model are then plotted. """
    
    # Create 10 cross-validation sets for training and testing
    cv = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.2, random_state = 0)

    # Generate the training set sizes increasing by 50
    train_sizes = np.rint(np.linspace(1, X.shape[0]*0.8 - 1, 9)).astype(int)

    # Create the figure window
    fig = plt.figure(figsize=(18, 12))
    plt.style.use('seaborn-whitegrid')

    # Create three different models based on max_depth
    for k, depth in enumerate([1,3,6,10]):
        
        # Create a Decision tree regressor at max_depth = depth
        regressor = DecisionTreeRegressor(max_depth = depth)

        # Calculate the training and testing scores
        sizes, train_scores, test_scores = curves.learning_curve(regressor, X, y, \
            cv = cv, train_sizes = train_sizes, scoring = 'r2')
        
        # Find the mean and standard deviation for smoothing
        train_std = np.std(train_scores, axis = 1)
        train_mean = np.mean(train_scores, axis = 1)
        test_std = np.std(test_scores, axis = 1)
        test_mean = np.mean(test_scores, axis = 1)

        # Subplot the learning curve 
        ax = fig.add_subplot(2, 2, k+1)
        ax.plot(sizes, train_mean, 'o-', color = '#E24A33', label = 'Training Score')
        ax.plot(sizes, test_mean, 'o-', color = '#348ABD', label = 'Testing Score')
        ax.fill_between(sizes, train_mean - train_std, \
            train_mean + train_std, alpha = 0.15, color = '#E24A33')
        ax.fill_between(sizes, test_mean - test_std, \
            test_mean + test_std, alpha = 0.15, color = '#348ABD')
        
        # Labels
        ax.set_title('max_depth = %s'%(depth))
        ax.set_xlabel('Number of Training Points')
        ax.set_ylabel('Score')
        ax.set_xlim([0, X.shape[0]*0.8])
        ax.set_ylim([-0.05, 1.05])
    
    # Visual aesthetics
    ax.legend(bbox_to_anchor=(1.05, 2.05), loc='lower left', borderaxespad = 0.)
    fig.suptitle('Decision Tree Regressor Learning Performances', fontsize = 16, y = 1.03)
    fig.tight_layout()
    fig.show()

def ModelComplexity(X, y):
    """ Calculates the performance of the model as model complexity increases.
        The learning and testing errors rates are then plotted. """
    
    # Create 10 cross-validation sets for training and testing
    cv = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.2, random_state = 0)

    # Vary the max_depth parameter from 1 to 10
    max_depth = np.arange(1, 11)

    # Calculate the training and testing scores
    train_scores, test_scores = curves.validation_curve(DecisionTreeRegressor(), X, y, \
        param_name = "max_depth", param_range = max_depth, cv = cv, scoring = 'r2')

    # Find the mean and standard deviation for smoothing
    train_mean = np.mean(train_scores, axis=1)
    train_std = np.std(train_scores, axis=1)
    test_mean = np.mean(test_scores, axis=1)
    test_std = np.std(test_scores, axis=1)

    # Plot the validation curve
    plt.figure(figsize=(18, 6))
    plt.title('Decision Tree Regressor Complexity Performance')
    plt.plot(max_depth, train_mean, 'o-', color = '#E24A33', label = 'Training Score')
    plt.plot(max_depth, test_mean, 'o-', color = '#348ABD', label = 'Validation Score')
    plt.fill_between(max_depth, train_mean - train_std, \
        train_mean + train_std, alpha = 0.15, color = '#E24A33')
    plt.fill_between(max_depth, test_mean - test_std, \
        test_mean + test_std, alpha = 0.15, color = '#348ABD')
    
    # Visual aesthetics
    plt.legend(loc = 'lower right')
    plt.xlabel('Maximum Depth')
    plt.ylabel('Score')
    plt.ylim([-0.05,1.05])
    plt.show()

def PredictTrials(X, y, fitter, data):
    """ Performs trials of fitting and predicting data. """

    # Store the predicted prices
    prices = []

    for k in range(10):
        # Split the data
        X_train, X_test, y_train, y_test = train_test_split(X, y, \
            test_size = 0.2, random_state = k)
        
        # Fit the data
        reg = fitter(X_train, y_train).best_estimator_
        
        # Make a prediction
        pred = reg.predict([data[0]])[0]
        prices.append(pred)
        
        # Result
        print ("Trial {}: ${:,.2f}".format(k+1, pred))

    # Display price range
    print ("\nRange in prices: ${:,.2f}".format(max(prices) - min(prices)))

Data Exploration

In this first section of this project, we will make a cursory investigation about the Boston housing data and provide the observations. Familiarizing ourself with the data through an explorative process is a fundamental practice to help us better understand and justify the results.

Since the main goal of this project is to construct a working model which has the capability of predicting the value of houses, we will need to separate the dataset into the features and the target variable. The features, 'RM', 'LSTAT', and 'PTRATIO', give us quantitative information about each data point. The target variable, 'MEDV', will be the variable we seek to predict. These are stored in features and prices, respectively.

In [8]:
hide_code
# Load the Boston housing dataset
data = pd.read_csv('housing.csv')
prices = data['MEDV']
features = data.drop('MEDV', axis = 1)
    
# Success
print ("Boston housing dataset has {} data points with {} variables each.".format(*data.shape))
data.describe().T
Boston housing dataset has 489 data points with 4 variables each.
Out[8]:
count mean std min 25% 50% 75% max
RM 489.0 6.240288 0.643650 3.561 5.88 6.185 6.575 8.398
LSTAT 489.0 12.939632 7.081990 1.980 7.37 11.690 17.120 37.970
PTRATIO 489.0 18.516564 2.111268 12.600 17.40 19.100 20.200 22.000
MEDV 489.0 454342.944785 165340.277653 105000.000 350700.00 438900.000 518700.000 1024800.000

Implementation: Calculate Statistics

For the very first coding implementation, we will calculate descriptive statistics about the Boston housing prices. Since numpy has already been imported, this library is used to perform the necessary calculations. These statistics will be extremely important later on to analyze various prediction results from the constructed model. In the code cell below, we will need to implement the following:

  • Calculate the minimum, maximum, mean, median, and standard deviation of 'MEDV', which is stored in prices.
  • Store each calculation in their respective variable.
In [9]:
hide_code
print ("Boston Housing Dataset Statistics: \n")
print ("Number of houses = ", len(prices))
print ("Number of features = ", len(list(features.keys())))
print ("Minimum house price = ", np.min(prices))
print ("Maximum house price = ", np.max(prices))
print ("Mean house price = ", "%.2f" % np.mean(prices))
print ("Median house price = ", "%.2f" % np.median(prices))
print ("Standard deviation of house prices =", "%.2f" % np.std(prices))
Boston Housing Dataset Statistics: 

Number of houses =  489
Number of features =  3
Minimum house price =  105000.0
Maximum house price =  1024800.0
Mean house price =  454342.94
Median house price =  438900.00
Standard deviation of house prices = 165171.13
In [10]:
hide_code
warnings.filterwarnings('ignore')
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(18, 6))
sns.distplot(prices, color='#348ABD')
plt.xlabel("Prices")
plt.title('Boston Housing Data');

Question 1 - Feature Observation

As a reminder, we are using three features from the Boston housing dataset: 'RM', 'LSTAT', and 'PTRATIO'. For each data point (neighborhood):

  • 'RM' is the average number of rooms among homes in the neighborhood.
  • 'LSTAT' is the percentage of homeowners in the neighborhood considered "lower class" (working poor).
  • 'PTRATIO' is the ratio of students to teachers in primary and secondary schools in the neighborhood.

Using your intuition, for each of the three features above, do you think that an increase in the value of that feature would lead to an increase in the value of 'MEDV' or a decrease in the value of 'MEDV'? Justify your answer for each.

Answer 1

My assumptions could be:

  • 'RM': shows the level of home comfort, its increase would lead to the increase in the value of 'MEDV';
  • 'PTRATIO': shows the level of educational resources, its increase would lead to the decrease in the value of 'MEDV';
  • 'LSTAT': indicates the level of social environment comfort, its increase would lead to the decrease in the value of 'MEDV'.

I have made the correlation list for all features in the original dataset to confirm the assumptions and created plots for the transformed features with the least squares regression fitted line and the hexagon-aggregated 2D histograms as an example to illustrate the trends.

In [11]:
hide_code
boston_data = datasets.load_boston()
boston_df = pd.DataFrame(boston_data.data, columns=boston_data.feature_names)
boston_df['MEDV'] = boston_data.target
pearson = boston_df.corr(method='pearson')
corr_with_prices = pearson.ix[-1][:-1]
corr_with_prices[abs(corr_with_prices).argsort()[::-1]]
Out[11]:
LSTAT     -0.737663
RM         0.695360
PTRATIO   -0.507787
INDUS     -0.483725
TAX       -0.468536
NOX       -0.427321
CRIM      -0.385832
RAD       -0.381626
AGE       -0.376955
ZN         0.360445
B          0.333461
DIS        0.249929
CHAS       0.175260
Name: MEDV, dtype: float64
In [12]:
hide_code
plt.figure(figsize=(18, 6))
x, y = features['RM'], prices
x1 = np.array([[v,1] for v in x])
y1 = np.array([[v,1] for v in y])
(slope,bias),_,_,_ = np.linalg.lstsq(x1,y1)
y_lin = x1 * slope + bias
plt.scatter(x1, y1, color='#348ABD', marker='*', facecolors='none', label='Original data')
plt.scatter(x1, y_lin, color='#104E8B', marker='v', facecolors='none', label='Fitted line')
plt.xlabel("Feature 'RM'")
plt.ylabel("Prices")
plt.title('Boston Housing Data')
plt.legend();
In [13]:
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');
In [14]:
hide_code
plt.figure(figsize=(18, 6))
x = features['PTRATIO']
x1 = np.array([[v,1] for v in x])
(slope,bias),_,_,_ = np.linalg.lstsq(x1,y1)
y_lin = x1 * slope + bias
plt.scatter(x1, y1, color='#348ABD', marker='*', facecolors='none', label='Original data')
plt.scatter(x1, y_lin, color='#104E8B', marker='v', facecolors='none', label='Fitted line')
plt.xlabel("Feature 'PTRATIO'")
plt.ylabel("Prices")
plt.title('Boston Housing Data')
plt.legend();
In [15]:
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');
In [16]:
hide_code
plt.figure(figsize=(18, 6))
x = features['LSTAT']
x1 = np.array([[v,1] for v in x])
(slope,bias),_,_,_ = np.linalg.lstsq(x1,y1)
y_lin = x1 * slope + bias
plt.scatter(x1, y1, color='#348ABD', marker='*', facecolors='none', label='Original data')
plt.scatter(x1, y_lin, color='#104E8B', marker='v', facecolors='none', label='Fitted line')
plt.xlabel("Feature 'LSTAT'")
plt.ylabel("Prices")
plt.title('Boston Housing Data')
plt.legend();
In [17]:
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');

Developing a Model

In this section of the project, we will develop the tools and techniques necessary for a model to make a prediction. Being able to make accurate evaluations of each model's performance through the use of these tools and techniques helps to greatly reinforce the confidence in the predictions.

Implementation: Define a Performance Metric

It is difficult to measure the quality of a given model without quantifying its performance over training and testing.

This is typically done using some type of performance metric, whether it is through calculating some type of error, the goodness of fit, or some other useful measurement. For this project, we will be calculating the coefficient of determination, $\color{#348ABD}{R^2}$, to quantify the model's performance. The coefficient of determination for a model is a useful statistic in regression analysis, as it often describes how "good" that model is at making predictions.

The values for $\color{#348ABD}{R^2}$ range from 0 to 1, which captures the percentage of squared correlation between the predicted and actual values of the target variable. A model with an $\color{#348ABD}{R^2}$ of 0 is no better than a model that always predicts the mean of the target variable, whereas a model with an $\color{#348ABD}{R^2}$ of 1 perfectly predicts the target variable. Any value between 0 and 1 indicates what percentage of the target variable, using this model, can be explained by the features. A model can be given a negative $\color{#348ABD}{R^2}$ as well, which indicates that the model is arbitrarily worse than one that always predicts the mean of the target variable.

For the performance_metric() function, we will need to implement the following:

  • use r2_score from sklearn.metrics to perform a performance calculation between y_true and y_predict;
  • assign the performance score to the score variable.
In [18]:
hide_code
# Import 'r2_score'
def performance_metric(y_true, y_predict):
    """ Calculates and returns the performance score between 
        true and predicted values based on the metric chosen. """
    
    # Calculate the performance score between 'y_true' and 'y_predict'
    score = r2_score(y_true, y_predict)
    
    # Return the score
    return score

Question 2 - Goodness of Fit

Assume that a dataset contains five data points and a model made the following predictions for the target variable:

True Value Prediction
3.0 2.5
-0.5 0.0
2.0 2.1
7.0 7.8
4.2 5.3

Would you consider this model to have successfully captured the variation of the target variable? Why or why not?

In [19]:
hide_code
# Calculate the performance of this model
score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3])
print ("Model has a coefficient of determination, R^2, of {:.3f}.".format(score))
Model has a coefficient of determination, R^2, of 0.923.

Answer 2

$\color{#348ABD}{R^2}$ indicates the performance of the model between the predicted and observed values of the target variable very well (especially for linear regression). It is close to 1 and seems that the model predicts quite accurately.

But we must be extremely careful with the conclusions in the case of a small amount of data. In addition, it is unknown whether it is a linear model and how many variables were needed to build it (details are given about the target variable only). Therefore, it can be stated only that a reasonably accurate prediction is possible to build in this case, but it is desirable to have more data.

Implementation: Shuffle and Split Data

The next implementation requires that we take the Boston housing dataset and split the data into training and testing subsets. Typically, the data is splitted and shuffled into a random order when creating the training and testing subsets to remove any bias in the ordering of the dataset.

In [20]:
hide_code
# Shuffle and split the data into training and testing subsets
X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size = 0.2, random_state = 1)

# Success
print ("Training and testing split was successful.")
Training and testing split was successful.

Question 3 - Training and Testing

What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm?

Answer 3

We should not only build a predictive model but also assess the quality of it. Naturally, we would like to know how our predictions will be relatively close to the actual outcomes.

We usually split the data into training and testing subsets exactly for this goal. The training set is used to choose the most effective parameters for given models, but what kind of model we should apply and how the concrete model works we can evaluate with the test set.

It helps to avoid overfitting, i.e. the cases when the built model will fit extremely well for the training sets but will not work with real data because of catching non-existing trends.

Analyzing Model Performance

In this section of the project, we will take a look at several models' learning and testing performances on various subsets of training data. Additionally, we'll investigate one particular algorithm with an increasing max_depth parameter on the full training set to observe how model complexity affects performance. Graphing the model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone.

Learning Curves

The following code cell produces four graphs for a decision tree model with different maximum depths. Each graph visualizes the learning curves of the model for both training and testing as the size of the training set is increased. The shaded region of a learning curve denotes the uncertainty of that curve (measured as the standard deviation). The model is scored on both the training and testing sets using $\color{#348ABD}{R^2}$, the coefficient of determination.

In [21]:
hide_code
# Produce learning curves for varying training set sizes and maximum depths
ModelLearning(features, prices)

Question 4 - Learning the Data

Choose one of the graphs above and state the maximum depth for the model. What happens to the score of the training curve as more training points are added? What about the testing curve? Would having more training points benefit the model?

Answer 4

I would prefer the graph with max_depth=3. As we can see, the training and testing score curves become enough close to 1 and to each other for this depth. These facts are important to fit the model well.

Let's have a look on each curve in this case. With an increase in the training set, the training score curve slowly decreases from 1.0 to 0.81-0.82, and stops to decrease at the level of 300 points.The testing score curve, on the contrary, increases (in the beginning - very rapidly) till the certain level (0.78-0.79) and then stays approximately the same.

Therefore, after 300 points increasing the number of points in the training set would not lead to the better model. Most likely, for improving the accuracy of the model, no more points in the training set are required, we just need to add more variables for analysis.

Complexity Curves

Now we produces a graph for a decision tree model that has been trained and validated on the training data using different maximum depths. The graph shows two complexity curves — one for training and one for validation. Similar to the learning curves, the shaded regions of both the complexity curves denote the uncertainty in those curves, and the model is scored on both the training and validation sets using the performance_metric() function.

In [22]:
hide_code
ModelComplexity(X_train, y_train)

Question 5 - Bias-Variance Tradeoff

When the model is trained with a maximum depth of 1, does the model suffer from high bias or from high variance? How about when the model is trained with a maximum depth of 10? What visual cues in the graph justify your conclusions?

Answer 5

With the maximum depth of 1, the model suffers from high bias and underfitting. The train and test datasets have low scores, it means the model does not represent the true relationship.

With the maximum depth of 10, there are huge gaps between two curves, and I barely see the testing curve. In this case, the model suffers from overfitting and high variance.

The visual cues in the graph confirm these conclusions: at the beginning of the graph both curves are close to each other but far away from the relable score 1; at the end of the graph curves are close to the desired level of accuracy but diverge at a quite big distance from each other.

Question 6 - Best-Guess Optimal Model

Which maximum depth do you think results in a model that best generalizes to unseen data? What intuition lead you to this answer?

Answer 6

The goal of model building is to simultaneously reduce bias and variance as much as possible to obtain as accurate predictions as is feasible. The tradeoff consists of selecting models of different flexibility or complexity and appropriate training sets to minimize these indicators.

The most tradeoff depth seems to equal to 4 in this model: before this point - the level of accuracy is not sufficient, after this point - the curves begin to diverge.

Evaluating Model Performance

In this section of the project, we will construct a model and make a prediction on the client's feature set using an optimized model from fit_model().

What is the grid search technique and how it can be applied to optimize a learning algorithm?

Answer 7

The grid search is a possible method for tuning the model and provides a set of possible values for each parameter. This algorithm automatically runs the model using each of these parameters and then selects the best ones according to a certain performance metric.

Question 8 - Cross-Validation

What is the k-fold cross-validation training technique? What benefit does this technique provide for grid search when optimizing a model?

Answer 8

The k-fold cross-validation is a model evaluation method to optimize the use of the training and testing data. The original sample is randomly partitioned into k equal size subsamples. One of subsamples is retained as the validation data for testing the model, and the remaining k-1 subsamples are used as training data. The process repeated k times, each of the k subsamples is used exactly once as the validation data.

The residual evaluations do not give an indication of how well the model will make new predictions for the future or unknown data. The cross validation helps to overcome it and test the performance of the learned model on independent data (the testing set).

In our case the grid search algorithm will choose the best parameters for the trained model and evaluate it using cross validation to avoid overfitting and optimize the result with limited data.

Implementation: Fitting a Model

The final implementation requires that we bring everything together and train a model using the decision tree algorithm. To ensure that you are producing an optimized model, we will train the model using the grid search technique to optimize the 'max_depth' parameter for the decision tree. The 'max_depth' parameter can be thought of as how many questions the decision tree algorithm is allowed to ask about the data before making a prediction. Decision trees are part of a class of algorithms called supervised learning algorithms.

In addition, we will use ShuffleSplit() for an alternative form of cross-validation. While it is not the K-Fold cross-validation technique we describe in Question 8, this type of cross-validation technique is just as useful!. The ShuffleSplit() implementation will create 10 ('n_splits') shuffled sets, and for each shuffle, 20% ('test_size') of the data will be used as the validation set.

Please note that ShuffleSplit() has different parameters in scikit-learn versions 0.17 and 0.18.

For the fit_model function in the code cell below, you will need to implement the following:

  • Use DecisionTreeRegressor from sklearn.tree to create a decision tree regressor object.
    • Assign this object to the 'regressor' variable.
  • Create a dictionary for 'max_depth' with the values from 1 to 10, and assign this to the 'params' variable.
  • Use make_scorer from sklearn.metrics to create a scoring function object.
    • Pass the performance_metric() function as a parameter to the object.
    • Assign this scoring function to the 'scoring_fnc' variable.
  • Use GridSearchCV from sklearn.grid_search to create a grid search object.
    • Pass the variables 'regressor', 'params', 'scoring_fnc', and 'cv_sets' as parameters to the object.
    • Assign the GridSearchCV object to the 'grid' variable.
In [39]:
hide_code
from sklearn.model_selection import ShuffleSplit
def fit_model(X, y):
    """ Performs grid search over the 'max_depth' parameter for a 
        decision tree regressor trained on the input data [X, y]. """
    
    # Create cross-validation sets from the training data
    cv_sets = ShuffleSplit(n_splits = 12, test_size = 0.20, random_state = 0)

    # Create a decision tree regressor object
    regressor = DecisionTreeRegressor()

    # Create a dictionary for the parameter 'max_depth' with a range from 1 to 10
    parameters = {'max_depth': [1,2,3,4,5,6,7,8,9,10]}

    # Transform 'performance_metric' into a scoring function using 'make_scorer' 
    scoring_function = make_scorer(performance_metric)

    # Create the grid search object
    grid = GridSearchCV(estimator=regressor, 
                        param_grid=parameters, 
                        scoring=scoring_function,
                        cv=cv_sets)

    # Fit the grid search object to the data to compute the optimal model
    grid = grid.fit(X, y)
    
    # Return the optimal model after fitting the data
    return grid

Making Predictions

Once a model has been trained on a given set of data, it can now be used to make predictions on new sets of input data. In the case of a decision tree regressor, the model has learned what the best questions to ask about the input data are, and can respond with a prediction for the target variable. We can use these predictions to gain information about data where the value of the target variable is unknown — such as data the model was not trained on.

Question 9 - Optimal Model

What maximum depth does the optimal model have? How does this result compare to your guess in Question 6?

Answer 9

The result corresponds to the expressed in the Answer 6 assumptions based on visualization of the model complexity.

In [51]:
hide_code
# Fit the training data to the model using grid search
fit = fit_model(X_train, y_train)
reg = fit.best_estimator_
results = fit.cv_results_

print("Grid Search Process Results")
display(pd.DataFrame(results).T)
# Produce the value for 'max_depth'
print ("\nParameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth']))
Grid Search Process Results
0 1 2 3 4 5 6 7 8 9
mean_fit_time 0.00154384 0.00151024 0.00134869 0.0013838 0.00175532 0.001682 0.00171977 0.00182587 0.00169977 0.00162053
mean_score_time 0.00128617 0.0005759 0.000550489 0.000505865 0.000706573 0.000500361 0.000631313 0.000608285 0.000603358 0.000462055
mean_test_score 0.313527 0.618603 0.751539 0.784497 0.780316 0.777926 0.759249 0.731212 0.723729 0.708287
mean_train_score 0.468268 0.728017 0.829148 0.876785 0.90361 0.927241 0.94824 0.96588 0.979036 0.986638
param_max_depth 1 2 3 4 5 6 7 8 9 10
params {'max_depth': 1} {'max_depth': 2} {'max_depth': 3} {'max_depth': 4} {'max_depth': 5} {'max_depth': 6} {'max_depth': 7} {'max_depth': 8} {'max_depth': 9} {'max_depth': 10}
rank_test_score 10 9 5 1 2 3 4 6 7 8
split0_test_score 0.116582 0.488321 0.685997 0.66404 0.696835 0.709628 0.679946 0.601845 0.592878 0.587325
split0_train_score 0.498357 0.746492 0.841618 0.884824 0.904176 0.920607 0.938588 0.960916 0.97426 0.981337
split10_test_score 0.383377 0.638592 0.766894 0.808644 0.757411 0.754812 0.756497 0.72844 0.707575 0.720276
split10_train_score 0.462824 0.729928 0.832102 0.882113 0.905312 0.926452 0.945185 0.961915 0.981067 0.989133
split11_test_score 0.402363 0.724584 0.790885 0.829662 0.832699 0.813057 0.826786 0.808265 0.82613 0.814158
split11_train_score 0.463418 0.716974 0.822198 0.863986 0.897457 0.92766 0.948726 0.965453 0.977331 0.985584
split1_test_score 0.421773 0.637014 0.762094 0.789359 0.761631 0.730092 0.723707 0.676812 0.710982 0.663283
split1_train_score 0.452616 0.72882 0.838559 0.889819 0.924551 0.944 0.962328 0.974336 0.982276 0.98697
split2_test_score 0.450657 0.705454 0.873412 0.913602 0.906763 0.884287 0.887396 0.863187 0.851036 0.858073
split2_train_score 0.435979 0.684494 0.795742 0.848515 0.880186 0.902345 0.930769 0.953702 0.971898 0.980104
split3_test_score 0.163281 0.551015 0.660528 0.712798 0.704014 0.738917 0.70928 0.691107 0.680305 0.659836
split3_train_score 0.496163 0.744692 0.845384 0.894944 0.917208 0.935437 0.957228 0.975203 0.985109 0.991925
split4_test_score 0.338163 0.659912 0.798542 0.835145 0.821585 0.829667 0.81603 0.821947 0.794967 0.75575
split4_train_score 0.477434 0.737987 0.824278 0.874529 0.90673 0.937272 0.955341 0.968706 0.978166 0.983612
split5_test_score 0.478467 0.70566 0.784054 0.80405 0.771666 0.768734 0.770981 0.729488 0.684294 0.67597
split5_train_score 0.436656 0.72437 0.836905 0.877912 0.903462 0.931656 0.951143 0.968973 0.983198 0.990391
split6_test_score 0.163202 0.513489 0.717398 0.760233 0.757984 0.787053 0.747877 0.691112 0.667006 0.650965
split6_train_score 0.467787 0.735123 0.83096 0.881232 0.904623 0.923846 0.949003 0.964415 0.976139 0.987565
split7_test_score 0.337509 0.708691 0.84634 0.856305 0.848562 0.850314 0.832735 0.810215 0.80751 0.805753
split7_train_score 0.467915 0.718403 0.822715 0.876369 0.903859 0.932735 0.94927 0.96757 0.984723 0.99207
split8_test_score 0.204108 0.487893 0.661571 0.694578 0.749264 0.765759 0.725434 0.707772 0.71221 0.704408
split8_train_score 0.489168 0.73777 0.821267 0.866703 0.888589 0.909274 0.931515 0.956422 0.974436 0.984527
split9_test_score 0.302838 0.602614 0.670753 0.745551 0.755378 0.702792 0.63432 0.644354 0.649853 0.603653
split9_train_score 0.4709 0.731154 0.83805 0.880476 0.907168 0.935608 0.95978 0.972945 0.979833 0.986443
std_fit_time 0.000471099 0.000421229 0.000306117 0.00033932 0.000479389 0.000409701 0.000310963 0.000270179 0.000262753 0.000190525
std_score_time 0.00228182 0.000208413 0.000225742 0.000128196 0.000343652 8.15421e-05 0.000181948 0.000173595 0.000208785 5.17345e-05
std_test_score 0.118225 0.0850716 0.0691419 0.0690774 0.0583937 0.0543396 0.0687273 0.0757436 0.0755982 0.0815673
std_train_score 0.0194757 0.0158126 0.0127494 0.0118926 0.011039 0.0114284 0.00983451 0.00651401 0.00417114 0.00370017
Parameter 'max_depth' is 4 for the optimal model.

Question 10 - Predicting Selling Prices

Imagine that you were a real estate agent in the Boston area looking to use this model to help price homes owned by your clients that they wish to sell. You have collected the following information from three of your clients:

Feature Client 1 Client 2 Client 3
Total number of rooms in home 5 rooms 4 rooms 8 rooms
Neighborhood poverty level (as %) 17% 32% 3%
Student-teacher ratio of nearby schools 15-to-1 22-to-1 12-to-1

What price would you recommend each client sell his/her home at? Do these prices seem reasonable given the values for the respective features?

Answer 10

Based on the constructed model, the predictions were as follows.

In [52]:
hide_code
# Produce a matrix for client data
client_data = [[5, 17, 15], # Client 1
               [4, 32, 22], # Client 2
               [8, 3, 12]]  # Client 3

# Show predictions
for i, price in enumerate(reg.predict(client_data)):
    print ("Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price))
Predicted selling price for Client 1's home: $411,417.39
Predicted selling price for Client 2's home: $230,828.57
Predicted selling price for Client 3's home: $937,230.00

We can compare them to the real prices for the housing of the considered database, extracting items with roughly the same indicators.

In [53]:
hide_code
print(data[(data['RM']>=5)&(data['RM']<5.1)&(data['LSTAT']>=10)&(data['LSTAT']<=20)])
print(data[(data['RM']>=4)&(data['RM']<4.2)&(data['LSTAT']>=30)&(data['LSTAT']<=40)])
print(data[(data['RM']>=8)&(data['RM']<8.2)&(data['LSTAT']>=2)&(data['LSTAT']<=4)])
        RM  LSTAT  PTRATIO      MEDV
152  5.012  12.12     14.7  321300.0
        RM  LSTAT  PTRATIO      MEDV
357  4.138  37.97     20.2  289800.0
       RM  LSTAT  PTRATIO      MEDV
218  8.04   3.13     17.4  789600.0

The predicted prices look reasonable but somewhat overpriced for a more comfortable housing. They can be recommended the clients as the start level for the sales with possible discounts of up to 10%.

The tendency of price change depending on changes in the features under consideration corresponds to the predicted.

Sensitivity

An optimal model is not necessarily a robust model. Sometimes, a model is either too complex or too simple to sufficiently generalize to new data. Sometimes, a model could use a learning algorithm that is not appropriate for the structure of the data given. Other times, the data itself could be too noisy or contain too few samples to allow a model to adequately capture the target variable — i.e., the model is underfitted. We can run the fit_model() function ten times with different training and testing sets to see how the prediction for a specific client changes with the data it's trained on.

In [54]:
hide_code
PredictTrials(features, prices, fit_model, client_data)
Trial 1: $391,183.33
Trial 2: $419,700.00
Trial 3: $415,800.00
Trial 4: $394,523.68
Trial 5: $418,377.27
Trial 6: $411,931.58
Trial 7: $399,663.16
Trial 8: $407,232.00
Trial 9: $402,531.82
Trial 10: $413,700.00

Range in prices: $28,516.67

Question 11 - Applicability

In a few sentences, discuss whether the constructed model should or should not be used in a real-world setting.

  • How relevant today is data that was collected from 1978?
  • Are the features present in the data sufficient to describe a home?
  • Is the model robust enough to make consistent predictions?
  • Would data collected in an urban city like Boston be applicable in a rural city?

Answer 11

The main methods used in the model are statistically justified. Preferences in house choosing change over time very slowly. For the population, the features which are similar to our data are significant in our times as well. Comfort inside, the level of external social environment and city infrastructure development will always be the most reasonable in the housing choice.

For practical application of the model the user has to perform several specific simple steps:

  • collect the set of modern data;
  • update the feature definitions according to the modern trends;
  • add to the model the certain features which are relevant exactly for the considered region;
  • apply the described programming steps.

Conclusion

The goal of this report was to describe the built model that determined the best result in house pricing. Here various statistical and machine learning techniques were applied to predictions and observations. The reader can see the parameters of the final model below.

In [55]:
hide_code
reg
Out[55]:
DecisionTreeRegressor(criterion='mse', max_depth=4, max_features=None,
           max_leaf_nodes=None, min_impurity_decrease=0.0,
           min_impurity_split=None, min_samples_leaf=1,
           min_samples_split=2, min_weight_fraction_leaf=0.0,
           presort=False, random_state=None, splitter='best')

Of course, the model is a little bit outdated. In the modern version, the project can be implemented in the form of an interactive map of recommended prices with the basic indices of living comfort, which can serve as a guide for buyers and sellers.