Last active
December 22, 2018 04:37
-
-
Save linnil1/71913d747b82d71099be205040962782 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
np.set_printoptions(2) | |
dataY = np.array([1, -1, 1, 1, 1, | |
-1, -1, 1, -1, -1]) | |
dataX = np.arange(len(dataY)) | |
print('X ', dataX) | |
print('Y ', dataY) | |
class DecisionStump(): | |
def __init__(self, u): | |
self.a = 0 | |
self.b = 1 | |
self.u = u | |
def evaluate(self, x): | |
return self.b * (2 * (x < self.a) - 1) | |
def loss(self): | |
cond = dataY * self.evaluate(dataX) < 0 | |
return np.sum(self.u[cond]) / np.sum(self.u) | |
def findOpt(self): | |
min_loss = np.Inf | |
opt = [] | |
for i in range(len(dataY) + 1): | |
for j in range(-1, 2, 2): | |
self.a = i | |
self.b = j | |
l = self.loss() | |
if l < min_loss: | |
min_loss = l | |
opt = (i, j) | |
self.a, self.b = opt | |
print('error', min_loss) | |
print('a, b ', opt) | |
assert(min_loss <= .5) | |
def getAlpha(self): | |
e = self.loss() | |
return np.log((1 - e) / e) / 2 | |
def getNextU(self): | |
u = np.copy(self.u) | |
alpha = self.getAlpha() | |
u *= np.exp(-alpha * self.evaluate(dataX) * dataY) | |
print('alpha', alpha) | |
print('NEWu ', u) | |
return u | |
u = np.ones(len(dataY)) | |
boost = [] | |
for i in range(3): | |
print('\n', i + 1) | |
f = DecisionStump(u) | |
f.findOpt() | |
u = f.getNextU() | |
boost.append(f) | |
print('\n', 'All') | |
predict = [] | |
for f in boost: | |
predict.append(f.getAlpha() * f.evaluate(dataX)) | |
predict = np.sum(predict, axis=0) | |
print('predict', predict) | |
print('binary', 2 * (predict >= 0) - 1) | |
print(dataY) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OUTPUT