Advertisement
cyphric

Untitled

Feb 21st, 2022
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import numpy as np
  2. import random, math
  3. from scipy.optimize import minimize
  4. import matplotlib.pyplot as plt
  5.  
  6. class Kernel:
  7. def __init__(self, ker, ps):
  8. self.ker = ker
  9. self.ps = ps
  10. return
  11.  
  12. def __getitem__(self, input):
  13. if self.ker == 'linear': return np.dot(input[0],input[1])
  14. if self.ker == 'poly': return (np.dot(input[0],input[1])+1)**self.ps
  15. if self.ker == 'rbf': return math.exp(-(np.dot(np.subtract(input[0],input[1]) , np.subtract(input[0],input[1]))) / (2*self.ps)**2)
  16.  
  17.  
  18. #---------------------------------------------------------------------------------
  19.  
  20. class Objective:
  21. def __init__(self, x, t, a, N, C=None, ker='linear', kerPs = 2):
  22. self.kernel = Kernel(ker, kerPs)
  23. p = np.zeros((N, N))
  24. for i in range(N):
  25. for j in range(N):
  26. p[i,j] = t[i]*t[j]*self.kernel[[x[i],x[j]]]
  27.  
  28. self.p = p
  29. self.x = x
  30. self.t = t
  31. self.alpha = a
  32. self.N = N
  33. self.bounds = [(0, C) for i in range(self.N)]
  34.  
  35.  
  36. def obj1(self, a):
  37. val = np.dot(a, np.dot(a, self.p))/2 - sum(a)
  38. return val
  39.  
  40. def zerofun(self, a):
  41. return np.dot(a,self.t)
  42.  
  43. def indicator(self, s1, s2):
  44. s = [s1, s2]
  45. k = [self.kernel[[s, xi]] for xi in self.x]
  46. return np.dot(np.multiply(self.alpha, self.t), k) - self.b
  47.  
  48. #---------------------------------------------------------------------------------
  49.  
  50. classA = np.random.randn(20, 2) + [0.0, 0.0]
  51. classB = np.random.randn(20, 2) + [0.0, 0.0]
  52.  
  53.  
  54. inputs = np.concatenate((classA, classB))
  55. targets = np.concatenate(
  56. (np.ones(classA.shape[0]),
  57. -np.ones(classB.shape[0])))
  58.  
  59. N = inputs.shape[0]
  60.  
  61. permute = list(range(N))
  62. random.shuffle(permute)
  63. inputs = inputs[permute, :]
  64. targets = targets[permute]
  65.  
  66.  
  67. O = Objective(inputs, targets, np.zeros(N), N, ker='rbf', kerPs = 2)
  68.  
  69. ret = minimize(O.obj1, O.alpha, bounds = O.bounds, constraints={'type':'eq', 'fun':O.zerofun})
  70. alpha = ret['x']
  71.  
  72. res = np.array([[alpha[i], O.x[i], O.t[i]] for i in range(len(alpha)) if alpha[i] > 1e-5])
  73. #print(res[:,0])
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement