🏙 Machine Learning Engineer Nanodegree   🌀   Home Page      

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

🕸UCI Housing Dataset  🕸UCI Machine Learning Repository  🕸scikit-learn. Machine Learning in Python  🕸seaborn: statistical data visualization 

Code Library





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.

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.


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.




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, $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 $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 $R^2$ of 0 is no better than a model that always predicts the mean of the target variable, whereas a model with an $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 $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.

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 ValuePrediction
Would you consider this model to have successfully captured the variation of the target variable? Why or why not?

Answer 2

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

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 and
- 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 the 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 $R^2$, the coefficient of determination.

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.

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

Question 7 - Grid Search

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.
This 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 described 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.
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.model_selection 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.

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.

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:
FeatureClient 1Client 2Client 3
Total number of rooms in home5 rooms4 rooms8 rooms
Neighborhood poverty level (as %)17%32%3%
Student-teacher ratio of nearby schools15-to-122-to-112-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?

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

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.

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.

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.

For Additional Code Experiments