Advertisement
Guest User

Untitled

a guest
Jan 27th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.12 KB | None | 0 0
  1. import numpy as np
  2. import random
  3. import matplotlib.pyplot as plt
  4. def generateDataset():
  5.  
  6. np.random.seed(120)
  7. n=100
  8. #Generate 100 points per class
  9. classA = np.random.randn(n, 2) * 0.5 + [0, 0]
  10.  
  11. classB = np.random.randn(n, 2) * 0.5 + [-2.0, -3.1]
  12.  
  13. # concatenate class
  14. inputs = np.concatenate(
  15. ( classA , classB )
  16. )
  17.  
  18. #Generate targets (-1 for class A, 1 for class B)
  19. targets = np.concatenate (
  20. (np.ones(classA.shape[0]), -np.ones(classB.shape[0])))
  21.  
  22. # shuffle dataset
  23. N = inputs.shape[0]
  24. permute=list(range(N))
  25. random.shuffle(permute)
  26. inputs = inputs [permute, : ]
  27. targets = targets [permute ]
  28.  
  29. ones=np.ones(np.shape(inputs)[0])
  30.  
  31. inputs=inputs.T
  32. # inputs = np.vstack((ones, inputs))
  33.  
  34. return np.matrix(inputs), np.matrix(targets.T)
  35.  
  36. def generateNonLinearDataset():
  37.  
  38. np.random.seed(120)
  39. n=100
  40. #Generate 100 points per class
  41. classA = np. concatenate (
  42. (
  43. np.random.randn(int(n/2), 2) * 0.2 + [2.5, 1.8],
  44. np.random.randn(int(n/2), 2) * 0.2 + [-2.5, -1.8])
  45. )
  46.  
  47. classB = np. concatenate (
  48. (
  49. np.random.randn(n, 2) * 0.3 + [0, -0.1],
  50. )
  51. )
  52. # concatenate class
  53. inputs = np.concatenate(
  54. ( classA , classB )
  55. )
  56.  
  57. #Generate targets (-1 for class A, 1 for class B)
  58. targets = np.concatenate (
  59. (np.ones(classA.shape[0]), -np.ones(classB.shape[0])))
  60.  
  61. # shuffle dataset
  62. N = inputs.shape[0]
  63. permute=list(range(N))
  64. random.shuffle(permute)
  65. inputs = inputs [permute, : ]
  66. targets = targets [permute ]
  67.  
  68. ones=np.ones(np.shape(inputs)[0])
  69.  
  70. inputs=inputs.T
  71. #binputs = np.vstack((ones, inputs))
  72.  
  73. return np.matrix(inputs), np.matrix(targets.T)
  74.  
  75. def generateDatasetSQW(n, datatype, add_ones = False):
  76. if datatype == '2D':
  77. """add_ones is False by default"""
  78. np.random.seed(120)
  79. random.seed(123)
  80.  
  81. #Generate n points per class
  82. classA = np.random.randn(n, 2) * 0.5 + [4.0, 4.5]
  83.  
  84. classB = np.random.randn(n, 2) * 0.5 + [-3.0, -3]
  85.  
  86. # concatenate class
  87. inputs = np.concatenate(
  88. ( classA , classB )
  89. )
  90.  
  91. # Generate targets (-1 for class A, 1 for class B)
  92. targets = np.concatenate (
  93. (np.ones(classA.shape[0]), -np.ones(classB.shape[0])))
  94.  
  95. # shuffle dataset
  96. N = inputs.shape[0]
  97. permute = list(range(N))
  98. random.shuffle(permute)
  99. inputs = inputs [permute, : ]
  100. targets = targets [permute ]
  101.  
  102.  
  103. if add_ones:
  104. # print(inputs)
  105. # print(np.matrix(inputs.T), inputs.T.shape)
  106. ones=np.ones(np.shape(inputs)[0])
  107. print(inputs)
  108. inputs = inputs.T
  109. inputs = np.vstack((ones, inputs))
  110. else:
  111. inputs=inputs.T
  112.  
  113. return np.matrix(inputs), np.matrix(targets.T)
  114.  
  115. if datatype == 'encoder':
  116. np.random.seed(100)
  117. random.seed(123)
  118.  
  119. inputs = - np.ones(n)
  120. idx_active = random.randrange(len(inputs))
  121. inputs[idx_active] = 1
  122. targets = np.copy(inputs)
  123. # np.random.shuffle(targets)
  124. # inputs = inputs.T
  125.  
  126. return np.matrix(inputs.T) , np.matrix(targets.T)
  127.  
  128. if datatype == 'gaussian':
  129. # x = np.arange(-5, 5.1, 0.5)
  130. x = np.linspace(-5 ,5 , n)
  131.  
  132. # y = np.arange(-5, 5.1, 0.5)
  133. y = np.linspace(-5 ,5 , n)
  134.  
  135. ndata = len(x)
  136. z = (np.exp(np.multiply(-x, x*0.1)) * np.exp(np.multiply(-y, y*0.1).T)) - 0.5
  137. fig = plt.figure()
  138. ax = fig.add_subplot(111, projection='3d')
  139. ax.plot(x, y, z)
  140. plt.show()
  141.  
  142.  
  143. targets = np.reshape(z, (1, ndata))
  144. xx, yy = np.meshgrid (x, y)
  145. patterns = np.vstack((np.reshape(xx, (1, ndata*ndata)), np.reshape(yy, (1, ndata*ndata))))
  146. return patterns, targets
  147.  
  148. def get_weights(n_nodes):
  149. """n_nodes: numpy array with values"""
  150. weights = []
  151. for layer in range(len(n_nodes) - 1):
  152. if layer != (len(n_nodes) - 1):
  153. weights.append(np.matrix(np.random.randn(n_nodes[layer + 1], n_nodes[layer] + 1)*np.sqrt(1/n_nodes[layer])))
  154. else:
  155. weights.append(np.matrix(np.random.randn(n_nodes[layer + 1], n_nodes[layer])*np.sqrt(1/n_nodes[layer])))
  156. return weights
  157.  
  158. def forward_pass(X, Ws, bias = False):
  159. if not bias:
  160.  
  161. ones = np.ones(np.shape(X)[1])
  162. H_star = np.dot(Ws[0], (np.vstack((X, ones))))
  163.  
  164. ones = np.ones(np.shape(H_star)[1])
  165. H = np.vstack((np.divide(2, (1 + np.exp(-H_star)) )-1, ones))
  166.  
  167. O_star = np.dot(Ws[1], H)
  168. O = np.divide(2, (1 + np.exp(-O_star))) - 1
  169. return O,O_star, H
  170. else:
  171. H_star = np.dot(Ws[0], X)
  172. H = np.vstack(np.divide(2, (1 + np.exp(-H_star)) )- 1, np.ones(np.shape(H_star)[0]))
  173. O_star = Ws[1] * H
  174. O = np.divide(2, (1 + np.exp( - O_star)))- 1
  175. pass
  176.  
  177. def backward_pass(O, H, T, weight):
  178. delta_o = np.multiply((O - T) , np.multiply((1 + O) , (1 - O))) * 0.5
  179. delta_h = np.multiply((weight.T @ delta_o) , np.multiply((1 + H) , (1 - H)))* 0.5
  180. delta_h = delta_h[:-1]
  181. #print(delta_h)
  182. return delta_h , delta_o
  183.  
  184. def weight_update(X, H, delta_h, delta_o, dw, dv, weights, eta, alpha):
  185. ones = np.ones(np.shape(X)[1])
  186. dw = np.multiply(dw , alpha) - np.multiply((delta_h * (np.vstack((X, ones))).T) , (1-alpha))
  187. dv = np.multiply(dv , alpha) - np.multiply((delta_o * H.T) , (1-alpha))
  188. weights[0] = weights[0] + np.multiply(dw , eta)
  189. weights[1] = weights[1] + np.multiply(dv , eta)
  190. return weights, dw, dv
  191.  
  192. def model(X, T, weights, n_nodes, epochs, eta, alpha, linear = True):
  193. for i in range(epochs):
  194. O,O_star, H = forward_pass(X, weights )
  195. dh, do, = backward_pass(O, H, T, weights[1])
  196. if i == 0:
  197. dw = 0
  198. dv = 0
  199. weights, dw, dv = weight_update(X, H, dh, do, dw, dv, weights, eta, alpha)
  200. return O_star
  201.  
  202.  
  203. def partition(X, fraction):
  204. breakPoint = int(len(X) * fraction)
  205. return X[:breakPoint], X[breakPoint:]
  206.  
  207.  
  208. def filterDataset1(inputs,targets,ratio=0.75):
  209. N = inputs.shape[1]
  210. idx=random.sample(list(range(N)),int(N*ratio))
  211. x_train = inputs [ :, idx]
  212. y_train = targets [:,idx ]
  213. x_test = inputs.delete(idx)
  214. y_test = inputs.delete(idx)
  215. return x_train,y_train, x_test, y_test
  216.  
  217. def filterDataset2(inputs,targets,ratio=0.50,filter=1):
  218. N = inputs.shape[1]
  219. #print(np.array(targets[0,:])[0])
  220. #print(list(np.where(np.array(targets[0,:])[0]==filter)[0]))
  221. idx=random.sample(list((np.where(np.array(targets[0,:])[0]==filter)[0])),int((N/2)*ratio)) #index to be removed
  222. #random.shuffle(permute)
  223. #print(idx)
  224. x_train = inputs [ :, idx]
  225. y_train = targets [:,idx ]
  226. x_test = inputs.delete(idx)
  227. y_test = inputs.delete(idx)
  228. return x_train,y_train, x_test, y_test
  229.  
  230. def filterDataset3(inputs,targets,ratio=0.50,filter=1):
  231. N = inputs.shape[1]
  232. #print(np.array(targets[0,:])[0])
  233. #print(list(np.where(np.array(targets[0,:])[0]==filter)[0]))
  234. color=list(np.where(np.array(targets[0,:])[0]==filter)[0])
  235.  
  236. #print(np.array(inputs[1,color])[0])
  237. #print(list((np.where(np.array(inputs[1,color])[0]<0)[0])))
  238. sub_set=list((np.where(np.array(inputs[1,color])[0]<0)[0]))
  239. idx1=random.sample(sub_set,int(len(sub_set)*0.2)) #index to be removed
  240.  
  241. color=list(np.where(np.array(targets[0,:])[0]==filter)[0])
  242. sub_set=list((np.where(np.array(inputs[1,color])[0]>0)[0]))
  243. idx2=random.sample(sub_set,int(len(sub_set)*0.8))
  244. #print(idx)
  245.  
  246. idx=np.concatenate((idx1,idx2))
  247.  
  248. x_test = inputs [ :, idx]
  249. y_test = targets [:,idx ]
  250. x_train = inputs.delete(idx)
  251. y_train = inputs.delete(idx)
  252. return inputs,targets
  253. # TO BE ADDED IN 'model' FOR SIZEING THE NN
  254. layers = 2
  255.  
  256. # function = get_function(x)
  257. #patterns, targets = generateDatasetSQW(100,"2D")
  258. patterns,targets=generateNonLinearDataset()
  259. #X_train,Y_train,X_test,Y_test = filterDataset1(patterns,targets)
  260. #X_train,X_test = partition(patterns,0.75)
  261. #Y_train,Y_test = partition(targets,0.75)
  262.  
  263.  
  264. eta = 0.001
  265. epochs_list = range(50,800,50)
  266. alpha = 0.9
  267. plt.figure()
  268. plt.title("Missclassified points after x epochs")
  269. for i in range(1,11):
  270. acc_list=[]
  271. for epochs in epochs_list:
  272. nodes = [patterns.shape[0], i, targets.shape[0]]
  273. weights = get_weights(nodes)
  274.  
  275. output=model(patterns, targets, weights, nodes,epochs, eta, alpha, linear = False)
  276. output=np.array(output)[0]
  277. accuracy=np.sum(np.where(np.sign(output)==np.array(targets)[0],1,0))
  278. acc_list.append(200-accuracy)
  279. plt.plot(epochs_list,acc_list,label="N.Hidden nodes="+str(i))
  280.  
  281. #plt.yscale('log')
  282. plt.xlabel("Epochs")
  283. plt.ylabel("Missclassified points")
  284. #plt.xlim((-0.2, 1))
  285. #plt.ylim((0,2))
  286. #plt.xticks(np.arange(0, iterations+1, 1))
  287. plt.legend()
  288. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement