-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbagging_regression.py
74 lines (59 loc) · 1.95 KB
/
bagging_regression.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
# https://deeplearningcourses.com/c/machine-learning-in-python-random-forest-adaboost
# https://www.udemy.com/machine-learning-in-python-random-forest-adaboost
from __future__ import print_function, division
from builtins import range, input
# Note: you may need to update your version of future
# sudo pip install -U future
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.utils import shuffle
# create the data
T = 100
x_axis = np.linspace(0, 2*np.pi, T)
y_axis = np.sin(x_axis)
# get the training data
N = 30
idx = np.random.choice(T, size=N, replace=False)
Xtrain = x_axis[idx].reshape(N, 1)
Ytrain = y_axis[idx]
# try a lone decision tree
model = DecisionTreeRegressor()
model.fit(Xtrain, Ytrain)
prediction = model.predict(x_axis.reshape(T, 1))
print("score for 1 tree:", model.score(x_axis.reshape(T, 1), y_axis))
# plot the lone decision tree's predictions
plt.plot(x_axis, prediction)
plt.plot(x_axis, y_axis)
plt.show()
# now try bagging
class BaggedTreeRegressor:
def __init__(self, B):
self.B = B
def fit(self, X, Y):
N = len(X)
self.models = []
for b in range(self.B):
idx = np.random.choice(N, size=N, replace=True)
Xb = X[idx]
Yb = Y[idx]
model = DecisionTreeRegressor()
model.fit(Xb, Yb)
self.models.append(model)
def predict(self, X):
predictions = np.zeros(len(X))
for model in self.models:
predictions += model.predict(X)
return predictions / self.B
def score(self, X, Y):
d1 = Y - self.predict(X)
d2 = Y - Y.mean()
return 1 - d1.dot(d1) / d2.dot(d2)
model = BaggedTreeRegressor(200)
model.fit(Xtrain, Ytrain)
print("score for bagged tree:", model.score(x_axis.reshape(T, 1), y_axis))
prediction = model.predict(x_axis.reshape(T, 1))
# plot the bagged regressor's predictions
plt.plot(x_axis, prediction)
plt.plot(x_axis, y_axis)
plt.show()