How to Manually Optimize Neural Network Models

Deep learning neural network models are fit on training data using the stochastic gradient descent optimization algorithm.

Updates to the weights of the model are made, using the backpropagation of error algorithm. The combination of the optimization and weight update algorithm was carefully chosen and is the most efficient approach known to fit neural networks.

Nevertheless, it is possible to use alternate optimization algorithms to fit a neural network model to a training dataset. This can be a useful exercise to learn more about how neural networks function and the central nature of optimization in applied machine learning. It may also be required for neural networks with unconventional model architectures and non-differentiable transfer functions.

In this tutorial, you will discover how to manually optimize the weights of neural network models.

After completing this tutorial, you will know:

  • How to develop the forward inference pass for neural network models from scratch.
  • How to optimize the weights of a Perceptron model for binary classification.
  • How to optimize the weights of a Multilayer Perceptron model using stochastic hill climbing.

Kick-start your project with my new book Optimization for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

Let’s get started.

How to Manually Optimize Neural Network Models

How to Manually Optimize Neural Network Models
Photo by Bureau of Land Management, some rights reserved.

Tutorial Overview

This tutorial is divided into three parts; they are:

  1. Optimize Neural Networks
  2. Optimize a Perceptron Model
  3. Optimize a Multilayer Perceptron

Optimize Neural Networks

Deep learning or neural networks are a flexible type of machine learning.

They are models composed of nodes and layers inspired by the structure and function of the brain. A neural network model works by propagating a given input vector through one or more layers to produce a numeric output that can be interpreted for classification or regression predictive modeling.

Models are trained by repeatedly exposing the model to examples of input and output and adjusting the weights to minimize the error of the model’s output compared to the expected output. This is called the stochastic gradient descent optimization algorithm. The weights of the model are adjusted using a specific rule from calculus that assigns error proportionally to each weight in the network. This is called the backpropagation algorithm.

The stochastic gradient descent optimization algorithm with weight updates made using backpropagation is the best way to train neural network models. However, it is not the only way to train a neural network.

It is possible to use any arbitrary optimization algorithm to train a neural network model.

That is, we can define a neural network model architecture and use a given optimization algorithm to find a set of weights for the model that results in a minimum of prediction error or a maximum of classification accuracy.

Using alternate optimization algorithms is expected to be less efficient on average than using stochastic gradient descent with backpropagation. Nevertheless, it may be more efficient in some specific cases, such as non-standard network architectures or non-differential transfer functions.

It can also be an interesting exercise to demonstrate the central nature of optimization in training machine learning algorithms, and specifically neural networks.

Next, let’s explore how to train a simple one-node neural network called a Perceptron model using stochastic hill climbing.

Want to Get Started With Optimization Algorithms?

Take my free 7-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

Optimize a Perceptron Model

The Perceptron algorithm is the simplest type of artificial neural network.

It is a model of a single neuron that can be used for two-class classification problems and provides the foundation for later developing much larger networks.

In this section, we will optimize the weights of a Perceptron neural network model.

First, let’s define a synthetic binary classification problem that we can use as the focus of optimizing the model.

We can use the make_classification() function to define a binary classification problem with 1,000 rows and five input variables.

The example below creates the dataset and summarizes the shape of the data.

Running the example prints the shape of the created dataset, confirming our expectations.

Next, we need to define a Perceptron model.

The Perceptron model has a single node that has one input weight for each column in the dataset.

Each input is multiplied by its corresponding weight to give a weighted sum and a bias weight is then added, like an intercept coefficient in a regression model. This weighted sum is called the activation. Finally, the activation is interpreted and used to predict the class label, 1 for a positive activation and 0 for a negative activation.

Before we optimize the model weights, we must develop the model and our confidence in how it works.

Let’s start by defining a function for interpreting the activation of the model.

This is called the activation function, or the transfer function; the latter name is more traditional and is my preference.

The transfer() function below takes the activation of the model and returns a class label, class=1 for a positive or zero activation and class=0 for a negative activation. This is called a step transfer function.

Next, we can develop a function that calculates the activation of the model for a given input row of data from the dataset.

This function will take the row of data and the weights for the model and calculate the weighted sum of the input with the addition of the bias weight. The activate() function below implements this.

Note: We are using simple Python lists and imperative programming style instead of NumPy arrays or list compressions intentionally to make the code more readable for Python beginners. Feel free to optimize it and post your code in the comments below.

Next, we can use the activate() and transfer() functions together to generate a prediction for a given row of data. The predict_row() function below implements this.

Next, we can call the predict_row() function for each row in a given dataset. The predict_dataset() function below implements this.

Again, we are intentionally using simple imperative coding style for readability instead of list compressions.

Finally, we can use the model to make predictions on our synthetic dataset to confirm it is all working correctly.

We can generate a random set of model weights using the rand() function.

Recall that we need one weight for each input (five inputs in this dataset) plus an extra weight for the bias weight.

We can then use these weights with the dataset to make predictions.

We can evaluate the classification accuracy of these predictions.

That’s it.

We can tie all of this together and demonstrate our simple Perceptron model for classification. The complete example is listed below.

Running the example generates a prediction for each example in the training dataset then prints the classification accuracy for the predictions.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

We would expect about 50 percent accuracy given a set of random weights and a dataset with an equal number of examples in each class, and that is approximately what we see in this case.

We can now optimize the weights of the dataset to achieve good accuracy on this dataset.

First, we need to split the dataset into train and test sets. It is important to hold back some data not used in optimizing the model so that we can prepare a reasonable estimate of the performance of the model when used to make predictions on new data.

We will use 67 percent of the data for training and the remaining 33 percent as a test set for evaluating the performance of the model.

Next, we can develop a stochastic hill climbing algorithm.

The optimization algorithm requires an objective function to optimize. It must take a set of weights and return a score that is to be minimized or maximized corresponding to a better model.

In this case, we will evaluate the accuracy of the model with a given set of weights and return the classification accuracy, which must be maximized.

The objective() function below implements this, given the dataset and a set of weights, and returns the accuracy of the model

Next, we can define the stochastic hill climbing algorithm.

The algorithm will require an initial solution (e.g. random weights) and will iteratively keep making small changes to the solution and checking if it results in a better performing model. The amount of change made to the current solution is controlled by a step_size hyperparameter. This process will continue for a fixed number of iterations, also provided as a hyperparameter.

The hillclimbing() function below implements this, taking the dataset, objective function, initial solution, and hyperparameters as arguments and returns the best set of weights found and the estimated performance.

We can then call this function, passing in a set of weights as the initial solution and the training dataset as the dataset to optimize the model against.

Finally, we can evaluate the best model on the test dataset and report the performance.

Tying this together, the complete example of optimizing the weights of a Perceptron model on the synthetic binary optimization dataset is listed below.

Running the example will report the iteration number and classification accuracy each time there is an improvement made to the model.

At the end of the search, the performance of the best set of weights on the training dataset is reported and the performance of the same model on the test dataset is calculated and reported.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, we can see that the optimization algorithm found a set of weights that achieved about 88.5 percent accuracy on the training dataset and about 81.8 percent accuracy on the test dataset.

Now that we are familiar with how to manually optimize the weights of a Perceptron model, let’s look at how we can extend the example to optimize the weights of a Multilayer Perceptron (MLP) model.

Optimize a Multilayer Perceptron

A Multilayer Perceptron (MLP) model is a neural network with one or more layers, where each layer has one or more nodes.

It is an extension of a Perceptron model and is perhaps the most widely used neural network (deep learning) model.

In this section, we will build on what we learned in the previous section to optimize the weights of MLP models with an arbitrary number of layers and nodes per layer.

First, we will develop the model and test it with random weights, then use stochastic hill climbing to optimize the model weights.

When using MLPs for binary classification, it is common to use a sigmoid transfer function (also called the logistic function) instead of the step transfer function used in the Perceptron.

This function outputs a real-value between 0-1 that represents a binomial probability distribution, e.g. the probability that an example belongs to class=1. The transfer() function below implements this.

We can use the same activate() function from the previous section. Here, we will use it to calculate the activation for each node in a given layer.

The predict_row() function must be replaced with a more elaborate version.

The function takes a row of data and the network and returns the output of the network.

We will define our network as a list of lists. Each layer will be a list of nodes and each node will be a list or array of weights.

To calculate the prediction of the network, we simply enumerate the layers, then enumerate nodes, then calculate the activation and transfer output for each node. In this case, we will use the same transfer function for all nodes in the network, although this does not have to be the case.

For networks with more than one layer, the output from the previous layer is used as input to each node in the next layer. The output from the final layer in the network is then returned.

The predict_row() function below implements this.

That’s about it.

Finally, we need to define a network to use.

For example, we can define an MLP with a single hidden layer with a single node as follows:

This is practically a Perceptron, although with a sigmoid transfer function. Quite boring.

Let’s define an MLP with one hidden layer and one output layer. The first hidden layer will have 10 nodes, and each node will take the input pattern from the dataset (e.g. five inputs). The output layer will have a single node that takes inputs from the outputs of the first hidden layer and then outputs a prediction.

We can then use the model to make predictions on the dataset.

Before we calculate the classification accuracy, we must round the predictions to class labels 0 and 1.

Tying this all together, the complete example of evaluating an MLP with random initial weights on our synthetic binary classification dataset is listed below.

Running the example generates a prediction for each example in the training dataset, then prints the classification accuracy for the predictions.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

Again, we would expect about 50 percent accuracy given a set of random weights and a dataset with an equal number of examples in each class, and that is approximately what we see in this case.

Next, we can apply the stochastic hill climbing algorithm to the dataset.

It is very much the same as applying hill climbing to the Perceptron model, except in this case, a step requires a modification to all weights in the network.

For this, we will develop a new function that creates a copy of the network and mutates each weight in the network while making the copy.

The step() function below implements this.

Modifying all weight in the network is aggressive.

A less aggressive step in the search space might be to make a small change to a subset of the weights in the model, perhaps controlled by a hyperparameter. This is left as an extension.

We can then call this new step() function from the hillclimbing() function.

Tying this together, the complete example of applying stochastic hill climbing to optimize the weights of an MLP model for binary classification is listed below.

Running the example will report the iteration number and classification accuracy each time there is an improvement made to the model.

At the end of the search, the performance of the best set of weights on the training dataset is reported and the performance of the same model on the test dataset is calculated and reported.

Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

In this case, we can see that the optimization algorithm found a set of weights that achieved about 87.3 percent accuracy on the training dataset and about 85.1 percent accuracy on the test dataset.

Further Reading

This section provides more resources on the topic if you are looking to go deeper.

Tutorials

APIs

Summary

In this tutorial, you discovered how to manually optimize the weights of neural network models.

Specifically, you learned:

  • How to develop the forward inference pass for neural network models from scratch.
  • How to optimize the weights of a Perceptron model for binary classification.
  • How to optimize the weights of a Multilayer Perceptron model using stochastic hill climbing.

Do you have any questions?
Ask your questions in the comments below and I will do my best to answer.

Get a Handle on Modern Optimization Algorithms!

Optimization for Maching Learning

Develop Your Understanding of Optimization

...with just a few lines of python code

Discover how in my new Ebook:
Optimization for Machine Learning

It provides self-study tutorials with full working code on:
Gradient Descent, Genetic Algorithms, Hill Climbing, Curve Fitting, RMSProp, Adam, and much more...

Bring Modern Optimization Algorithms to
Your Machine Learning Projects


See What's Inside

13 Responses to How to Manually Optimize Neural Network Models

  1. Rupesh Mahamune December 4, 2020 at 11:55 am #

    Useful code. Thank you

  2. Suraj December 5, 2020 at 6:52 pm #

    Good article, gave insight about neural networks Thanks!!

  3. Dexter December 7, 2020 at 10:28 am #

    Hello Jason, great article!!

    Could you do the same for an LSTM network?

    • Jason Brownlee December 7, 2020 at 1:35 pm #

      Sure!

      • Bibhuti December 18, 2020 at 12:45 am #

        Can you share anything about how to optimise neural network using PSO Or GA particularly for prediction regression task. I searched everywhere but didn’t get a good or proper explanation.

        • Jason Brownlee December 18, 2020 at 7:17 am #

          You can adapt the above example to use any optimization algorithm you like, like a GA or PSO.

  4. Andrew August 4, 2021 at 6:47 am #

    Hi Jason,

    Thanks so much for this. Could this optimization be extended to a CNN for use on a simple case test case such as the MNIST dataset?

  5. CHAYMAE MAKRI October 21, 2021 at 8:45 pm #

    how I can use an Artificial neural network to solve an optimization problem.
    Thank you in advance for your answer

    • Adrian Tam
      Adrian Tam October 22, 2021 at 4:11 am #

      Can you give an example of your optimization problem?

  6. Eshwar February 15, 2022 at 3:35 am #

    Great work sir, thank you.

Leave a Reply

Machine Learning Mastery is part of Guiding Tech Media, a leading digital media publisher focused on helping people figure out technology. Visit our corporate website to learn more about our mission and team.