Advertisement
mfgnik

Untitled

Apr 4th, 2020
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.42 KB | None | 0 0
  1. def compute_w_diff(x, y, w, b,  C=0.0):
  2.     prod_xy = np.array(y).reshape((y.size, 1)) * x
  3.     exp = np.exp(-prod_xy.dot(w) + b)
  4.     big_sum = np.sum(prod_xy * (1 - 1/(1 + exp)), axis=0)
  5.     return big_sum.reshape(w.shape)/y.size -  C * w
  6.  
  7. def compute_b_diff(x, y, w, b):
  8.     prod_xy = np.array(y).reshape((y.size, 1)) * x
  9.     return np.sum(np.array(y).reshape((y.size, 1)) * (1 - 1/(1 + np.exp(-prod_xy.dot(w) + b))))/y.size
  10.  
  11. class LinearClassifier(BaseEstimator, LinearClassifierMixin):
  12.     def __init__(self, step, stop_function=lambda iters, dif : iters < 10000, rand_init=False, C=0.0):
  13.         self.step = step
  14.         self.stop_function = stop_function
  15.         self.rand_init = rand_init
  16.         self.C = C
  17.    
  18.     def fit(self, X, y):
  19.         if self.rand_init:
  20.             w = (np.random.rand(x.shape[1]).reshape((x.shape[1], 1)) - 0.5) / x.shape[0]
  21.         else:
  22.             w = np.zeros((x.shape[1], 1))
  23.         b = 0
  24.         current_iters = 0
  25.         while True:
  26.             w_dif = self.step * compute_w_diff(X, y, w, b, self.C)
  27.             b_dif = self.step * compute_b_diff(X, y, w, b)
  28.             w += w_dif
  29.             b += b_dif
  30.             if self.stop_function(current_iters, w_dif):
  31.                 self.coef_ = w
  32.                 self.intercept_ = b
  33.                 return self
  34.             current_iters += 1
  35.    
  36.     def predict_proba(self, X):
  37.         return super()._predict_proba_lr(X)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement