-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathexercise_02.py
292 lines (231 loc) · 9.83 KB
/
exercise_02.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""
Astronomy Tutorial: exercise 2
Photometric redshift determination
usage: python exercise_02.py datadir
- datadir is $TUTORIAL_DIR/data/sdss_photoz
This directory should contain the files:
- sdss_photoz.npy
Here we will take a closer look at the photometric redshift problem discussed
in section 5 of the tutorial. Using the decision tree classifier, we'll take
a look at the 4-color observations of just over 400,000 points.
The point of this exercise is to answer the question: how can we get the rms
error down to below 0.1? Would it be a better use of telescope time to
observe more objects, or to observe additional features of the objects
in the data set? We'll use the techniques discussed in section 3 of the
tutorial.
"""
import os, sys
import numpy as np
import pylab as pl
from sklearn.ensemble import RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn import metrics
try:
datadir = sys.argv[1]
except:
print __doc__
sys.exit()
def compute_rms_error(y_pred, y_true):
"""Compute the rms error between the arrays y_pred and y_true"""
return np.sqrt(metrics.mean_squared_error(y_pred, y_true))
def compute_outlier_fraction(y_pred, y_true, cutoff=0.2):
"""Compute the outlier rate between the arrays y_pred and y_true"""
return np.sum((abs(y_pred - y_true) > cutoff)) * 1. / len(y_pred)
#------------------------------------------------------------
# load data and compute colors
data = np.load(os.path.join(datadir, 'sdss_photoz.npy'))
# here we'll truncate the data to 50,000 points. This will allow the code
# below to be run quickly while it's being written. When you're satisfied
# that the code is ready to go, you can comment out this line.
data = data[:50000]
print '%i points' % data.shape[0]
u, g, r, i, z = [data[f] for f in 'ugriz']
X = np.zeros((len(data), 4))
X[:, 0] = u - g
X[:, 1] = g - r
X[:, 2] = r - i
X[:, 3] = i - z
y = data['redshift']
#------------------------------------------------------------
# divide into training, cross-validation, and test samples
Ntot = len(y)
Ncv = Ntot / 5
Ntest = Ntot / 5
Ntrain = Ntot - Ncv - Ntest
X_train = X[:Ntrain]
y_train = y[:Ntrain]
X_cv = X[Ntrain:Ntrain + Ncv]
y_cv = y[Ntrain:Ntrain + Ncv]
X_test = X[Ntrain + Ncv:]
y_test = y[Ntrain + Ncv:]
#------------------------------------------------------------
# plot the Decision Tree error as a function of max_depth parameter
#
# This is the first main part of the exercise. This is photometric
# redshift determination using DecisionTreeRegressor. Here you'll plot
# the training error and cross-validation error as a function of the
# meta-parameter 'max_depth'.
#
# You will create three arrays: max_depth_array, train_error, and cv_error.
# Use at least 10 different values of max_depth, and compute the training
# and cross-validation error associated with each of them.
#
# note that the error can be computed with the function compute_rms_error()
max_depth_array = []
train_error = []
cv_error = []
#{{{ compute the arrays max_depth_array, train_error, and cv_error
max_depth_array = np.arange(1, 21)
train_error = np.zeros(max_depth_array.shape)
cv_error = np.zeros(max_depth_array.shape)
for i, max_depth in enumerate(max_depth_array):
# print progress update
sys.stdout.write(' %i / %i\r' % (max_depth, max_depth_array[-1]))
sys.stdout.flush()
clf = RandomForestRegressor(10, max_depth=max_depth)
#clf = DecisionTreeRegressor(max_depth=max_depth)
clf.fit(X_train, y_train)
y_train_pred = clf.predict(X_train)
y_cv_pred = clf.predict(X_cv)
train_error[i] = compute_rms_error(y_train_pred, y_train)
cv_error[i] = compute_rms_error(y_cv_pred, y_cv)
#}}}
pl.figure()
pl.plot(max_depth_array, cv_error, label='cross-val error')
pl.plot(max_depth_array, train_error, label='training error')
pl.legend()
pl.xlabel('max depth')
pl.ylabel('error')
# select the value of max_depth which led to the best results
max_depth = max_depth_array[np.argmin(cv_error)]
print "max_depth = %i" % max_depth
#------------------------------------------------------------
# plot the Decision Tree error as a function of number of samples
#
# This is the second main part of the exercise. Here you'll plot the
# training error and cross-validation error as a function of the
# number of training samples.
#
# You will create three arrays: n_samples_array, train_error, and cv_error.
# Use at least 40 different values of n_samples, and compute the training
# and cross-validation error associated with each of them.
#
# Make sure that when computing the training error for each number of
# samples, you use the same samples that the model was trained on.
n_samples_array = []
train_error = []
cv_error = []
#{{{ compute the arrays n_samples_array, train_error, and cv_error
n_samples_array = np.linspace(100, Ntrain, 50).astype(int)
train_error = np.zeros(n_samples_array.shape)
cv_error = np.zeros(n_samples_array.shape)
for i, n_samples in enumerate(n_samples_array):
# print progress update
sys.stdout.write(' %i / %i\r' % (n_samples, Ntrain))
sys.stdout.flush()
clf = RandomForestRegressor(10, max_depth=max_depth)
#clf = DecisionTreeRegressor(max_depth=max_depth)
clf.fit(X_train[:n_samples], y_train[:n_samples])
y_train_pred = clf.predict(X_train[:n_samples])
y_cv_pred = clf.predict(X_cv)
train_error[i] = compute_rms_error(y_train_pred,
y_train[:n_samples])
cv_error[i] = compute_rms_error(y_cv_pred, y_cv)
print
#}}}
pl.figure()
pl.plot(n_samples_array, cv_error, label='cross-val error')
pl.plot(n_samples_array, train_error, label='training error')
pl.legend()
pl.xlabel('number of samples')
pl.ylabel('error')
#----------------------------------------------------------------------
# Use the whole dataset:
# If you have been running your code on only a part of the dataset,
# now that you have it working, you can run it on the full dataset
# (note: this will take a long time to execute!) You can do this by
# commenting out the line
# data = data[:50000]
# above. How does this change the results?
#------------------------------------------------------------
# Catastrophic Outliers
# Though the rms error is one useful measure of the performance of an
# algorithm, astronomers are often more interested in reducing the
# 'catastrophic outlier' rate. Catastrophic outliers are points which
# are given redshifts very far from the true value. For accuracy of
# cosmological results, this is often more important than the overall
# rms error.
#
# Here, you can re-implement te above tasks, plotting the catastrophic
# outlier rate as a function of the max_depth parameter, and as a function
# of the number of training points. This can be accomplished either by
# copying and pasting the above code here, or by modifying the above code.
#
# To compute the catastrophic error rate, you can use the function
# compute_outlier_fraction()
#{{{ repeat the above two plots using catastrophic error rate
max_depth_array = np.arange(1, 21)
train_error = np.zeros(max_depth_array.shape)
cv_error = np.zeros(max_depth_array.shape)
for i, max_depth in enumerate(max_depth_array):
# print progress update
sys.stdout.write(' %i / %i\r' % (max_depth, max_depth_array[-1]))
sys.stdout.flush()
clf = RandomForestRegressor(10, max_depth=max_depth)
#clf = DecisionTreeRegressor(max_depth=max_depth)
clf.fit(X_train, y_train)
y_train_pred = clf.predict(X_train)
y_cv_pred = clf.predict(X_cv)
train_error[i] = compute_outlier_fraction(y_train_pred, y_train)
cv_error[i] = compute_outlier_fraction(y_cv_pred, y_cv)
pl.figure()
pl.plot(max_depth_array, cv_error, label='cross-val error')
pl.plot(max_depth_array, train_error, label='training error')
pl.legend()
pl.xlabel('max depth')
pl.ylabel('error')
# select the value of max_depth which led to the best results
max_depth = max_depth_array[np.argmin(cv_error)]
print "max_depth = %i" % max_depth
#------------------------------------------------------------
# plot the Decision Tree error as a function of number of samples
n_samples_array = np.linspace(100, Ntrain, 50).astype(int)
train_error = np.zeros(n_samples_array.shape)
cv_error = np.zeros(n_samples_array.shape)
for i, n_samples in enumerate(n_samples_array):
# print progress update
sys.stdout.write(' %i / %i\r' % (n_samples, Ntrain))
sys.stdout.flush()
clf = RandomForestRegressor(10, max_depth=max_depth)
#clf = DecisionTreeRegressor(max_depth=max_depth)
clf.fit(X_train[:n_samples], y_train[:n_samples])
y_train_pred = clf.predict(X_train[:n_samples])
y_cv_pred = clf.predict(X_cv)
train_error[i] = compute_outlier_fraction(y_train_pred,
y_train[:n_samples])
cv_error[i] = compute_outlier_fraction(y_cv_pred, y_cv)
print
pl.figure()
pl.plot(n_samples_array, cv_error, label='cross-val error')
pl.plot(n_samples_array, train_error, label='training error')
pl.legend()
pl.xlabel('number of samples')
pl.ylabel('error')
#}}}
#----------------------------------------------------------------------
# Analyze the results
#
# Compare your results to the discussion of bias and variance in section
# 3. How do you think these results could be improved? Is it better to
# spend telescope time increasing the size of the training set, or would
# it be better to measure more features of the objects we already have?
# Does this recommendation change if the astronomer is interested in
# minimizing the number of catastrophic outliers rather than the rms error?
#----------------------------------------------------------------------
# Bonus
# Random Forest Regression uses an ensemble of decision trees to reduce
# the effects of over-fitting.
# Use sklearn.ensemble.RandomForestRegressor and compare the results to
# your decision tree. Does this change the error? Does it change your
# recommendations?
pl.show()