forked from Ryuk17/MachineLearning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomForest.py
224 lines (203 loc) · 7.81 KB
/
RandomForest.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
"""
@ Filename: RandomForest.py
@ Author: Danc1elion
@ Create Date: 2019-07-09
@ Update Date: 2019-07-09
@ Description: Implement RandomForest
"""
import numpy as np
import operator as op
import pickle
from DecisionTree import DecisionTreeClassifier
from TreeRegression import RegressionTree
class RandomForestClassifier:
def __init__(self, tree_num=10, alpha=1e-5):
self.tree_num = tree_num
self.alpha=alpha
self.trees = []
self.prediction = None
self.probability = None
'''
Function: boostrap
Description: boostrap sampling and train a model
Input: train_data dataType: ndarray description: features
train_label dataType: ndarray description: labels
self dataType: obj description: the trained model
'''
def boostrap(self, train_data, train_label):
index = np.random.randint(0, len(train_data), (len(train_data)))
x = train_data[index]
y = train_label[index]
clf = DecisionTreeClassifier(t=self.alpha)
clf.train(x, y)
return clf
'''
Function: train
Description: train the model
Input: train_data dataType: ndarray description: features
train_label dataType: ndarray description: labels
Output: self dataType: obj description: the trained model
'''
def train(self, train_data, train_label):
for i in range(self.tree_num):
clf = self.boostrap(train_data, train_label)
self.trees.append(clf)
return self
'''
Function: vote
Description: return the label of the majority
Input: labels dataType: ndarray description: labels
Output: pred dataType: int description: prediction label of input vector
'''
def vote(self, labels):
label_count = {}
# get the counts of each label
for c in labels:
label_count[c] = label_count.get(c, 0) + 1
# get the labels of the majority
predition = sorted(label_count.items(), key=op.itemgetter(1), reverse=True)
pred = predition[0][0]
return pred
'''
Function: predict
Description: predict the testing set
Input: test_data dataType: ndarray description: features
Output: prediction dataType: ndarray description: the prediction results for testing set
'''
def predict(self, test_data):
labels = np.zeros([len(test_data), self.tree_num])
for i in range(self.tree_num):
clf = self.trees[i]
labels[:, i] = clf.predict(test_data).reshape(len(test_data))
prediction = np.zeros([len(test_data)])
for j in range(len(labels)):
prediction[j] = self.vote(labels[j,:])
self.prediction = prediction
return prediction
'''
Function: showDetectionResult
Description: show detection result
Input: test_data dataType: ndarray description: data for test
test_label dataType: ndarray description: labels of test data
Output: accuracy dataType: float description: detection accuarcy
'''
def accuarcy(self, test_label):
prediction = self.prediction
accuarcy = sum(prediction == test_label)/len(test_label)
return accuarcy
'''
Function: save
Description: save the model as pkl
Input: filename dataType: str description: the path to save model
'''
def save(self, filename):
f = open(filename, 'w')
model = self.trees
pickle.dump(model, f)
f.close()
'''
Function: load
Description: load the model
Input: filename dataType: str description: the path to save model
Output: self dataType: obj description: the trained model
'''
def load(self, filename):
f = open(filename)
self.trees = pickle.load(f)
return self
class RandomForestRegression:
def __init__(self, tree_num=10, error_threshold=1, N=4, alpha=0.01):
self.sample_num = 0
self.tree_num = tree_num
self.trees = []
self.error_threshold = error_threshold # the threshold of error
self.N = N # the least number of sample for split
self.alpha = alpha
self.tree_node = None
self.prediction = None
'''
Function: boostrap
Description: boostrap sampling and train a model
Input: train_data dataType: ndarray description: features
train_label dataType: ndarray description: labels
self dataType: obj description: the trained model
'''
def boostrap(self, train_data, train_label):
index = np.random.randint(0, self.sample_num, (self.sample_num))
x = train_data[index]
y = train_label[index]
clf = RegressionTree(error_threshold=1, N=4, alpha=0.01)
clf.train(x, y)
return clf
'''
Function: train
Description: train the model
Input: train_data dataType: ndarray description: features
train_label dataType: ndarray description: labels
Output: self dataType: obj description: the trained model
'''
def train(self, train_data, train_label):
for i in range(self.tree_num):
clf = self.boostrap(train_data, train_label)
self.trees.append(clf)
return self
'''
Function: vote
Description: return the label of the majority
Input: labels dataType: ndarray description: labels
Output: pred dataType: int description: prediction label of input vector
'''
def vote(self, labels):
label_count = {}
# get the counts of each label
for c in labels:
label_count[c] = label_count.get(c, 0) + 1
# get the labels of the majority
predition = sorted(label_count.items(), key=op.itemgetter(1), reverse=True)
pred = predition[0][0]
return pred
'''
Function: predict
Description: predict the testing set
Input: test_data dataType: ndarray description: features
Output: prediction dataType: ndarray description: the prediction results for testing set
'''
def predict(self, test_data):
labels = np.zeros([len(test_data), self.tree_num])
for i in range(self.tree_num):
labels[:,i] = self.trees[i].predict(test_data)
prediction = np.mean(labels, axis=0)
self.prediction = prediction
return prediction
'''
Function: showDetectionResult
Description: show detection result
Input: test_data dataType: ndarray description: data for test
test_label dataType: ndarray description: labels of test data
Output: accuracy dataType: float description: detection accuarcy
'''
def accuarcy(self, test_label):
test_label = np.expand_dims(test_label, axis=1)
prediction = self.prediction
accuarcy = sum(prediction == test_label)/len(test_label)
return accuarcy
'''
Function: save
Description: save the model as pkl
Input: filename dataType: str description: the path to save model
'''
def save(self, filename):
f = open(filename, 'w')
model = self.trees
pickle.dump(model, f)
f.close()
'''
Function: load
Description: load the model
Input: filename dataType: str description: the path to save model
Output: self dataType: obj description: the trained model
'''
def load(self, filename):
f = open(filename)
self.trees = pickle.load(f)
return self