-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclassify.py
96 lines (72 loc) · 2.36 KB
/
classify.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
"""Classifiers that cen be passed to eLSA.
You can implement your own ones, and they need to implement methods fit, dw and predict.
"""
from sklearn.linear_model import LogisticRegression
from scipy.stats import logistic
import numpy as np
from sklearn.svm import SVC
class CustomClassifier(object):
def __init__(self, alpha=0.01):
self.alpha = alpha
def fit(self, X, Y, epoch=1000):
self.w = np.random.random(X.shape[1])*0.1 - 0.05
self.b = np.random.random()*0.1 - 0.05
for e in range(epoch):
self.update(X, Y)
def update(self, X, Y):
h = X.dot(self.w)
#h = h.sum(axis=1)
h += self.b
Yhat = logistic.cdf(h)
dif = Yhat-Y
sigma = dif * Yhat * (1-Yhat)
dw = (X.T.dot(sigma.reshape(-1,1))).T.sum(axis=0)
db = sigma.sum()
self.b -= db
self.w -= dw
def dX(self, X, Y):
h = (X*self.w).sum(axis=1) + self.b
Yhat = logistic.cdf(h)
dif = Yhat-Y
sigma = dif * Yhat * (1-Yhat)
dx = (sigma.reshape(-1,1)* self.w)
def predict(self, X):
h = X.dot(self.w) + self.b
Yhat = logistic.cdf(h)
return (Yhat>0.5)+0
class SkClassifier(object):
def __init__(self, params=None):
if params is None:
params = {}
self.raw_cls = LogisticRegression(**params)
def fit(self, X, Y, epoch=1000):
self.raw_cls.fit(X, Y)
def dx(self, X, Y):
b = self.raw_cls.intercept_[0]
theta = self.raw_cls.coef_[0]
h = (X*theta).sum(axis=1) + b
Yhat = logistic.cdf(h)
dif = Yhat-Y
sigma = dif * Yhat * (1-Yhat)
dx = (sigma.reshape(-1,1)* theta)
return dx
def predict(self, X):
return self.raw_cls.predict(X)
class SVCClassifier(object):
def __init__(self, params=None):
if params is None:
params = {}
self.raw_cls = SVC(**params)
def fit(self, X, Y, epoch=1000):
self.raw_cls.fit(X, Y)
def dx(self, X, Y):
raise "Not implemented"
def predict(self, X):
return self.raw_cls.predict(X)
class MostClassifier(object):
def __init__(self, params=None):
self.most = None
def fit(self, X, Y):
self.most = round(np.mean(Y))
def predict(self, X):
return self.most