forked from dwave-examples/qboost
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqboost.py
More file actions
392 lines (305 loc) · 12 KB
/
qboost.py
File metadata and controls
392 lines (305 loc) · 12 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# Copyright 2018 D-Wave Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http: // www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, AdaBoostRegressor
import numpy as np
from copy import deepcopy
def weight_penalty(prediction, y, percent = 0.1):
"""
For Regression we have to introduce a metric to penalize differences of the prediction from the label y.
Percent gives the maximum deviation of the prediction from the label that is not penalized.
"""
diff = np.abs(prediction-y)
min_ = diff.min()
max_ = diff.max()
norm = (diff-min_)/(max_-min_)
norm = 1.0*(norm < percent)
return norm
class WeakClassifiers(object):
"""
Weak Classifiers based on DecisionTree
"""
def __init__(self, n_estimators=50, max_depth=3):
self.n_estimators = n_estimators
self.estimators_ = []
self.max_depth = max_depth
self.__construct_wc()
def __construct_wc(self):
self.estimators_ = [DecisionTreeClassifier(max_depth=self.max_depth,
random_state=np.random.randint(1000000,10000000))
for _ in range(self.n_estimators)]
def fit(self, X, y):
"""
fit estimators
:param X:
:param y:
:return:
"""
self.estimator_weights = np.zeros(self.n_estimators)
d = np.ones(len(X)) / len(X)
for i, h in enumerate(self.estimators_):
h.fit(X, y, sample_weight=d)
pred = h.predict(X)
eps = d.dot(pred != y)
if eps == 0: # to prevent divided by zero error
eps = 1e-20
w = (np.log(1 - eps) - np.log(eps)) / 2
d = d * np.exp(- w * y * pred)
d = d / d.sum()
self.estimator_weights[i] = w
def predict(self, X):
"""
predict label of X
:param X:
:return:
"""
if not hasattr(self, 'estimator_weights'):
raise Exception('Not Fitted Error!')
y = np.zeros(len(X))
for (h, w) in zip(self.estimators_, self.estimator_weights):
y += w * h.predict(X)
y = np.sign(y)
return y
def copy(self):
classifier = WeakClassifiers(n_estimators=self.n_estimators, max_depth=self.max_depth)
classifier.estimators_ = deepcopy(self.estimators_)
if hasattr(self, 'estimator_weights'):
classifier.estimator_weights = np.array(self.estimator_weights)
return classifier
class QBoostClassifier(WeakClassifiers):
"""
Qboost Classifier
"""
def __init__(self, n_estimators=50, max_depth=3):
super(QBoostClassifier, self).__init__(n_estimators=n_estimators,
max_depth=max_depth)
def fit(self, X, y, sampler, lmd=0.2, **kwargs):
n_data = len(X)
# step 1: fit weak classifiers
super(QBoostClassifier, self).fit(X, y)
# step 2: create QUBO
hij = []
for h in self.estimators_:
hij.append(h.predict(X))
hij = np.array(hij)
# scale hij to [-1/N, 1/N]
hij = 1. * hij / self.n_estimators
## Create QUBO
qii = n_data * 1. / (self.n_estimators ** 2) + lmd - 2 * np.dot(hij, y)
qij = np.dot(hij, hij.T)
Q = dict()
Q.update(dict(((k, k), v) for (k, v) in enumerate(qii)))
for i in range(self.n_estimators):
for j in range(i + 1, self.n_estimators):
Q[(i, j)] = qij[i, j]
# step 3: optimize QUBO
res = sampler.sample_qubo(Q, **kwargs)
samples = np.array([[samp[k] for k in range(self.n_estimators)] for samp in res])
# take the optimal solution as estimator weights
self.estimator_weights = samples[0]
def predict(self, X):
n_data = len(X)
pred_all = np.array([h.predict(X) for h in self.estimators_])
temp1 = np.dot(self.estimator_weights, pred_all)
T1 = np.sum(temp1, axis=0) / (n_data * self.n_estimators * 1.)
y = np.sign(temp1 - T1) #binary classes are either 1 or -1
return y
class WeakRegressor(object):
"""
Weak Regressor based on DecisionTreeRegressor
"""
def __init__(self, n_estimators=50, max_depth=3, DT = True, Ada = False, ):
self.n_estimators = n_estimators
self.estimators_ = []
self.max_depth = max_depth
self.__construct_wc()
def __construct_wc(self):
self.estimators_ = [DecisionTreeRegressor(max_depth=self.max_depth,
random_state=np.random.randint(1000000,10000000))
for _ in range(self.n_estimators)]
# self.estimators_ = [AdaBoostRegressor(random_state=np.random.randint(1000000,10000000))
# for _ in range(self.n_estimators)]
def fit(self, X, y):
"""
fit estimators
:param X:
:param y:
:return:
"""
self.estimator_weights = np.zeros(self.n_estimators) #initialize all estimator weights to zero
d = np.ones(len(X)) / len(X)
for i, h in enumerate(self.estimators_): #fit all estimators
h.fit(X, y, sample_weight=d)
pred = h.predict(X)
# For classification one simply compares (pred != y)
# For regression we have to define another metric
norm = weight_penalty(pred, y)
eps = d.dot(norm)
if eps == 0: # to prevent divided by zero error
eps = 1e-20
w = (np.log(1 - eps) - np.log(eps)) / 2
d = d * np.exp(- w * y * pred)
d = d / d.sum()
self.estimator_weights[i] = w
def predict(self, X):
"""
predict label of X
:param X:
:return:
"""
if not hasattr(self, 'estimator_weights'):
raise Exception('Not Fitted Error!')
y = np.zeros(len(X))
for (h, w) in zip(self.estimators_, self.estimator_weights):
y += w * h.predict(X)
y = np.sign(y)
return y
def copy(self):
classifier = WeakRegressor(n_estimators=self.n_estimators, max_depth=self.max_depth)
classifier.estimators_ = deepcopy(self.estimators_)
if hasattr(self, 'estimator_weights'):
classifier.estimator_weights = np.array(self.estimator_weights)
return classifier
class QBoostRegressor(WeakRegressor):
"""
Qboost Regressor
"""
def __init__(self, n_estimators=50, max_depth=3):
super(QBoostRegressor, self).__init__(n_estimators=n_estimators,
max_depth=max_depth)
self.Qu = 0.0
self.hij = 0.0
self.var1 = 0.0
self.qij = 0.0
def fit(self, X, y, sampler, lmd=0.2, **kwargs):
n_data = len(X)
# step 1: fit weak classifiers
super(QBoostRegressor, self).fit(X, y)
# step 2: create QUBO
hij = []
for h in self.estimators_:
hij.append(h.predict(X))
hij = np.array(hij)
# scale hij to [-1/N, 1/N]
hij = 1. * hij / self.n_estimators
self.hij = hij
## Create QUBO
qii = n_data * 1. / (self.n_estimators ** 2) + lmd - 2 * np.dot(hij, y)
self.var1 = qii
qij = np.dot(hij, hij.T)
self.qij = qij
Q = dict()
Q.update(dict(((k, k), v) for (k, v) in enumerate(qii)))
for i in range(self.n_estimators):
for j in range(i + 1, self.n_estimators):
Q[(i, j)] = qij[i, j]
self.Qu = Q
# step 3: optimize QUBO
res = sampler.sample_qubo(Q, **kwargs)
samples = np.array([[samp[k] for k in range(self.n_estimators)] for samp in res])
# take the optimal solution as estimator weights
# self.estimator_weights = np.mean(samples, axis=0)
self.estimator_weights = samples[0]
def predict(self, X):
n_data = len(X)
pred_all = np.array([h.predict(X) for h in self.estimators_])
temp1 = np.dot(self.estimator_weights, pred_all)
norm = np.sum(self.estimator_weights)
if norm > 0:
y = temp1 / norm
else:
y = temp1
return y
class QboostPlus(object):
"""
Only for Classifiers
Quantum boost existing (weak) classifiers
"""
def __init__(self, weak_classifier_list):
self.estimators_ = weak_classifier_list
self.n_estimators = len(self.estimators_)
self.estimator_weights = np.ones(self.n_estimators) #estimator weights will be binary (Dwave output)
def fit(self, X, y, sampler, lmd=0.2, **kwargs):
n_data = len(X)
# step 1: create QUBO
hij = []
for h in self.estimators_:
hij.append(h.predict(X))
hij = np.array(hij)
# scale hij to [-1/N, 1/N]
hij = 1. * hij / self.n_estimators
## Create QUBO
qii = n_data * 1. / (self.n_estimators ** 2) + lmd - 2 * np.dot(hij, y)
qij = np.dot(hij, hij.T)
Q = dict()
Q.update(dict(((k, k), v) for (k, v) in enumerate(qii)))
for i in range(self.n_estimators):
for j in range(i + 1, self.n_estimators):
Q[(i, j)] = qij[i, j]
# step 3: optimize QUBO
res = sampler.sample_qubo(Q, **kwargs)
samples = np.array([[samp[k] for k in range(self.n_estimators)] for samp in res])
# take the optimal solution as estimator weights
self.estimator_weights = samples[0]
def predict(self, X):
n_data = len(X)
T = 0
y = np.zeros(n_data)
for i, h in enumerate(self.estimators_):
y0 = self.estimator_weights[i] * h.predict(X) # prediction of weak classifier
y += y0
T += np.sum(y0)
y = np.sign(y - T / (n_data*self.n_estimators))
return y
class QboostPlusRegression(object):
"""
Quantum boost existing (weak) regressors
"""
def __init__(self, weak_Regressor_list):
self.estimators_ = weak_Regressor_list
self.n_estimators = len(self.estimators_)
self.estimator_weights = np.ones(self.n_estimators)
def fit(self, X, y, sampler, lmd=0.2, **kwargs):
n_data = len(X)
# step 1: create QUBO
hij = []
for h in self.estimators_:
hij.append(h.predict(X))
hij = np.array(hij)
# scale hij to [-1/N, 1/N]
hij = 1. * hij / self.n_estimators
## Create QUBO
qii = n_data * 1. / (self.n_estimators ** 2) + lmd - 2 * np.dot(hij, y)
qij = np.dot(hij, hij.T)
Q = dict()
Q.update(dict(((k, k), v) for (k, v) in enumerate(qii)))
for i in range(self.n_estimators):
for j in range(i + 1, self.n_estimators):
Q[(i, j)] = qij[i, j]
# step 3: optimize QUBO
res = sampler.sample_qubo(Q, **kwargs)
samples = np.array([[samp[k] for k in range(self.n_estimators)] for samp in res])
# take the optimal solution as estimator weights
self.estimator_weights = samples[0]
def predict(self, X):
n_data = len(X)
T = 0
y = np.zeros(n_data)
for i, h in enumerate(self.estimators_):
y0 = self.estimator_weights[i] * h.predict(X) # prediction of weak classifier
y += y0
T += np.sum(y0)
norm = np.sum(self.estimator_weights)
if norm > 0:
y = y / norm
else:
y = y
return y