-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boston_housing.py
242 lines (167 loc) · 7.77 KB
/
boston_housing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# coding: utf-8
# In[26]:
"""Load the Boston dataset and examine its target (label) distribution."""
# Load libraries
import numpy as np
import pylab as pl
from sklearn import datasets
from sklearn.tree import DecisionTreeRegressor
################################
### ADD EXTRA LIBRARIES HERE ###
################################
from sklearn import cross_validation
from sklearn import metrics
from sklearn import grid_search
def load_data():
"""Load the Boston dataset."""
boston = datasets.load_boston()
return boston
def explore_city_data(city_data):
"""Calculate the Boston housing statistics."""
# Get the labels and features from the housing data
housing_prices = city_data.target
housing_features = city_data.data
###################################
### Step 1. YOUR CODE GOES HERE ###
###################################
# Please calculate the following values using the Numpy library
# Size of data (number of houses)?
print "Data Size: ", np.ptp(housing_prices)
# Number of features?
print "Features: ", np.ptp(housing_features)
# Minimum price?
print "Minimum Price: ", np.amin(housing_prices)
# Maximum price?
print "Maximum Price: ", np.amax(housing_prices)
# Calculate mean price?
print "Mean Price: ", np.mean(housing_prices)
# Calculate median price?
print "Median Price: ", np.median(housing_prices)
# Calculate standard deviation?
print "Standard Deviation: ", np.std(housing_prices)
def split_data(city_data):
"""Randomly shuffle the sample set. Divide it into 70 percent training and 30 percent testing data."""
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
###################################
### Step 2. YOUR CODE GOES HERE ###
###################################
kf = cross_validation.KFold(len(city_data.data),3, shuffle= True, random_state=0)
for train_indicies, test_indicies in kf:
X_train, X_test = X[train_indicies], X[test_indicies]
y_train, y_test = y[train_indicies], y[test_indicies]
return X_train, y_train, X_test, y_test
def performance_metric(label, prediction):
"""Calculate and return the appropriate error performance metric."""
###################################
### Step 3. YOUR CODE GOES HERE ###
###################################
loss = metrics.mean_squared_error(label, prediction)
return loss
# The following page has a table of scoring functions in sklearn:
# http://scikit-learn.org/stable/modules/classes.html#sklearn-metrics-metrics
pass
def learning_curve(depth, X_train, y_train, X_test, y_test):
"""Calculate the performance of the model after a set of training data."""
# We will vary the training set size so that we have 50 different sizes
sizes = np.round(np.linspace(1, len(X_train), 50))
train_err = np.zeros(len(sizes))
test_err = np.zeros(len(sizes))
print "Decision Tree with Max Depth: "
print depth
for i, s in enumerate(sizes):
# Create and fit the decision tree regressor model
regressor = DecisionTreeRegressor(max_depth=depth)
regressor.fit(X_train[:s], y_train[:s])
# Find the performance on the training and testing set
train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s]))
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot learning curve graph
learning_curve_graph(sizes, train_err, test_err)
def learning_curve_graph(sizes, train_err, test_err):
"""Plot training and test error as a function of the training size."""
pl.figure()
pl.title('Decision Trees: Performance vs Training Size')
pl.plot(sizes, test_err, lw=2, label = 'test error')
pl.plot(sizes, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Training Size')
pl.ylabel('Error')
pl.show()
def model_complexity(X_train, y_train, X_test, y_test):
"""Calculate the performance of the model as model complexity increases."""
print "Model Complexity: "
# We will vary the depth of decision trees from 2 to 25
max_depth = np.arange(1, 25)
train_err = np.zeros(len(max_depth))
test_err = np.zeros(len(max_depth))
for i, d in enumerate(max_depth):
# Setup a Decision Tree Regressor so that it learns a tree with depth d
regressor = DecisionTreeRegressor(max_depth=d)
# Fit the learner to the training data
regressor.fit(X_train, y_train)
# Find the performance on the training set
train_err[i] = performance_metric(y_train, regressor.predict(X_train))
# Find the performance on the testing set
test_err[i] = performance_metric(y_test, regressor.predict(X_test))
# Plot the model complexity graph
model_complexity_graph(max_depth, train_err, test_err)
def model_complexity_graph(max_depth, train_err, test_err):
"""Plot training and test error as a function of the depth of the decision tree learn."""
pl.figure()
pl.title('Decision Trees: Performance vs Max Depth')
pl.plot(max_depth, test_err, lw=2, label = 'test error')
pl.plot(max_depth, train_err, lw=2, label = 'training error')
pl.legend()
pl.xlabel('Max Depth')
pl.ylabel('Error')
pl.show()
def fit_predict_model(city_data):
"""Find and tune the optimal model. Make a prediction on housing data."""
# Get the features and labels from the Boston housing data
X, y = city_data.data, city_data.target
# Setup a Decision Tree Regressor
regressor = DecisionTreeRegressor()
parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)}
###################################
### Step 4. YOUR CODE GOES HERE ###
###################################
# 1. Find an appropriate performance metric. This should be the same as the
# one used in your performance_metric procedure above:
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html
scorer = metrics.make_scorer(metrics.mean_squared_error, greater_is_better = False)
# 2. We will use grid search to fine tune the Decision Tree Regressor and
# obtain the parameters that generate the best training performance. Set up
# the grid search object here.
# http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html#sklearn.grid_search.GridSearchCV
reg = grid_search.GridSearchCV(regressor, parameters, scorer)
# Fit the learner to the training data to obtain the best parameter set
print "Final Model: "
print reg.fit(X, y)
# Use the model to predict the output of a particular sample
x = [11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385, 24, 680.0, 20.20, 332.09, 12.13]
y = reg.predict(x)
print "House: " + str(x)
print "Prediction: " + str(y)
#In the case of the documentation page for GridSearchCV, it might be the case that the example is just a demonstration of syntax for use of the function, rather than a statement about
def main():
"""Analyze the Boston housing data. Evaluate and validate the
performanance of a Decision Tree regressor on the housing data.
Fine tune the model to make prediction on unseen data."""
# Load data
city_data = load_data()
# Explore the data
explore_city_data(city_data)
# Training/Test dataset split
X_train, y_train, X_test, y_test = split_data(city_data)
# Learning Curve Graphs
max_depths = [1,2,3,4,5,6,7,8,9,10]
for max_depth in max_depths:
learning_curve(max_depth, X_train, y_train, X_test, y_test)
# Model Complexity Graph
model_complexity(X_train, y_train, X_test, y_test)
# Tune and predict Model
fit_predict_model(city_data)
if __name__ == "__main__":
main()
# In[ ]: