Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.13 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import numpy as np
  3. import matplotlib.cm as cm
  4. import matplotlib.mlab as mlab
  5. import matplotlib.pyplot as plt
  6. import matplotlib.animation as animation
  7.  
  8.  
  9. ###############################################################################
  10. class RBFNN:
  11. def __init__(self, inputs_num, hidden_num, output_num):#hidden_num=number of radial neurons in the hidden layer
  12. self.inputs_num = inputs_num
  13. self.hidden_num = hidden_num
  14. self.output_num = output_num
  15. self.hcenters = np.zeros((hidden_num, inputs_num)) #centres of radial functions in the hidden layer
  16. self.hsigmas = np.ones(hidden_num)#sigma values of radial functions in the hidden layer
  17. self.outweights = np.random.rand(hidden_num, output_num) #each output neuron as a column
  18. self.outbiases = np.random.rand(output_num)#biases of the output linear neurons
  19. self.houtputs = None #outputs of radial neurons (hidden layer)
  20. self.netoutputs = None #output of the network (linear neurons)
  21. self.stats = None #statistics about the MSE during batch training
  22. def Print(self):#print basic info about the network
  23. print('hcenters:\n',self.hcenters)
  24. print('hsigmas:\n',self.hsigmas)
  25. print('outweights:\n', self.outweights)
  26. print('outbiases:\n',self.outbiases)
  27. if self.houtputs is not None:
  28. print('houtputs:\n',self.houtputs)
  29. if self.netoutputs is not None:
  30. print('netoutputs:\n',self.netoutputs)
  31. def Forward(self, inputs):
  32. ##outputs of radial neurons (hidden layer)
  33. self.houtputs = np.empty((inputs.shape[0], self.hcenters.shape[0]), dtype = float)
  34. for i in range(inputs.shape[0]): #for each training example
  35. self.houtputs[i,:] = np.exp(-np.sum((self.hcenters - inputs[i,:])**2, axis=1)/self.hsigmas**2)
  36. ##outputs of linear neurons (output layer)
  37. self.netoutputs = np.dot(self.houtputs, self.outweights) + self.outbiases
  38. def GetOutputs(self):#returns real valued outputs
  39. return self.netoutputs
  40. def GetPredictions(self):#returns class labels as 0,1,2,...
  41. return np.argmax(self.netoutputs, axis=1)
  42. def GetClassificationError(self, labels):
  43. return np.sum(labels!=self.GetPredictions())
  44. def GetMSE(self, d):
  45. self.mse = ((self.netoutputs - d)*(self.netoutputs - d)).sum(axis=1).sum() /d.shape[0]
  46. return self.mse
  47. def GetMaxRadialValue(self, X):#helper function for vizualization; for each example (row in X) returns the maximum value of any of the radial functions
  48. self.Forward(X)
  49. return self.houtputs.max(axis=1)
  50. def InitCenters(self, inputs, sigma):#randomly select a self.hidden_num number of training examples and copy their positions as centres of rbf neurons
  51. self.hsigmas = np.ones(self.hidden_num)*sigma
  52. indxs = set()
  53. while len(indxs) < self.hcenters.shape[0]:
  54. indxs.add(np.random.randint(0,inputs.shape[0]))
  55. self.hcenters = inputs[np.asarray(list(indxs)), :].copy()
  56. def TrainMPInv(self, X, d, sigma): #matrix pseudo inverse
  57. self.InitCenters(X, sigma)
  58. self.Forward(X)
  59. #now the matrix pseudoinverse for the weights of the output linear neurons
  60. r = np.hstack((np.ones((self.houtputs.shape[0], 1)), self.houtputs))
  61. w = np.dot(np.dot( np.linalg.inv( np.dot(r.T, r) ), r.T), d)
  62. self.w = w[1:,:]
  63. self.b = w[0,:]
  64. def TrainBatch(self, X, d, labels, sigma, eta, max_iters): #Widrow-Hoff model, delta rule
  65. self.InitCenters(X, sigma)
  66. self.Forward(X)
  67. self.stats = []
  68. for i in range(max_iters):
  69. self.outweights += eta*np.dot(self.houtputs.T, d - self.netoutputs)/X.shape[0]
  70. self.outbiases += eta*np.dot(np.ones((1,self.houtputs.shape[0])), d - self.netoutputs).flatten()/X.shape[0]
  71. self.Forward(X)
  72. mse = self.GetMSE(d)
  73. self.stats.append(mse)
  74. #print('mse=',mse)
  75. classification_error = self.GetClassificationError(labels)
  76. #print('classification_error=',classification_error)
  77. #print()
  78. ###############################################################################
  79. ###############################################################################
  80.  
  81. ##Data Encoding
  82.  
  83. def encode_labels(d):
  84. enc = np.unique(d,axis=0)
  85. #print("encoded",enc)
  86. for i in range(len(d)):
  87. for j in range(len(enc)):
  88. if d[i]==enc[j]:
  89. d[i]=j
  90. return d
  91.  
  92. def encode_labels_as_binary(d, num_of_classes):
  93. rows = d.shape[0]
  94. #print("this is dshape",d.shape[0])
  95. labels = -1*np.ones((rows, num_of_classes), dtype='float32')
  96. labels[np.arange(rows),encode_labels(d).T] = 1
  97. return labels
  98. ###############################################################################
  99. #Data Loading
  100. X = np.genfromtxt("iris.csv", delimiter='\t', dtype=str)
  101. #Splitting inputs from cls
  102. d = X[:,-1].astype('str')
  103. X = X[:,:-1].astype('float')
  104.  
  105. #Normalization####
  106. X = X/np.absolute(X.max(axis=0))
  107. #####
  108. num_of_cls = len(set(d))
  109. num_of_ins = X.shape[1]
  110.  
  111. print('num_of_cls=',num_of_cls)
  112. print('num_of_ins=',num_of_ins)
  113. d = encode_labels(d).astype('int')
  114. dtrain = encode_labels_as_binary(d, num_of_cls)
  115. #print('dtrain=',dtrain)
  116.  
  117. #experiment with the values of hidden_num and sigma, so that the training data is well covered by radial responses
  118. hidden_num = 11 #experiment with this value
  119. sigma = 0.4 #experiment with this value
  120.  
  121. net = RBFNN(num_of_ins, hidden_num, num_of_cls)
  122. net.Print()
  123. net.Forward(X)
  124. net.Print()
  125. print('MSE before training=',net.GetMSE(dtrain))
  126. print('Classification error before training=',net.GetClassificationError(d))
  127.  
  128. #net.TrainMPInv(X, d, sigma)
  129. net.TrainBatch(X, dtrain, d, sigma, 0.35, 1000)
  130.  
  131. net.Forward(X)
  132. net.Print()
  133. print('MSE after training=',net.GetMSE(dtrain))
  134. print('Classification error after training=',net.GetClassificationError(d))
  135. print('houts max=',net.houtputs.max(axis=1).min())
  136. print('out w max=',net.outweights.max())
  137. print('out w min=',net.outweights.min())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement