Building a single layer neural network

Now that we know how to create a perceptron, let's create a single layer neural network. A single layer neural network consists of multiple neurons in a single layer. Overall, we will have an input layer, a hidden layer, and an output layer.

How to do it…

  1. Create a new Python file, and import the following packages:
    import numpy as np
    import matplotlib.pyplot as plt
    import neurolab as nl 
  2. We will use the data in the data_single_layer.txt file. Let's load this:
    # Define input data
    input_file = 'data_single_layer.txt'
    input_text = np.loadtxt(input_file)
    data = input_text[:, 0:2]
    labels = input_text[:, 2:]
  3. Let's plot the input data:
    # Plot input data
    plt.figure()
    plt.scatter(data[:,0], data[:,1])
    plt.xlabel('X-axis')
    plt.ylabel('Y-axis')
    plt.title('Input data')
  4. Let's extract the minimum and maximum values:
    # Min and max values for each dimension
    x_min, x_max = data[:,0].min(), data[:,0].max()
    y_min, y_max = data[:,1].min(), data[:,1].max()
  5. Let's define a single layer neural network with two neurons in the hidden layer:
    # Define a single-layer neural network with 2 neurons;
    # Each element in the list (first argument) specifies the 
    # min and max values of the inputs
    single_layer_net = nl.net.newp([[x_min, x_max], [y_min, y_max]], 2)
  6. Train the neural network until 50 epochs:
    # Train the neural network
    error = single_layer_net.train(data, labels, epochs=50, show=20, lr=0.01)
  7. Plot the results, as follows:
    # Plot results
    plt.figure()
    plt.plot(error)
    plt.xlabel('Number of epochs')
    plt.ylabel('Training error')
    plt.title('Training error progress')
    plt.grid()
    
    plt.show()
  8. Let's test the neural network on new test data:
    print single_layer_net.sim([[0.3, 4.5]])
    print single_layer_net.sim([[4.5, 0.5]])
    print single_layer_net.sim([[4.3, 8]])
  9. The full code is in the single_layer.py file that's already provided to you. If you run this code, you will see two figures. The first figure displays the input data:
    How to do it…

    The second figure displays the training error progress:

    How to do it…

    You will see the following printed on your Terminal, indicating where the input test points belong:

    [[ 0.  0.]]
    [[ 1.  0.]]
    [[ 1.  1.]]
    

    You can verify that the outputs are correct based on our labels.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.44.223