Advertisement
Guest User

Untitled

a guest
Feb 14th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. class RBFNetwork():
  2. def __init__(self, input_dim, num_centers, output_dim):
  3. self.input_dim = input_dim
  4. self.output_dim = output_dim
  5. self.num_centers = num_centers
  6. self.centers = [np.random.uniform(-1, 1, input_dim) for i in range(num_centers)]
  7. self.beta = 1
  8. self.weights = None
  9.  
  10. # spocteni hodnot neuronu na skryte vrstve
  11. def calculate_activation(self, data):
  12. hidden_layer_values = np.zeros((data.shape[0], self.num_centers), float)
  13. for c_idx, c in enumerate(self.centers):
  14. for x_idx, x in enumerate(data):
  15. hidden_layer_values[x_idx,c_idx] = self.activation_fcn(c, x)
  16. return hidden_layer_values
  17.  
  18. # hodnota aktivacni fce
  19. def activation_fcn(self, centers, data):
  20. return np.exp(-self.beta * np.linalg.norm(centers-data)**2)
  21.  
  22. def fit(self, data, labels):
  23. # zvol nahodne hodnoty pocatecnich centroidu
  24. random_idx = np.random.permutation(data.shape[0])[:self.num_centers]
  25. self.centers = [data[i,:] for i in random_idx]
  26.  
  27. # spocitame aktivaci mezi vstupem a skrytou vrstvou
  28. hidden_layer_values = self.calculate_activation(data)
  29.  
  30. # porovname skutecne a predikovane vystupy a aktualizujem vahy
  31. # pseudoinverzni matice je vlastne vzorecek pro LR pro train vah
  32. self.weights = np.dot(np.linalg.pinv(hidden_layer_values), labels)
  33.  
  34. def predict(self, data):
  35. hidden_layer_values = self.calculate_activation(data)
  36. labels = np.dot(hidden_layer_values, self.weights)
  37. return labels
  38.  
  39.  
  40. # ziskame data
  41. iris = datasets.load_iris()
  42. x, y = iris.data, iris.target
  43. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
  44.  
  45. # delame klasifikaci prevedeme vystup do one hot encoding
  46. onehotencoder = OneHotEncoder(categorical_features = [0])
  47. y_train_onehot = onehotencoder.fit_transform(y_train.reshape(-1, 1)).toarray()
  48. y_test_onehot = onehotencoder.fit_transform(y_test.reshape(-1, 1)).toarray()
  49.  
  50. # natrenujeme a ohodnotime sit
  51. rbf = RBFNetwork(4, 10, 3)
  52. rbf.fit(x_train, y_train_onehot)
  53. predicted = rbf.predict(x_test)
  54. y_pred = np.argmax(predicted, axis=1)
  55. accuracy = np.mean(y_pred == y_test)
  56. print('Accuracy: ' + str(accuracy))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement