Advertisement
mirosh111000

Двошарова нейронна мережа прямого поширення(pr4)v1

Sep 8th, 2024 (edited)
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.55 KB | None | 0 0
  1. import numpy as np
  2. import pandas as pd
  3. import seaborn as sns
  4. import matplotlib.pyplot as plt
  5. from sklearn.metrics import mean_squared_error
  6.  
  7. def f(x):
  8.     return np.sin(x)
  9.  
  10.  
  11. class MultiNeuralNetwork:
  12.     def __init__(self, learning_rate=0.01, epochs=100000, hidden_layers=[10], epsilon=0.001, C=1):
  13.         self.learning_rate = learning_rate
  14.         self.epochs = epochs
  15.         self.hidden_layers = hidden_layers
  16.         self.epsilon = epsilon
  17.         self.C = 1
  18.         self.weights = []
  19.         self.biases = []
  20.         self.mse_err = []
  21.         self.train_epochs = []
  22.  
  23.     def sigmoid(self, z):
  24.         return 1 / (1 + np.exp(-z))
  25.  
  26.     def sigmoid_derivative(self, z):
  27.         s = self.sigmoid(z)
  28.         return s * (1 - s)
  29.  
  30.     def linear(self, z, C=1):
  31.         return z * C
  32.  
  33.     def mean_squared_error(self, y_true, y_pred):
  34.         return np.mean((y_true - y_pred) ** 2)
  35.  
  36.     def initialize_parameters(self, input_size, output_size):
  37.         layers = [input_size] + self.hidden_layers + [output_size]
  38.         self.weights = [np.random.randn(layers[i], layers[i + 1]) for i in range(len(layers) - 1)]
  39.         self.biases = [np.random.randn(layers[i + 1]) for i in range(len(layers) - 1)]
  40.  
  41.     def forward_propagation(self, x):
  42.         activations = [x[:, np.newaxis]]
  43.         z_values = []
  44.        
  45.         for w, b in zip(self.weights, self.biases):
  46.             z = np.dot(activations[-1], w) + b
  47.             z_values.append(z)
  48.             if w.shape[1] == 1:
  49.                 a = self.linear(z, C=self.C)
  50.             else:
  51.                 a = self.sigmoid(z)
  52.             activations.append(a)
  53.         return activations, z_values
  54.  
  55.     def backward_propagation(self, activations, z_values, y):
  56.         d_weights = [None] * len(self.weights)
  57.         d_biases = [None] * len(self.biases)
  58.  
  59.         delta = 2 * (activations[-1] - y[:, np.newaxis]) / len(y)
  60.         d_weights[-1] = np.dot(activations[-2].T, delta)
  61.         d_biases[-1] = np.sum(delta, axis=0)
  62.  
  63.         for i in reversed(range(len(d_weights) - 1)):
  64.             delta = np.dot(delta, self.weights[i + 1].T) * self.sigmoid_derivative(z_values[i])
  65.             d_weights[i] = np.dot(activations[i].T, delta)
  66.             d_biases[i] = np.sum(delta, axis=0)
  67.        
  68.         return d_weights, d_biases
  69.  
  70.     def fit(self, x, y):
  71.         self.initialize_parameters(input_size=1, output_size=1)
  72.        
  73.         for epoch in range(self.epochs):
  74.             activations, z_values = self.forward_propagation(x)
  75.             y_pred = activations[-1].flatten()
  76.             error = self.mean_squared_error(y, y_pred)
  77.            
  78.             self.train_epochs.append(epoch+1)
  79.             self.mse_err.append(error)
  80.            
  81.             if error < self.epsilon:
  82.                 print(f"Навчання зупинено на епохі {epoch} з помилкою {error}")
  83.                 break
  84.            
  85.             d_weights, d_biases = self.backward_propagation(activations, z_values, y)
  86.            
  87.             for i in range(len(self.weights)):
  88.                 self.weights[i] -= self.learning_rate * d_weights[i]
  89.                 self.biases[i] -= self.learning_rate * d_biases[i]
  90.  
  91.     def predict(self, x):
  92.         activations, _ = self.forward_propagation(x)
  93.         return activations[-1].flatten()
  94.  
  95.  
  96.  
  97. N = 100  
  98. a, b = 0, 10  
  99.  
  100. x = np.linspace(a, b, N)
  101. y = f(x)
  102.  
  103. x_test = x + 0.05
  104. y_test = f(x_test)
  105.  
  106. df = pd.DataFrame(x, columns=['X'])
  107. df['target'] = y
  108. print(df)
  109.  
  110. sns.pairplot(df)
  111. plt.show()
  112.  
  113. model = MultiNeuralNetwork(hidden_layers=[10], learning_rate=0.01, epochs=1000000, epsilon=0.001)
  114. model.fit(x, y)
  115.  
  116.  
  117. plt.figure(figsize=(10, 5))
  118. plt.title('Залежність помилки від епохи навчання')
  119. plt.plot(model.train_epochs, model.mse_err, label=f'lr={model.learning_rate}, epsilon={model.epsilon}')
  120. plt.ylabel('MSE')
  121. plt.xlabel('Epoche')
  122. plt.grid()
  123. plt.legend()
  124. plt.show()
  125.  
  126.  
  127. y_pred = model.predict(x)
  128.  
  129. plt.figure(figsize=(10, 5))
  130. plt.title('Тренувальні дані')
  131. plt.scatter(x, y, label='Реальні дані')
  132. plt.plot(x, y_pred, label='Передбачення нейронної мережі', color='red')
  133. plt.grid()
  134. plt.legend()
  135. plt.show()
  136.  
  137. y_pred_test = model.predict(x)
  138.  
  139. plt.figure(figsize=(10, 5))
  140. plt.title('Тестові дані (x_test = x_train + 0.05)')
  141. plt.scatter(x_test, y_test, label='Тестові дані')
  142. plt.plot(x_test, y_pred_test, label=f'Передбачення (MSE={round(mean_squared_error(y_test, y_pred_train), 4)})', color='red')
  143. plt.grid()
  144. plt.legend()
  145. plt.show()
  146.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement