Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.35 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. np.random.seed(100)
  5.  
  6.  
  7. class Layer:
  8.     """
  9.    Represents a layer (hidden or output) in our neural network.
  10.    """
  11.  
  12.     def __init__(self, n_input, n_neurons, activation=None, weights=None, bias=None):
  13.         """
  14.        :param int n_input: The input size (coming from the input layer or a previous hidden layer)
  15.        :param int n_neurons: The number of neurons in this layer.
  16.        :param str activation: The activation function to use (if any).
  17.        :param weights: The layer's weights.
  18.        :param bias: The layer's bias.
  19.        """
  20.  
  21.         self.weights = weights if weights is not None else np.random.rand(n_input, n_neurons)
  22.         self.activation = activation
  23.         self.bias = bias if bias is not None else np.zeros(n_neurons)
  24.         self.last_activation = None
  25.         self.error = None
  26.         self.delta = None
  27.  
  28.     def activate(self, x):
  29.         """
  30.        Calculates the dot product of this layer.
  31.        :param x: The input.
  32.        :return: The result.
  33.        """
  34.  
  35.         r = np.dot(x, self.weights) + self.bias
  36.         self.last_activation = self._apply_activation(r)
  37.         return self.last_activation
  38.  
  39.     def _apply_activation(self, r):
  40.         """
  41.        Applies the chosen activation function (if any).
  42.        :param r: The normal value.
  43.        :return: The "activated" value.
  44.        """
  45.  
  46.         # In case no activation function was chosen
  47.         if self.activation is None:
  48.             return r
  49.  
  50.         # tanh
  51.         if self.activation == 'tanh':
  52.             return np.tanh(r)
  53.  
  54.         # sigmoid
  55.         if self.activation == 'sigmoid':
  56.             return 1 / (1 + np.exp(-r))
  57.  
  58.         return r
  59.  
  60.     def apply_activation_derivative(self, r):
  61.         """
  62.        Applies the derivative of the activation function (if any).
  63.        :param r: The normal value.
  64.        :return: The "derived" value.
  65.        """
  66.  
  67.         # We use 'r' directly here because its already activated, the only values that
  68.         # are used in this function are the last activations that were saved.
  69.  
  70.         if self.activation is None:
  71.             return r
  72.  
  73.         if self.activation == 'tanh':
  74.             return 1 - r ** 2
  75.  
  76.         if self.activation == 'sigmoid':
  77.             return r * (1 - r)
  78.  
  79.         return r
  80.  
  81.  
  82. class NeuralNetwork:
  83.     """
  84.    Represents a neural network.
  85.    """
  86.  
  87.     def __init__(self):
  88.         self._layers = []
  89.  
  90.     def add_layer(self, layer):
  91.         """
  92.        Adds a layer to the neural network.
  93.        :param Layer layer: The layer to add.
  94.        """
  95.  
  96.         self._layers.append(layer)
  97.  
  98.     def feed_forward(self, X):
  99.         """
  100.        Feed forward the input through the layers.
  101.        :param X: The input values.
  102.        :return: The result.
  103.        """
  104.  
  105.         for layer in self._layers:
  106.             X = layer.activate(X)
  107.  
  108.         return X
  109.  
  110.     def predict(self, X):
  111.         """
  112.        Predicts a class (or classes).
  113.        :param X: The input values.
  114.        :return: The predictions.
  115.        """
  116.  
  117.         ff = self.feed_forward(X)
  118.  
  119.         # One row
  120.         if ff.ndim == 1:
  121.             return np.argmax(ff)
  122.  
  123.         # Multiple rows
  124.         return np.argmax(ff, axis=1)
  125.  
  126.     def backpropagation(self, X, y, learning_rate):
  127.         """
  128.        Performs the backward propagation algorithm and updates the layers weights.
  129.        :param X: The input values.
  130.        :param y: The target values.
  131.        :param float learning_rate: The learning rate (between 0 and 1).
  132.        """
  133.  
  134.         # Feed forward for the output
  135.         output = self.feed_forward(X)
  136.  
  137.         # Loop over the layers backward
  138.         for i in reversed(range(len(self._layers))):
  139.             layer = self._layers[i]
  140.  
  141.             # If this is the output layer
  142.             if layer == self._layers[-1]:
  143.                 layer.error = y - output
  144.                 # The output = layer.last_activation in this case
  145.                 layer.delta = layer.error * layer.apply_activation_derivative(output)
  146.             else:
  147.                 next_layer = self._layers[i + 1]
  148.                 layer.error = np.dot(next_layer.weights, next_layer.delta)
  149.                 layer.delta = layer.error * layer.apply_activation_derivative(layer.last_activation)
  150.  
  151.         # Update the weights
  152.         for i in range(len(self._layers)):
  153.             layer = self._layers[i]
  154.             # The input is either the previous layers output or X itself (for the first hidden layer)
  155.             input_to_use = np.atleast_2d(X if i == 0 else self._layers[i - 1].last_activation)
  156.             layer.weights += layer.delta * input_to_use.T * learning_rate
  157.  
  158.     def train(self, X, y, learning_rate, max_epochs):
  159.         """
  160.        Trains the neural network using backpropagation.
  161.        :param X: The input values.
  162.        :param y: The target values.
  163.        :param float learning_rate: The learning rate (between 0 and 1).
  164.        :param int max_epochs: The maximum number of epochs (cycles).
  165.        :return: The list of calculated MSE errors.
  166.        """
  167.  
  168.         mses = []
  169.  
  170.         for i in range(max_epochs):
  171.             for j in range(len(X)):
  172.                 self.backpropagation(X[j], y[j], learning_rate)
  173.             if i % 10 == 0:
  174.                 mse = np.mean(np.square(y - nn.feed_forward(X)))
  175.                 mses.append(mse)
  176.                 print('Epoch: #%s, MSE: %f' % (i, float(mse)))
  177.  
  178.         return mses
  179.  
  180.     @staticmethod
  181.     def accuracy(y_pred, y_true):
  182.         """
  183.        Calculates the accuracy between the predicted labels and true labels.
  184.        :param y_pred: The predicted labels.
  185.        :param y_true: The true labels.
  186.        :return: The calculated accuracy.
  187.        """
  188.  
  189.         return (y_pred == y_true).mean()
  190.  
  191.  
  192.  
  193. nn = NeuralNetwork()
  194. nn.add_layer(Layer(2, 30, 'sigmoid'))
  195. nn.add_layer(Layer(30, 30, 'sigmoid'))
  196. nn.add_layer(Layer(30, 30, 'sigmoid'))
  197. nn.add_layer(Layer(30, 3, 'sigmoid'))
  198. nn.add_layer(Layer(3, 1, 'sigmoid'))
  199.  
  200. # Define dataset
  201. X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
  202. y = np.array([[0], [1], [1], [0]])
  203.  
  204. # Train the neural network
  205. errors = nn.train(X, y, 0.03, 290)
  206. print('Accuracy: %.2f%%' % (nn.accuracy(nn.predict(X), y.flatten()) * 100))
  207.  
  208. # Plot changes in mse
  209. plt.plot(errors)
  210. plt.title('Changes in MSE')
  211. plt.xlabel('Epoch (every 10th)')
  212. plt.ylabel('MSE')
  213. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement