**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.

## Tutorial Overview

This tutorial is divided into three parts; they are:

- Optimize Neural Networks
- Optimize a Perceptron Model
- 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.

1 2 3 4 5 6 |
# define a binary classification dataset from sklearn.datasets import make_classification # define dataset X, y = make_classification(n_samples=1000, n_features=5, n_informative=2, n_redundant=1, random_state=1) # summarize the shape of the dataset print(X.shape, y.shape) |

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

1 |
(1000, 5) (1000,) |

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.

1 2 3 4 5 |
# transfer function def transfer(activation): if activation >= 0.0: return 1 return 0 |

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.

1 2 3 4 5 6 7 8 |
# activation function def activate(row, weights): # add the bias, the last weight activation = weights[-1] # add the weighted input for i in range(len(row)): activation += weights[i] * row[i] return activation |

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.

1 2 3 4 5 6 |
# use model weights to predict 0 or 1 for a given row of data def predict_row(row, weights): # activate for input activation = activate(row, weights) # transfer for activation return transfer(activation) |

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.

1 2 3 4 5 6 7 |
# use model weights to generate predictions for a dataset of rows def predict_dataset(X, weights): yhats = list() for row in X: yhat = predict_row(row, weights) yhats.append(yhat) return yhats |

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.

1 2 3 4 5 6 7 |
... # define dataset X, y = make_classification(n_samples=1000, n_features=5, n_informative=2, n_redundant=1, random_state=1) # determine the number of weights n_weights = X.shape[1] + 1 # generate random weights weights = rand(n_weights) |

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

1 2 3 |
... # generate predictions for dataset yhat = predict_dataset(X, weights) |

We can evaluate the classification accuracy of these predictions.

1 2 3 4 |
... # calculate accuracy score = accuracy_score(y, yhat) print(score) |

That’s it.

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# simple perceptron model for binary classification from numpy.random import rand from sklearn.datasets import make_classification from sklearn.metrics import accuracy_score # transfer function def transfer(activation): if activation >= 0.0: return 1 return 0 # activation function def activate(row, weights): # add the bias, the last weight activation = weights[-1] # add the weighted input for i in range(len(row)): activation += weights[i] * row[i] return activation # use model weights to predict 0 or 1 for a given row of data def predict_row(row, weights): # activate for input activation = activate(row, weights) # transfer for activation return transfer(activation) # use model weights to generate predictions for a dataset of rows def predict_dataset(X, weights): yhats = list() for row in X: yhat = predict_row(row, weights) yhats.append(yhat) return yhats # define dataset X, y = make_classification(n_samples=1000, n_features=5, n_informative=2, n_redundant=1, random_state=1) # determine the number of weights n_weights = X.shape[1] + 1 # generate random weights weights = rand(n_weights) # generate predictions for dataset yhat = predict_dataset(X, weights) # calculate accuracy score = accuracy_score(y, yhat) print(score) |

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.

1 |
0.548 |

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.

1 2 3 |
... # split into train test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) |

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

1 2 3 4 5 6 7 |
# objective function def objective(X, y, weights): # generate predictions for dataset yhat = predict_dataset(X, weights) # calculate accuracy score = accuracy_score(y, yhat) return score |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# hill climbing local search algorithm def hillclimbing(X, y, objective, solution, n_iter, step_size): # evaluate the initial point solution_eval = objective(X, y, solution) # run the hill climb for i in range(n_iter): # take a step candidate = solution + randn(len(solution)) * step_size # evaluate candidate point candidte_eval = objective(X, y, candidate) # check if we should keep the new point if candidte_eval >= solution_eval: # store the new point solution, solution_eval = candidate, candidte_eval # report progress print('>%d %.5f' % (i, solution_eval)) return [solution, solution_eval] |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 |
... # define the total iterations n_iter = 1000 # define the maximum step size step_size = 0.05 # determine the number of weights n_weights = X.shape[1] + 1 # define the initial solution solution = rand(n_weights) # perform the hill climbing search weights, score = hillclimbing(X_train, y_train, objective, solution, n_iter, step_size) print('Done!') print('f(%s) = %f' % (weights, score)) |

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

1 2 3 4 5 6 |
... # generate predictions for the test dataset yhat = predict_dataset(X_test, weights) # calculate accuracy score = accuracy_score(y_test, yhat) print('Test Accuracy: %.5f' % (score * 100)) |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# hill climbing to optimize weights of a perceptron model for classification from numpy import asarray from numpy.random import randn from numpy.random import rand from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # transfer function def transfer(activation): if activation >= 0.0: return 1 return 0 # activation function def activate(row, weights): # add the bias, the last weight activation = weights[-1] # add the weighted input for i in range(len(row)): activation += weights[i] * row[i] return activation # # use model weights to predict 0 or 1 for a given row of data def predict_row(row, weights): # activate for input activation = activate(row, weights) # transfer for activation return transfer(activation) # use model weights to generate predictions for a dataset of rows def predict_dataset(X, weights): yhats = list() for row in X: yhat = predict_row(row, weights) yhats.append(yhat) return yhats # objective function def objective(X, y, weights): # generate predictions for dataset yhat = predict_dataset(X, weights) # calculate accuracy score = accuracy_score(y, yhat) return score # hill climbing local search algorithm def hillclimbing(X, y, objective, solution, n_iter, step_size): # evaluate the initial point solution_eval = objective(X, y, solution) # run the hill climb for i in range(n_iter): # take a step candidate = solution + randn(len(solution)) * step_size # evaluate candidate point candidte_eval = objective(X, y, candidate) # check if we should keep the new point if candidte_eval >= solution_eval: # store the new point solution, solution_eval = candidate, candidte_eval # report progress print('>%d %.5f' % (i, solution_eval)) return [solution, solution_eval] # define dataset # split into train test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) # define the total iterations n_iter = 1000 # define the maximum step size step_size = 0.05 # determine the number of weights n_weights = X.shape[1] + 1 # define the initial solution solution = rand(n_weights) # perform the hill climbing search weights, score = hillclimbing(X_train, y_train, objective, solution, n_iter, step_size) print('Done!') print('f(%s) = %f' % (weights, score)) # generate predictions for the test dataset yhat = predict_dataset(X_test, weights) # calculate accuracy score = accuracy_score(y_test, yhat) print('Test Accuracy: %.5f' % (score * 100)) |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
... >111 0.88060 >119 0.88060 >126 0.88209 >134 0.88209 >205 0.88209 >262 0.88209 >280 0.88209 >293 0.88209 >297 0.88209 >336 0.88209 >373 0.88209 >437 0.88358 >463 0.88507 >630 0.88507 >701 0.88507 Done! f([ 0.0097317 0.13818088 1.17634326 -0.04296336 0.00485813 -0.14767616]) = 0.885075 Test Accuracy: 81.81818 |

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.

1 2 3 4 |
# transfer function def transfer(activation): # sigmoid transfer function return 1.0 / (1.0 + exp(-activation)) |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# activation function for a network def predict_row(row, network): inputs = row # enumerate the layers in the network from input to output for layer in network: new_inputs = list() # enumerate nodes in the layer for node in layer: # activate the node activation = activate(inputs, node) # transfer activation output = transfer(activation) # store output new_inputs.append(output) # output from this layer is input to the next layer inputs = new_inputs return inputs[0] |

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:

1 2 3 4 5 |
... # create a one node network node = rand(n_inputs + 1) layer = [node] network = [layer] |

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.

1 2 3 4 5 6 |
... # one hidden layer and an output layer n_hidden = 10 hidden1 = [rand(n_inputs + 1) for _ in range(n_hidden)] output1 = [rand(n_hidden + 1)] network = [hidden1, output1] |

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

1 2 3 |
... # generate predictions for dataset yhat = predict_dataset(X, network) |

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

1 2 3 4 5 6 |
... # round the predictions yhat = [round(y) for y in yhat] # calculate accuracy score = accuracy_score(y, yhat) print(score) |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# develop an mlp model for classification from math import exp from numpy.random import rand from sklearn.datasets import make_classification from sklearn.metrics import accuracy_score # transfer function def transfer(activation): # sigmoid transfer function return 1.0 / (1.0 + exp(-activation)) # activation function def activate(row, weights): # add the bias, the last weight activation = weights[-1] # add the weighted input for i in range(len(row)): activation += weights[i] * row[i] return activation # activation function for a network def predict_row(row, network): inputs = row # enumerate the layers in the network from input to output for layer in network: new_inputs = list() # enumerate nodes in the layer for node in layer: # activate the node activation = activate(inputs, node) # transfer activation output = transfer(activation) # store output new_inputs.append(output) # output from this layer is input to the next layer inputs = new_inputs return inputs[0] # use model weights to generate predictions for a dataset of rows def predict_dataset(X, network): yhats = list() for row in X: yhat = predict_row(row, network) yhats.append(yhat) return yhats # define dataset # determine the number of inputs n_inputs = X.shape[1] # one hidden layer and an output layer n_hidden = 10 hidden1 = [rand(n_inputs + 1) for _ in range(n_hidden)] output1 = [rand(n_hidden + 1)] network = [hidden1, output1] # generate predictions for dataset yhat = predict_dataset(X, network) # round the predictions yhat = [round(y) for y in yhat] # calculate accuracy score = accuracy_score(y, yhat) print(score) |

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.

1 |
0.499 |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# take a step in the search space def step(network, step_size): new_net = list() # enumerate layers in the network for layer in network: new_layer = list() # enumerate nodes in this layer for node in layer: # mutate the node new_node = node.copy() + randn(len(node)) * step_size # store node in layer new_layer.append(new_node) # store layer in network new_net.append(new_layer) return new_net |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# hill climbing local search algorithm def hillclimbing(X, y, objective, solution, n_iter, step_size): # evaluate the initial point solution_eval = objective(X, y, solution) # run the hill climb for i in range(n_iter): # take a step candidate = step(solution, step_size) # evaluate candidate point candidte_eval = objective(X, y, candidate) # check if we should keep the new point if candidte_eval >= solution_eval: # store the new point solution, solution_eval = candidate, candidte_eval # report progress print('>%d %f' % (i, solution_eval)) return [solution, solution_eval] |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# stochastic hill climbing to optimize a multilayer perceptron for classification from math import exp from numpy.random import randn from numpy.random import rand from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # transfer function def transfer(activation): # sigmoid transfer function return 1.0 / (1.0 + exp(-activation)) # activation function def activate(row, weights): # add the bias, the last weight activation = weights[-1] # add the weighted input for i in range(len(row)): activation += weights[i] * row[i] return activation # activation function for a network def predict_row(row, network): inputs = row # enumerate the layers in the network from input to output for layer in network: new_inputs = list() # enumerate nodes in the layer for node in layer: # activate the node activation = activate(inputs, node) # transfer activation output = transfer(activation) # store output new_inputs.append(output) # output from this layer is input to the next layer inputs = new_inputs return inputs[0] # use model weights to generate predictions for a dataset of rows def predict_dataset(X, network): yhats = list() for row in X: yhat = predict_row(row, network) yhats.append(yhat) return yhats # objective function def objective(X, y, network): # generate predictions for dataset yhat = predict_dataset(X, network) # round the predictions yhat = [round(y) for y in yhat] # calculate accuracy score = accuracy_score(y, yhat) return score # take a step in the search space def step(network, step_size): new_net = list() # enumerate layers in the network for layer in network: new_layer = list() # enumerate nodes in this layer for node in layer: # mutate the node new_node = node.copy() + randn(len(node)) * step_size # store node in layer new_layer.append(new_node) # store layer in network new_net.append(new_layer) return new_net # hill climbing local search algorithm def hillclimbing(X, y, objective, solution, n_iter, step_size): # evaluate the initial point solution_eval = objective(X, y, solution) # run the hill climb for i in range(n_iter): # take a step candidate = step(solution, step_size) # evaluate candidate point candidte_eval = objective(X, y, candidate) # check if we should keep the new point if candidte_eval >= solution_eval: # store the new point solution, solution_eval = candidate, candidte_eval # report progress print('>%d %f' % (i, solution_eval)) return [solution, solution_eval] # define dataset # split into train test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33) # define the total iterations n_iter = 1000 # define the maximum step size step_size = 0.1 # determine the number of inputs n_inputs = X.shape[1] # one hidden layer and an output layer n_hidden = 10 hidden1 = [rand(n_inputs + 1) for _ in range(n_hidden)] output1 = [rand(n_hidden + 1)] network = [hidden1, output1] # perform the hill climbing search network, score = hillclimbing(X_train, y_train, objective, network, n_iter, step_size) print('Done!') print('Best: %f' % (score)) # generate predictions for the test dataset yhat = predict_dataset(X_test, network) # round the predictions yhat = [round(y) for y in yhat] # calculate accuracy score = accuracy_score(y_test, yhat) print('Test Accuracy: %.5f' % (score * 100)) |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
... >55 0.755224 >56 0.765672 >59 0.794030 >66 0.805970 >77 0.835821 >120 0.838806 >165 0.840299 >188 0.841791 >218 0.846269 >232 0.852239 >237 0.852239 >239 0.855224 >292 0.867164 >368 0.868657 >823 0.868657 >852 0.871642 >889 0.871642 >892 0.871642 >992 0.873134 Done! Best: 0.873134 Test Accuracy: 85.15152 |

## Further Reading

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

### Tutorials

- Train-Test Split for Evaluating Machine Learning Algorithms
- How To Implement The Perceptron Algorithm From Scratch In Python
- How to Code a Neural Network with Backpropagation In Python (from scratch)

### APIs

- sklearn.datasets.make_classification APIs.
- sklearn.metrics.accuracy_score APIs.
- numpy.random.rand API.

## 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.

Useful code. Thank you

Thanks!

Good article, gave insight about neural networks Thanks!!

Thanks.

Hello Jason, great article!!

Could you do the same for an LSTM network?

Sure!

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.

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

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?

Sure.

how I can use an Artificial neural network to solve an optimization problem.

Thank you in advance for your answer

Can you give an example of your optimization problem?

Great work sir, thank you.