Training a Neural Network

In this example, we’ll be training a neural network using particle swarm optimization. For this we’ll be using the standard global-best PSO pyswarms.single.GBestPSO for optimizing the network’s weights and biases. This aims to demonstrate how the API is capable of handling custom-defined functions.

For this example, we’ll try to classify the three iris species in the Iris Dataset.

[1]:
# Import modules
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris


# Import PySwarms
import pyswarms as ps

# Some more magic so that the notebook will reload external python modules;
# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython
%load_ext autoreload
%autoreload 2

First, we’ll load the dataset from scikit-learn. The Iris Dataset contains 3 classes for each of the iris species (iris setosa, iris virginica, and iris versicolor). It has 50 samples per class with 150 samples in total, making it a very balanced dataset. Each sample is characterized by four features (or dimensions): sepal length, sepal width, petal length, petal width.

[2]:
# Load the iris dataset
data = load_iris()

# Store the features as X and the labels as y
X = data.data
y = data.target

Constructing a custom objective function

Recall that neural networks can simply be seen as a mapping function from one space to another. For now, we’ll build a simple neural network with the following characteristics: * Input layer size: 4 * Hidden layer size: 20 (activation: \(\tanh(x)\)) * Output layer size: 3 (activation: \(softmax(x)\))

Things we’ll do: 1. Create a forward_prop method that will do forward propagation for one particle. 2. Create an overhead objective function f() that will compute forward_prop() for the whole swarm.

What we’ll be doing then is to create a swarm with a number of dimensions equal to the weights and biases. We will unroll these parameters into an n-dimensional array, and have each particle take on different values. Thus, each particle represents a candidate neural network with its own weights and bias. When feeding back to the network, we will reconstruct the learned weights and biases.

When rolling-back the parameters into weights and biases, it is useful to recall the shape and bias matrices: * Shape of input-to-hidden weight matrix: (4, 20) * Shape of input-to-hidden bias array: (20, ) * Shape of hidden-to-output weight matrix: (20, 3) * Shape of hidden-to-output bias array: (3, )

By unrolling them together, we have \((4 * 20) + (20 * 3) + 20 + 3 = 163\) parameters, or 163 dimensions for each particle in the swarm.

The negative log-likelihood will be used to compute for the error between the ground-truth values and the predictions. Also, because PSO doesn’t rely on the gradients, we’ll not be performing backpropagation (this may be a good thing or bad thing under some circumstances).

Now, let’s write the forward propagation procedure as our objective function. Let \(X\) be the input, \(z_l\) the pre-activation at layer \(l\), and \(a_l\) the activation for layer \(l\):

[3]:
# Forward propagation
def forward_prop(params):
    """Forward propagation as objective function

    This computes for the forward propagation of the neural network, as
    well as the loss. It receives a set of parameters that must be
    rolled-back into the corresponding weights and biases.

    Inputs
    ------
    params: np.ndarray
        The dimensions should include an unrolled version of the
        weights and biases.

    Returns
    -------
    float
        The computed negative log-likelihood loss given the parameters
    """
    # Neural network architecture
    n_inputs = 4
    n_hidden = 20
    n_classes = 3

    # Roll-back the weights and biases
    W1 = params[0:80].reshape((n_inputs,n_hidden))
    b1 = params[80:100].reshape((n_hidden,))
    W2 = params[100:160].reshape((n_hidden,n_classes))
    b2 = params[160:163].reshape((n_classes,))

    # Perform forward propagation
    z1 = X.dot(W1) + b1  # Pre-activation in Layer 1
    a1 = np.tanh(z1)     # Activation in Layer 1
    z2 = a1.dot(W2) + b2 # Pre-activation in Layer 2
    logits = z2          # Logits for Layer 2

    # Compute for the softmax of the logits
    exp_scores = np.exp(logits)
    probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True)

    # Compute for the negative log likelihood
    N = 150 # Number of samples
    corect_logprobs = -np.log(probs[range(N), y])
    loss = np.sum(corect_logprobs) / N

    return loss

Now that we have a method to do forward propagation for one particle (or for one set of dimensions), we can then create a higher-level method to compute forward_prop() to the whole swarm:

[4]:
def f(x):
    """Higher-level method to do forward_prop in the
    whole swarm.

    Inputs
    ------
    x: numpy.ndarray of shape (n_particles, dimensions)
        The swarm that will perform the search

    Returns
    -------
    numpy.ndarray of shape (n_particles, )
        The computed loss for each particle
    """
    n_particles = x.shape[0]
    j = [forward_prop(x[i]) for i in range(n_particles)]
    return np.array(j)

Performing PSO on the custom-function

Now that everything has been set-up, we just call our global-best PSO and run the optimizer as usual. For now, we’ll just set the PSO parameters arbitrarily.

[5]:
%%time
# Initialize swarm
options = {'c1': 0.5, 'c2': 0.3, 'w':0.9}

# Call instance of PSO
dimensions = (4 * 20) + (20 * 3) + 20 + 3
optimizer = ps.single.GlobalBestPSO(n_particles=100, dimensions=dimensions, options=options)

# Perform optimization
cost, pos = optimizer.optimize(f, iters=1000)
2019-05-18 15:41:57,877 - pyswarms.single.global_best - INFO - Optimize for 1000 iters with {'c1': 0.5, 'c2': 0.3, 'w': 0.9}
pyswarms.single.global_best: 100%|██████████|1000/1000, best_cost=0.0165
2019-05-18 15:42:31,581 - pyswarms.single.global_best - INFO - Optimization finished | best cost: 0.016531416872331766, best pos: [ 5.85443277e-01  3.18983187e-01  4.87616029e+00  6.92819686e-01
  5.91348094e-01 -1.47072755e+00 -3.87333270e-01  2.28078097e-01
  5.64760071e-01 -7.56088270e-01  6.87331448e-01  2.88151297e-02
  3.31349600e-01 -1.59924694e+00  4.67166210e-02 -1.12181711e+00
 -1.46116999e+00  8.28885848e-02 -5.87848222e-01  4.84650773e-01
  7.25055845e-01  1.60319161e+00  1.01734077e+00  6.77151277e-01
  4.68472188e-01 -2.03064036e+00  6.04853725e-01  8.69137842e-01
  3.37968541e-02  7.35966984e+00  3.77854618e-01  5.39704445e-01
 -3.18805135e-01  3.98886841e-01  1.35014252e+00  6.30151934e-01
 -9.89671205e+00  5.30611778e-01 -3.94029130e-01  1.28325712e+00
  4.00896282e-01  1.44504447e+00  4.80281265e-02 -2.23726897e+00
 -1.30647406e+00 -1.22876659e+00  1.05121523e+00  1.65897010e-02
 -3.01271564e-01  7.11549766e-01 -4.30742366e-01 -8.79857761e-01
  4.65148904e-01  2.68559029e+00 -8.19525838e-01  1.54207613e+00
  1.11130818e+00 -1.00668214e+00  1.34198293e+00  1.37349242e+00
  8.63633177e-01  7.71218636e-01 -3.24648088e+00 -2.77803089e-01
  5.61820577e-01  3.60558056e-01 -1.84423615e-01  7.31299682e-01
 -2.70701588e-01  7.40742860e-01 -2.04198406e-01 -3.40162714e+00
 -1.63934080e+00  4.25175361e-01 -5.64146954e-01  9.32478016e-03
  3.21352295e+01 -1.70581217e-02  2.82477110e-03 -6.18616886e-01
  1.38075445e+00  4.79120594e-01 -1.38986251e+00  1.08695023e+00
 -3.27381335e-01 -1.88859617e+00  5.74757420e-03  3.17290632e-01
 -3.38194174e-01 -7.56263717e-01 -1.99762849e-01  1.48606896e+00
  1.33930708e+00  6.64423514e-01 -3.54654570e-01 -5.97853941e-02
 -2.37687453e+01  2.72228437e+00  1.06655131e+00  6.82690854e-01
  2.31485658e+00 -1.52431864e+00 -3.59092541e-01  2.86005282e+00
  6.34208138e-01 -4.77038443e-02 -2.15260265e-01  1.02182659e+00
  9.64123957e-03  1.81348424e+00  1.23999239e+00 -8.64817004e-01
  7.99587790e-01 -6.65369364e-01 -1.19005701e+00  6.56194773e-01
 -7.91411474e-01 -1.28616596e+00 -1.17059974e-01  1.58063399e+00
 -5.29152828e-02  7.20523887e-01 -7.31449869e-01 -1.91568507e+00
  8.65212737e-02  2.90227497e-01 -1.89333200e+00  5.57458851e-01
  3.49374578e-01 -1.87458746e-01 -9.91365971e-01  3.19524629e-01
  2.94593616e-01  1.04852932e+00 -8.21094379e-01 -8.56035315e-02
 -1.11249671e-02 -1.51713779e+00 -1.72314444e-01 -2.63524712e+00
  4.20163362e-01 -1.69099999e+00  1.12468986e+00  7.20661344e-01
 -6.21266399e-01 -2.27307898e+00 -1.14414646e+00  2.82661220e+00
 -5.48558830e-01  6.14762373e-01  6.30690474e+00  2.65412287e+00
  2.57065658e+00 -1.15195847e+01 -1.70542094e+00  9.64484168e-01
  7.66919284e-01  6.93106240e-01  2.34685030e+00  1.86609454e+00
 -7.14644033e-01  7.41293434e-01 -2.36930354e-01]
CPU times: user 23.8 s, sys: 488 ms, total: 24.3 s
Wall time: 33.7 s

Checking the accuracy

We can then check the accuracy by performing forward propagation once again to create a set of predictions. Then it’s only a simple matter of matching which one’s correct or not. For the logits, we take the argmax. Recall that the softmax function returns probabilities where the whole vector sums to 1. We just take the one with the highest probability then treat it as the network’s prediction.

Moreover, we let the best position vector found by the swarm be the weight and bias parameters of the network.

[6]:
def predict(X, pos):
    """
    Use the trained weights to perform class predictions.

    Inputs
    ------
    X: numpy.ndarray
        Input Iris dataset
    pos: numpy.ndarray
        Position matrix found by the swarm. Will be rolled
        into weights and biases.
    """
    # Neural network architecture
    n_inputs = 4
    n_hidden = 20
    n_classes = 3

    # Roll-back the weights and biases
    W1 = pos[0:80].reshape((n_inputs,n_hidden))
    b1 = pos[80:100].reshape((n_hidden,))
    W2 = pos[100:160].reshape((n_hidden,n_classes))
    b2 = pos[160:163].reshape((n_classes,))

    # Perform forward propagation
    z1 = X.dot(W1) + b1  # Pre-activation in Layer 1
    a1 = np.tanh(z1)     # Activation in Layer 1
    z2 = a1.dot(W2) + b2 # Pre-activation in Layer 2
    logits = z2          # Logits for Layer 2

    y_pred = np.argmax(logits, axis=1)
    return y_pred

And from this we can just compute for the accuracy. We perform predictions, compare an equivalence to the ground-truth value y, and get the mean.

[7]:
(predict(X, pos) == y).mean()
[7]:
0.9866666666666667