Advertisement
fevzi02

Untitled

Dec 25th, 2023
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. import numpy as np
  2.  
  3. class NeuralNetwork:
  4. def __init__(self, input_size, hidden_size, output_size):
  5. self.input_size = input_size
  6. self.hidden_size = hidden_size
  7. self.output_size = output_size
  8.  
  9. # Инициализация весов
  10. self.weights_input_hidden = np.random.rand(input_size, hidden_size)
  11. self.weights_hidden_output = np.random.rand(hidden_size, output_size)
  12.  
  13. def sigmoid(self, x):
  14. return 1 / (1 + np.exp(-x))
  15.  
  16. def sigmoid_derivative(self, x):
  17. return x * (1 - x)
  18.  
  19. def train(self, X, y, learning_rate, epochs):
  20. for epoch in range(epochs):
  21. # Прямое распространение
  22. hidden_layer_input = np.dot(X, self.weights_input_hidden)
  23. hidden_layer_output = self.sigmoid(hidden_layer_input)
  24. output_layer_input = np.dot(hidden_layer_output, self.weights_hidden_output)
  25. output_layer_output = self.sigmoid(output_layer_input)
  26.  
  27. # Вычисление ошибки
  28. error = y - output_layer_output
  29.  
  30. # Обратное распространение
  31. d_output = error * self.sigmoid_derivative(output_layer_output)
  32. error_hidden = d_output.dot(self.weights_hidden_output.T)
  33. d_hidden = error_hidden * self.sigmoid_derivative(hidden_layer_output)
  34.  
  35. # Обновление весов
  36. self.weights_hidden_output += hidden_layer_output.T.dot(d_output) * learning_rate
  37. self.weights_input_hidden += X.T.dot(d_hidden) * learning_rate
  38.  
  39. def predict(self, X):
  40. hidden_layer_input = np.dot(X, self.weights_input_hidden)
  41. hidden_layer_output = self.sigmoid(hidden_layer_input)
  42. output_layer_input = np.dot(hidden_layer_output, self.weights_hidden_output)
  43. output_layer_output = self.sigmoid(output_layer_input)
  44. return output_layer_output
  45.  
  46. # Загрузка данных из iris.json и подготовка их для обучения
  47. import json
  48.  
  49. with open('iris.json', 'r') as f:
  50. data = json.load(f)
  51.  
  52. X = np.array([item[:2] for item in data])
  53. y = np.array([item[2] for item in data])
  54.  
  55. # Создание и обучение нейронной сети
  56. input_size = 2
  57. hidden_size = 4
  58. output_size = 1
  59.  
  60. nn = NeuralNetwork(input_size, hidden_size, output_size)
  61. nn.train(X, y, learning_rate=0.1, epochs=1000)
  62.  
  63. # Теперь вы можете использовать nn.predict() для предсказания класса для новых данных и построения карты классификации.
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement