You can use the Python language to build neural networks, from simple to complex. For you to build a neural network, you first need to decide what you want it to learn. For this simple Python tutorial, put your eyes on a pretty simple goal: implement a three-input XOR gate. (That’s an eXclusive OR gate.) The table below shows the function you’re going to implement in table form.
X1 | X2 | X3 | Y1 |
0 | 0 | 0 | 1 |
0 | 0 | 1 | 0 |
0 | 1 | 0 | 0 |
0 | 1 | 1 | 0 |
1 | 0 | 0 | 0 |
1 | 0 | 1 | 0 |
1 | 1 | 0 | 0 |
1 | 1 | 1 | 1 |
An Exclusive Or function returns a 1 only if all the inputs are either 0 or 1.
The neural-net Python code
Here, you will be using the Python library called NumPy, which provides a great set of functions to help organize a neural network and also simplifies the calculations.
Our Python code using NumPy for the two-layer neural network follows. Using nano (or your favorite text editor), open up a file called “2LayerNeuralNetwork.py” and enter the following code:
# 2 Layer Neural Network in NumPy import numpy as np # X = input of our 3 input XOR gate # set up the inputs of the neural network (right from the table) X = np.array(([0,0,0],[0,0,1],[0,1,0], [0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]), dtype=float) # y = our output of our neural network y = np.array(([1], [0], [0], [0], [0], [0], [0], [1]), dtype=float) # what value we want to predict xPredicted = np.array(([0,0,1]), dtype=float) X = X/np.amax(X, axis=0) # maximum of X input array # maximum of xPredicted (our input data for the prediction) xPredicted = xPredicted/np.amax(xPredicted, axis=0) # set up our Loss file for graphing lossFile = open(“SumSquaredLossList.csv”, “w”) class Neural_Network (object): def __init__(self): #parameters self.inputLayerSize = 3 # X1,X2,X3 self.outputLayerSize = 1 # Y1 self.hiddenLayerSize = 4 # Size of the hidden layer # build weights of each layer # set to random values # look at…
Source