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:
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:
%%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>
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
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)))
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.
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
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:
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))
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');
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.
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.
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]]
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();
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');
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();
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');
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();
hide_code
sns.jointplot(x, y, kind='hex', joint_kws={'alpha':0.8}, size=12, color='#348ABD');
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.
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:
r2_score
from sklearn.metrics to perform a performance calculation between y_true
and y_predict
;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
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?
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))
$\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.
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.
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.")
What is the benefit to splitting a dataset into some ratio of training and testing subsets for a learning algorithm?
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.
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.
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.
hide_code
# Produce learning curves for varying training set sizes and maximum depths
ModelLearning(features, prices)
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?
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.
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.
hide_code
ModelComplexity(X_train, y_train)
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?
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.
Which maximum depth do you think results in a model that best generalizes to unseen data? What intuition lead you to this answer?
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.
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?
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.
What is the k-fold cross-validation training technique? What benefit does this technique provide for grid search when optimizing a model?
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.
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:
DecisionTreeRegressor
from sklearn.tree to create a decision tree regressor object.'regressor'
variable.make_scorer
from sklearn.metrics to create a scoring function object.performance_metric()
function as a parameter to the object.'scoring_fnc'
variable.GridSearchCV
from sklearn.grid_search to create a grid search object.'regressor'
, 'params'
, 'scoring_fnc'
, and 'cv_sets'
as parameters to the object.GridSearchCV
object to the 'grid'
variable.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
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.
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']))
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?
Based on the constructed model, the predictions were as follows.
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))
We can compare them to the real prices for the housing of the considered database, extracting items with roughly the same indicators.
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)])
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.
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.
hide_code
PredictTrials(features, prices, fit_model, client_data)
In a few sentences, discuss whether the constructed model should or should not be used in a real-world setting.
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:
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.
hide_code
reg
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.