Advertisement
fevzi02

Untitled

Dec 18th, 2023
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. import numpy as np
  2.  
  3. class NeuralNetwork:
  4. def __init__(self, input_size, hidden_size, output_size):
  5. # Инициализация весов
  6. self.weights_input_to_hidden = np.random.rand(input_size, hidden_size)
  7. self.weights_hidden_to_output = np.random.rand(hidden_size, output_size)
  8.  
  9. def sigmoid(self, x):
  10. return 1 / (1 + np.exp(-x))
  11.  
  12. def sigmoid_derivative(self, x):
  13. return x * (1 - x)
  14.  
  15. def forward_pass(self, inputs):
  16. self.input = inputs
  17. self.hidden = self.sigmoid(np.dot(self.input, self.weights_input_to_hidden))
  18. self.output = self.sigmoid(np.dot(self.hidden, self.weights_hidden_to_output))
  19. return self.output
  20.  
  21. def backward_pass(self, inputs, expected_output, learning_rate):
  22. error = expected_output - self.output
  23. d_output = error * self.sigmoid_derivative(self.output)
  24.  
  25. error_hidden = d_output.dot(self.weights_hidden_to_output.T)
  26. d_hidden = error_hidden * self.sigmoid_derivative(self.hidden)
  27.  
  28. # Обновление весов
  29. self.weights_hidden_to_output += self.hidden.T.dot(d_output) * learning_rate
  30. self.weights_input_to_hidden += inputs.T.dot(d_hidden) * learning_rate
  31.  
  32. def train(self, training_inputs, training_outputs, learning_rate):
  33. output = self.forward_pass(training_inputs)
  34. self.backward_pass(training_inputs, training_outputs, learning_rate)
  35.  
  36. # Пример использования
  37. input_size = 3
  38. hidden_size = 4
  39. output_size = 1
  40. learning_rate = 0.1
  41. network = NeuralNetwork(input_size, hidden_size, output_size)
  42.  
  43. # Данные для обучения
  44. training_inputs = np.array([[0,0,1], [1,1,1], [1,0,1], [0,1,1]])
  45. training_outputs = np.array([[0,1,1,0]]).T
  46.  
  47. # Обучение
  48. for i in range(2000):
  49. network.train(training_inputs, training_outputs, learning_rate)
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement