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.
import numpy as np import matplotlib.pyplot as plt import neurolab as nl
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:]
# Plot input data plt.figure() plt.scatter(data[:,0], data[:,1]) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Input data')
# 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()
# 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)
# Train the neural network error = single_layer_net.train(data, labels, epochs=50, show=20, lr=0.01)
# 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()
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]])
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:The second figure displays the training error progress:
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.
18.188.44.223